From 59b5f647200b61dd996a6c4aec21b11ea517b6d2 Mon Sep 17 00:00:00 2001 From: Justin Mazzocchi <2831158+jzzocc@users.noreply.github.com> Date: Sun, 13 Sep 2020 02:06:52 -0700 Subject: [PATCH] Simplify bit array --- .../Sources/CodableBloomFilter/BitArray.swift | 23 +++---------------- 1 file changed, 3 insertions(+), 20 deletions(-) diff --git a/CodableBloomFilter/Sources/CodableBloomFilter/BitArray.swift b/CodableBloomFilter/Sources/CodableBloomFilter/BitArray.swift index f0cc651..736b160 100644 --- a/CodableBloomFilter/Sources/CodableBloomFilter/BitArray.swift +++ b/CodableBloomFilter/Sources/CodableBloomFilter/BitArray.swift @@ -1,7 +1,5 @@ // Copyright © 2020 Metabolist. All rights reserved. -// Adapted from https://github.com/dduan/BitArray - import Foundation struct BitArray { @@ -19,13 +17,13 @@ extension BitArray { subscript(index: Int) -> Bool { get { - let (byteIndex, bitIndex) = Self.byteAndBitIndices(index: index) + let (byteIndex, bitIndex) = index.quotientAndRemainder(dividingBy: Self.bitsInByte) return bytes[byteIndex] & Self.mask(bitIndex: bitIndex) > 0 } set { - let (byteIndex, bitIndex) = Self.byteAndBitIndices(index: index) + let (byteIndex, bitIndex) = index.quotientAndRemainder(dividingBy: Self.bitsInByte) if newValue { bytes[byteIndex] |= Self.mask(bitIndex: bitIndex) @@ -51,22 +49,7 @@ extension BitArray: Codable { private extension BitArray { static let bitsInByte = 8 - static func byteAndBitIndices(index: Int) -> (Int, Int) { - index.quotientAndRemainder(dividingBy: bitsInByte) - } - static func mask(bitIndex: Int) -> UInt8 { - switch bitIndex { - case 0: return 0b00000001 - case 1: return 0b00000010 - case 2: return 0b00000100 - case 3: return 0b00001000 - case 4: return 0b00010000 - case 5: return 0b00100000 - case 6: return 0b01000000 - case 7: return 0b10000000 - default: - fatalError("Invalid bit index: \(bitIndex)") - } + UInt8(2 << (bitIndex - 1)) } }