Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added ability to export array as raw data #2

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions bitarray.go
Original file line number Diff line number Diff line change
Expand Up @@ -265,3 +265,28 @@ func (bits *BitArray) ToArray() []int {

return ints
}

func (bits *BitArray) ToByteArray() []byte {
return bits.bytes
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think Bytes() is more precise since there is no copy or conversion, and we need some doc comment to clarify that the changes to the bytes will affect the result of future operations from BitArray.

}

// New create a new BitArray with length(bits).
func FromByteArray(length int, data []byte) (*BitArray, error) {
if data == nil {
return nil, errors.New("data can't be nil")
}
lenpad := nwords(length) * _BytesPW
if len(data) != lenpad {
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should create a new bytes slice with lenpad then copy content from the origin slice, also the length should be greater or equal to len(data).

return nil, errors.New("length and size of data don't match")
}
return &BitArray{
lenpad: lenpad,
length: length,
bytes: data,
}, nil
}

func BitLenToByteLen(length int) int {
lenpad := nwords(length) * _BytesPW
return lenpad
}
24 changes: 24 additions & 0 deletions bitarray_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -226,3 +226,27 @@ func TestLeq(t *testing.T) {

_testLtOrEq(t, true)
}

func TestFromByteArray(t *testing.T) {
fmt.Println("Test: FromByteArray")

_, e := FromByteArray(0, nil)
if e == nil {
t.Error("allowed nil data")
}

bits := New(64)
data := bits.ToByteArray()

recreatedData, e := FromByteArray(64, data)

if e != nil || recreatedData == nil {
t.Error("failed to re-cteate byte array", e)
}

recreatedData, e = FromByteArray(88, data)

if e == nil || recreatedData != nil {
t.Error("failed to check for correct length", e)
}
}