2019-12-29 20:24:06 -05:00
|
|
|
package bitfield
|
|
|
|
|
|
|
|
|
|
// A Bitfield represents the pieces that a peer has
|
|
|
|
|
type Bitfield []byte
|
|
|
|
|
|
|
|
|
|
// HasPiece tells if a bitfield has a particular index set
|
|
|
|
|
func (bf Bitfield) HasPiece(index int) bool {
|
|
|
|
|
byteIndex := index / 8
|
|
|
|
|
offset := index % 8
|
2019-12-30 10:34:41 -05:00
|
|
|
if byteIndex < 0 || byteIndex >= len(bf) {
|
|
|
|
|
return false
|
|
|
|
|
}
|
2021-02-23 11:04:04 +08:00
|
|
|
return bf[byteIndex]>>uint(7-offset)&1 != 0
|
2019-12-29 20:24:06 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// SetPiece sets a bit in the bitfield
|
|
|
|
|
func (bf Bitfield) SetPiece(index int) {
|
|
|
|
|
byteIndex := index / 8
|
|
|
|
|
offset := index % 8
|
2019-12-30 10:34:41 -05:00
|
|
|
|
|
|
|
|
// silently discard invalid bounded index
|
|
|
|
|
if byteIndex < 0 || byteIndex >= len(bf) {
|
|
|
|
|
return
|
|
|
|
|
}
|
2021-02-23 11:04:04 +08:00
|
|
|
bf[byteIndex] |= 1 << uint(7 - offset)
|
2019-12-29 20:24:06 -05:00
|
|
|
}
|