bf: add setall(), clearall(), string() and str2bf()

pull/1141/head
Vitalie Ciubotaru 2019-07-15 00:56:48 +09:00 committed by Alexander Medvednikov
parent 7fa1f423e2
commit 9a3baf5609
2 changed files with 119 additions and 0 deletions

View File

@ -64,6 +64,29 @@ fn cleartail(instance BitField) {
// public functions // public functions
pub fn str2bf(input string) BitField {
mut output := new(input.len)
for i := 0; i < input.len; i++ {
if input[i] != 48 {
output.setbit(i)
}
}
return output
}
pub fn (input BitField) string() string {
mut output := ''
for i := 0; i < input.size; i++ {
if input.getbit(i) == 1 {
output = output + '1'
}
else {
output = output + '0'
}
}
return output
}
pub fn new(size int) BitField { pub fn new(size int) BitField {
output := BitField{ output := BitField{
size: size size: size
@ -93,6 +116,19 @@ pub fn (instance mut BitField) clearbit(bitnr int) {
bitclear(instance, bitnr) bitclear(instance, bitnr)
} }
pub fn (instance mut BitField) setall() {
for i := 0; i < bitnslots(instance.size); i++ {
instance.field[i] = u32(-1)
}
cleartail(instance)
}
pub fn (instance mut BitField) clearall() {
for i := 0; i < bitnslots(instance.size); i++ {
instance.field[i] = u32(0)
}
}
pub fn (instance mut BitField) togglebit(bitnr int) { pub fn (instance mut BitField) togglebit(bitnr int) {
if bitnr >= instance.size {return} if bitnr >= instance.size {return}
bittoggle(instance, bitnr) bittoggle(instance, bitnr)

View File

@ -119,3 +119,86 @@ fn test_hamming() {
} }
assert count == bf.hamming(input1, input2) assert count == bf.hamming(input1, input2)
} }
fn test_bf_str2bf() {
rand.seed(time.now().uni)
len := 80
mut input := ''
for i := 0; i < len; i++ {
if rand.next(2) == 1 {
input = input + '1'
}
else {
input = input + '0'
}
}
output := bf.str2bf(input)
mut result := 1
for i := 0; i < len; i++ {
if input[i] != output.getbit(i) + 48 {
result = 0
}
}
assert result == 1
}
fn test_bf_bf2str() {
rand.seed(time.now().uni)
len := 80
mut input := bf.new(len)
for i := 0; i < len; i++ {
if rand.next(2) == 1 {
input.setbit(i)
}
}
mut check := ''
for i := 0; i < len; i++ {
if input.getbit(i) == 1 {
check = check + '1'
}
else {
check = check + '0'
}
}
output := input.string()
mut result := 1
for i := 0; i < len; i++ {
if check[i] != output[i] {
result = 0
}
}
assert result == 1
}
fn test_bf_setall() {
rand.seed(time.now().uni)
len := 80
mut input := bf.new(len)
input.setall()
mut result := 1
for i := 0; i < len; i++ {
if input.getbit(i) != 1 {
result = 0
}
}
assert result == 1
}
fn test_bf_clearall() {
rand.seed(time.now().uni)
len := 80
mut input := bf.new(len)
for i := 0; i < len; i++ {
if rand.next(2) == 1 {
input.setbit(i)
}
}
input.clearall()
mut result := 1
for i := 0; i < len; i++ {
if input.getbit(i) != 0 {
result = 0
}
}
assert result == 1
}