2022-07-18 11:02:40 +00:00
|
|
|
# Copyright (c) 2019-2022 Status Research & Development GmbH
|
|
|
|
# Licensed and distributed under either of
|
|
|
|
# * MIT license: http://opensource.org/licenses/MIT
|
|
|
|
# * Apache License, Version 2.0: http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
# at your option. This file may not be copied, modified, or distributed except according to those terms.
|
|
|
|
|
|
|
|
{.used.}
|
|
|
|
|
2019-07-30 23:11:12 +00:00
|
|
|
import
|
2022-07-08 09:34:21 +00:00
|
|
|
unittest2, strformat,
|
2019-12-20 12:23:30 +00:00
|
|
|
../stew/[bitseqs]
|
2019-07-30 23:11:12 +00:00
|
|
|
|
|
|
|
suite "Bit fields":
|
|
|
|
test "roundtrips":
|
|
|
|
var
|
|
|
|
a = BitSeq.init(100)
|
|
|
|
b = BitSeq.init(100)
|
|
|
|
|
|
|
|
check:
|
|
|
|
not a[0]
|
|
|
|
|
2019-12-20 12:23:30 +00:00
|
|
|
a.setBit 1
|
2019-07-30 23:11:12 +00:00
|
|
|
|
|
|
|
check:
|
|
|
|
not a[0]
|
|
|
|
a[1]
|
|
|
|
|
2019-12-20 12:23:30 +00:00
|
|
|
b.setBit 2
|
2019-07-30 23:11:12 +00:00
|
|
|
|
|
|
|
a.combine(b)
|
|
|
|
|
|
|
|
check:
|
|
|
|
not a[0]
|
|
|
|
a[1]
|
|
|
|
a[2]
|
2019-08-06 18:02:03 +00:00
|
|
|
|
|
|
|
test "iterating words":
|
|
|
|
for bitCount in [8, 3, 7, 8, 14, 15, 16, 19, 260]:
|
|
|
|
checkpoint &"trying bit count {bitCount}"
|
|
|
|
var
|
|
|
|
a = BitSeq.init(bitCount)
|
|
|
|
b = BitSeq.init(bitCount)
|
|
|
|
bitsInWord = sizeof(uint) * 8
|
|
|
|
expectedWordCount = (bitCount div bitsInWord) + 1
|
|
|
|
|
|
|
|
for i in 0 ..< expectedWordCount:
|
|
|
|
let every3rdBit = i * sizeof(uint) * 8 + 2
|
|
|
|
a[every3rdBit] = true
|
|
|
|
b[every3rdBit] = true
|
|
|
|
|
|
|
|
for word in words(a):
|
|
|
|
check word == 4
|
|
|
|
word = 2
|
|
|
|
|
|
|
|
for wa, wb in words(a, b):
|
|
|
|
check wa == 2 and wb == 4
|
|
|
|
wa = 1
|
|
|
|
wb = 2
|
|
|
|
|
|
|
|
for i in 0 ..< expectedWordCount:
|
|
|
|
for j in 0 ..< bitsInWord:
|
|
|
|
let bitPos = i * bitsInWord + j
|
|
|
|
if bitPos < bitCount:
|
|
|
|
check a[j] == (j == 0)
|
|
|
|
check b[j] == (j == 1)
|
|
|
|
|
2019-08-19 14:35:16 +00:00
|
|
|
test "overlaps":
|
2019-08-19 15:09:15 +00:00
|
|
|
for bitCount in [1, 62, 63, 64, 91, 127, 128, 129]:
|
2019-08-19 14:35:16 +00:00
|
|
|
checkpoint &"trying bit count {bitCount}"
|
|
|
|
var
|
|
|
|
a = BitSeq.init(bitCount)
|
|
|
|
b = BitSeq.init(bitCount)
|
2019-08-19 15:09:15 +00:00
|
|
|
|
|
|
|
for pos in [4, 8, 9, 12, 29, 32, 63, 64, 67]:
|
|
|
|
if pos + 2 < bitCount:
|
2019-12-20 12:23:30 +00:00
|
|
|
a.setBit(pos)
|
|
|
|
b.setBit(pos + 2)
|
2019-08-19 14:35:16 +00:00
|
|
|
|
|
|
|
check:
|
|
|
|
not a.overlaps(b)
|
|
|
|
not b.overlaps(a)
|
2019-08-19 15:09:15 +00:00
|
|
|
|