oscbyspro / AwesomeNumbersKit

Large number arithmetic in Swift
Apache License 2.0
7 stars 1 forks source link

Fixed-width bitwise inverse of `isZero` #104

Closed oscbyspro closed 1 year ago

oscbyspro commented 1 year ago

As mentioned in (#103), I've found some value in the bitwise inverse isZero.

extension ANKFixedWidthInteger {

    /// Returns whether all its bits are set, in two's complement form.
    ///
    /// The returned value can be viewed as the bitwise inverse of ``isZero``.
    ///
    /// ```swift
    ///  Int8(0b_1111_1111).isFull // true
    /// UInt8(0b_1111_1111).isFull // true
    ///  Int8(0b_1111_1110).isFull // false
    /// UInt8(0b_1111_1110).isFull // false
    /// ```
    ///
    @_transparent public var isFull: Bool {
        nonzeroBitCount == bitWidth 
        // OR self == ~(0 as Self)
        // OR low.isFull && high.isFull
    }
}
oscbyspro commented 1 year ago

Hm. I believe I want this—not necessarily because isFull is the most useful thing ever made, but because I need an efficient, non-allocating, way of matching a repeating bit. I've played with the following, and I find it easy to reason about. I mean, I already have init(repeating:) because it comes up a lot:

@_transparent public func matches(repeating bit: Bool) -> Bool {
    bit ? isFull : isZero
}
oscbyspro commented 1 year ago

I admit that isFull sounds like is collection property, relating in some way to isEmpty. Having said that, it makes sense considering an isFull integer cannot be modified by the OR operator.