Skip to content
This repository has been archived by the owner on Jul 12, 2022. It is now read-only.

Commit

Permalink
Refactoring functions usage
Browse files Browse the repository at this point in the history
  • Loading branch information
rlespinasse committed Oct 29, 2017
1 parent 9c23b28 commit b2f12c3
Show file tree
Hide file tree
Showing 10 changed files with 525 additions and 864 deletions.
18 changes: 18 additions & 0 deletions bits.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package byteslice

const (
maxBitsLength = 8
maxLeastSignificantBit = 0
maxMostSignificantBit = maxBitsLength - 1
)

// RBitState get the state of a specific bit of the little endian ordered data byte.
func RBitState(data byte, bit uint8) byte {
return (data >> bit & 0x01) << bit
}

// RBitsSubset get the byte value of a subset of the little endian ordered data byte defined
// by the least significant bit and the most significant bit.
func RBitsSubset(data byte, leastSignificantBit, mostSignificantBit uint8) byte {
return data << (maxMostSignificantBit - mostSignificantBit) >> (maxMostSignificantBit + leastSignificantBit - mostSignificantBit)
}
78 changes: 78 additions & 0 deletions bits_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package byteslice

import (
"testing"
)

var tcRBitState = []struct {
name string
data byte
bit uint8
result byte
}{
{"get low bit of high nibble", 0xf0, 4, 0x10},
{"get low bit", 0xf0, 0, 0},
}

func TestRBitState(t *testing.T) {
var val byte
for _, tc := range tcRBitState {
t.Run(tc.name, func(t *testing.T) {
val = RBitState(tc.data, tc.bit)
if val != (tc.result) {
t.Errorf("RBitState(%x, %v) was %x, should be %x",
tc.data, tc.bit,
val,
tc.result)
}
})
}
}

func BenchmarkRBitState(b *testing.B) {
var val byte
for _, tc := range tcRBitState {
b.Run(tc.name, func(b *testing.B) {
for i := 0; i < b.N; i++ {
val = RBitState(tc.data, tc.bit)
}
})
}
}

var tcRBitsSubset = []struct {
name string
data byte
leastSignificantBit, mostSignificantBit uint8
result byte
}{
{"get bottom 3 bits", 0xf2, 0, 2, 0x02},
{"get low bit", 0xf0, 0, 0, 0x00},
{"lsb and msb out of order", 0xf0, 2, 0, 0x00},
}

func TestRBitsSubset(t *testing.T) {
var val byte
for _, tc := range tcRBitsSubset {
t.Run(tc.name, func(t *testing.T) {
val = RBitsSubset(tc.data, tc.leastSignificantBit, tc.mostSignificantBit)
if val != tc.result {
t.Errorf("RBitsSubset(%x, %v, %v) was %x, should be %x",
tc.data, tc.leastSignificantBit, tc.mostSignificantBit,
val,
tc.result)
}
})
}
}

func BenchmarkRBitsSubset(b *testing.B) {
var val byte
for _, tc := range tcRBitsSubset {
b.Run(tc.name, func(b *testing.B) {
for i := 0; i < b.N; i++ {
val = RBitsSubset(tc.data, tc.leastSignificantBit, tc.mostSignificantBit)
}
})
}
}
50 changes: 0 additions & 50 deletions byteitem.go

This file was deleted.

Loading

0 comments on commit b2f12c3

Please sign in to comment.