uint128.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package ipbits
  2. import (
  3. "encoding/binary"
  4. "math/bits"
  5. )
  6. type uint128 struct{ hi, lo uint64 }
  7. func uint128From16(b [16]byte) uint128 {
  8. return uint128{
  9. hi: binary.BigEndian.Uint64(b[:8]),
  10. lo: binary.BigEndian.Uint64(b[8:]),
  11. }
  12. }
  13. func uint128From(x uint64) uint128 {
  14. return uint128{lo: x}
  15. }
  16. func (x uint128) add(y uint128) uint128 {
  17. lo, carry := bits.Add64(x.lo, y.lo, 0)
  18. hi, _ := bits.Add64(x.hi, y.hi, carry)
  19. return uint128{hi: hi, lo: lo}
  20. }
  21. func (x uint128) lsh(n uint) uint128 {
  22. if n > 64 {
  23. return uint128{hi: x.lo << (n - 64)}
  24. }
  25. return uint128{
  26. hi: x.hi<<n | x.lo>>(64-n),
  27. lo: x.lo << n,
  28. }
  29. }
  30. func (x uint128) rsh(n uint) uint128 {
  31. if n > 64 {
  32. return uint128{lo: x.hi >> (n - 64)}
  33. }
  34. return uint128{
  35. hi: x.hi >> n,
  36. lo: x.lo>>n | x.hi<<(64-n),
  37. }
  38. }
  39. func (x uint128) and(y uint128) uint128 {
  40. return uint128{hi: x.hi & y.hi, lo: x.lo & y.lo}
  41. }
  42. func (x uint128) not() uint128 {
  43. return uint128{hi: ^x.hi, lo: ^x.lo}
  44. }
  45. func (x uint128) fill16(a *[16]byte) {
  46. binary.BigEndian.PutUint64(a[:8], x.hi)
  47. binary.BigEndian.PutUint64(a[8:], x.lo)
  48. }
  49. func (x uint128) uint64() uint64 {
  50. return x.lo
  51. }