Skip to content

Commit

Permalink
feat(bitfield): bitfield pieces
Browse files Browse the repository at this point in the history
  • Loading branch information
BrianLusina committed Jul 19, 2022
1 parent e72452f commit 7513323
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 0 deletions.
27 changes: 27 additions & 0 deletions pkg/bitfield/bitfield.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package bitfield

// Bitfield represents the pieces that a peer has
type Bitfield []byte

// HasPiece teels if a bitfield has a particular index
func (bf Bitfield) HasPiece(index int) bool {
byteIndex := index / 8
offset := index % 8
if byteIndex < 0 || byteIndex >= len(bf) {
return false
}
return bf[byteIndex]>>(7-offset)&1 != 0
}

// SetPiece sets a bit in the bitfield
func (bf Bitfield) SetPiece(index int) {
byteIndex := index / 8
offset := index % 8

// silently ignore invalid bounded index
if byteIndex < 0 || byteIndex >= len(bf) {
return
}

bf[byteIndex] |= 1 << (7 - offset)
}
49 changes: 49 additions & 0 deletions pkg/bitfield/bitfield_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package bitfield

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestHasPiece(t *testing.T) {
bf := Bitfield{0b01010100, 0b01010100}
outputs := []bool{false, true, false, true, false, true, false, false, false, true, false, true, false, true, false, false, false, false, false, false}
for i := 0; i < len(outputs); i++ {
assert.Equal(t, outputs[i], bf.HasPiece(i))
}
}

func TestSetPiece(t *testing.T) {
tests := []struct {
input Bitfield
index int
output Bitfield
}{
{
input: Bitfield{0b01010100, 0b01010100},
index: 4, // v (set)
output: Bitfield{0b01011100, 0b01010100},
},
{
input: Bitfield{0b01010100, 0b01010100},
index: 9, // v (noop)
output: Bitfield{0b01010100, 0b01010100},
},
{
input: Bitfield{0b01010100, 0b01010100},
index: 15, // v (set)
output: Bitfield{0b01010100, 0b01010101},
},
{
input: Bitfield{0b01010100, 0b01010100},
index: 19, // v (noop)
output: Bitfield{0b01010100, 0b01010100},
},
}
for _, test := range tests {
bf := test.input
bf.SetPiece(test.index)
assert.Equal(t, test.output, bf)
}
}

0 comments on commit 7513323

Please sign in to comment.