You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

56 lines
839 B

  1. package kademlia
  2. import (
  3. "bytes"
  4. "crypto/rand"
  5. "encoding/hex"
  6. )
  7. type ID [B]byte
  8. func NewID() (ID, error) {
  9. b := make([]byte, 32)
  10. _, err := rand.Read(b)
  11. if err != nil {
  12. return ID{}, err
  13. }
  14. var id ID
  15. copy(id[:], b[:B])
  16. return id, nil
  17. }
  18. func (id ID) String() string {
  19. return hex.EncodeToString(id[:])
  20. }
  21. func IDFromString(s string) (ID, error) {
  22. b, err := hex.DecodeString(s)
  23. if err != nil {
  24. return ID{}, err
  25. }
  26. var id ID
  27. copy(id[:], b[:B])
  28. return id, nil
  29. }
  30. func (idA ID) Equal(idB ID) bool {
  31. return bytes.Equal(idA[:], idB[:])
  32. }
  33. // Cmp returns true if idA > idB
  34. func (idA ID) Cmp(idB ID) bool {
  35. for i := 0; i < len(idA); i++ {
  36. if idA[i] != idB[i] {
  37. return idA[i] > idB[i]
  38. }
  39. }
  40. return false
  41. }
  42. func (idA ID) Distance(idB ID) ID {
  43. var d ID
  44. for i := 0; i < B; i++ {
  45. d[i] = idA[i] ^ idB[i]
  46. }
  47. return d
  48. }