hashalgorithm.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Copyright (C) 2016 The Protocol Authors.
  2. package protocol
  3. import "fmt"
  4. type HashAlgorithm int
  5. const (
  6. SHA256 HashAlgorithm = iota
  7. )
  8. func (h HashAlgorithm) String() string {
  9. switch h {
  10. case SHA256:
  11. return "sha256"
  12. default:
  13. return "unknown"
  14. }
  15. }
  16. // FlagBits returns the bits that we should or into the folder flag field to
  17. // indicate the hash algorithm.
  18. func (h HashAlgorithm) FlagBits() uint32 {
  19. switch h {
  20. case SHA256:
  21. return FolderHashSHA256 << FolderHashShiftBits
  22. default:
  23. panic("unknown hash algorithm")
  24. }
  25. }
  26. func (h *HashAlgorithm) UnmarshalText(bs []byte) error {
  27. switch string(bs) {
  28. case "sha256":
  29. *h = SHA256
  30. return nil
  31. }
  32. return fmt.Errorf("Unknown hash algorithm %q", string(bs))
  33. }
  34. func (h *HashAlgorithm) MarshalText() ([]byte, error) {
  35. return []byte(h.String()), nil
  36. }
  37. func HashAlgorithmFromFlagBits(flags uint32) (HashAlgorithm, error) {
  38. algo := flags >> FolderHashShiftBits & FolderHashMask
  39. switch algo {
  40. case FolderHashSHA256:
  41. return SHA256, nil
  42. default:
  43. return 0, fmt.Errorf("Unknown hash algorithm %d", algo)
  44. }
  45. }