Skip to content

Latest commit

 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

BitKit

Bit-level utilities for Swift. The companion package of the book Bit Magic: 64 bit-level techniques for Swift, one page each, checked against the compiler, by Ihor Malovanyi.

No dependencies, Swift 6. Three rules shaped it:

  1. Every function names the entry ("bit") of the book that explains it.
  2. Whatever can be misused says so with a precondition. A trap at the call site beats a quiet wrong answer three layers later.
  3. Nothing is here for completeness. What the standard library already does (nonzeroBitCount, byteSwapped, magnitude, min), the package does not wrap.

Swift is not C: overflow traps, shifts are "smart", unsigned values have no unary minus, and the operator table is different. The spellings that make the classic tricks correct in Swift (0 &- x, &<<, &- 1) are written once, here, in the form the optimizer recognizes: rotatedLeft(by:) still compiles to ror, bitReversed to rbit.

Install

dependencies: [
    .package(url: "https://github.com/ihormalovanyi/BitKit.git", from: "1.0.0"),
]

A tour

import BitKit

let x: UInt8 = 0b0101_1000

x.bits                                        // "0b0101_1000"
x.lowestSetBit.bits                           // "0b0000_1000"
x.clearingLowestSetBit.bits                   // "0b0101_0000"
Array(x.setBitPositions)                      // [3, 4, 6]
UInt16(0b10101_110011_00001).field(at: 5, width: 6)   // 0b110011

UInt64(1000).roundedUpToPowerOfTwo            // 1024
UInt64(1_000_000).decimalDigitCount           // 7
midpoint(Int.max, Int.max - 2)                // Int.max - 1, and no overflow on the way
UInt64(1).rotatedLeft(by: 65)                 // 2
UInt64(1).bitReversed                         // 1 << 63

What OptionSet is missing, and the type it could have been:

struct Permissions: OptionSet {
    let rawValue: UInt8
    static let read = Permissions(rawValue: 1 << 0)
    static let write = Permissions(rawValue: 1 << 1)
    static let execute = Permissions(rawValue: 1 << 2)
}
enum Style: Int, CaseIterable { case bold, italic, underline, strikethrough }

let permissions: Permissions = [.execute, .read]
permissions.members.map(\.rawValue)           // [1, 4]
permissions.subsets.count                     // 4

var style: EnumSet<Style> = [.underline, .bold]
style.insert(.italic)
"\(style)"                                    // "[.bold, .italic, .underline]"
EnumSet<Style>.all.rawValue                   // 0b1111

Larger pieces:

var rng = Xoshiro256StarStar(seed: 63)        // seedable: the same numbers on every run
var filter = BloomFilter(bitCount: 1 << 12, hashCount: 4)
for _ in 0..<100 { filter.insert(rng.next()) }

Morton.decode(Morton.encode(x: 640, y: 480)) == (640, 480)     // true
SWAR.parseEightDigits(0x3632_3032_3930_3931)                   // 19_092_026: the bytes of "19092026"

What is inside

File Contents
Bits.swift bits, lowMask, field(at:width:), replacingField, signExtend, BitField
Tricks.swift lowestSetBit, clearingLowestSetBit, isPowerOfTwo, roundedUpToPowerOfTwo, alignedUp, log2Floor, bitLength, decimalDigitCount, rotatedLeft, bitReversed, nextWithSamePopcount, submasks, setBitPositions, Gray codes, midpoint, ZigZag
OptionSets.swift members, subsets, EnumSet
BitSets.swift BitSet, FixedBitSet, SparseArray
SWAR.swift the SWAR and Morton namespaces
RandomAndHashing.swift SplitMix64, Xoshiro256StarStar, fmix64, BloomFilter
Formats.swift UTF-8 sequence length, LEB128, BitReader, Float.sortKey, hammingDistance

Notes

  • FixedBitSet stores its words inline in an InlineArray, so it needs the OS 26 generation of Apple platforms. Everything else runs on macOS 13, iOS 16 and later.
  • SplitMix64 and Xoshiro256StarStar are for simulations, tests and games. They are not cryptographically secure.
  • Found a mistake? Please open an issue.

License

MIT. Copyright © 2026 Ihor Malovanyi.

GitHub · LinkedIn

About

Bit-level utilities for Swift: the companion package of the book Bit Magic. No dependencies.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages