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.

74 lines
1.2 KiB

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