replica_placement.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package super_block
  2. import (
  3. "fmt"
  4. )
  5. type ReplicaPlacement struct {
  6. SameRackCount int `json:"node,omitempty"`
  7. DiffRackCount int `json:"rack,omitempty"`
  8. DiffDataCenterCount int `json:"dc,omitempty"`
  9. }
  10. func NewReplicaPlacementFromString(t string) (*ReplicaPlacement, error) {
  11. rp := &ReplicaPlacement{}
  12. switch len(t) {
  13. case 0:
  14. t = "000"
  15. case 1:
  16. t = "00" + t
  17. case 2:
  18. t = "0" + t
  19. }
  20. for i, c := range t {
  21. count := int(c - '0')
  22. if count < 0 {
  23. return rp, fmt.Errorf("unknown replication type: %s", t)
  24. }
  25. switch i {
  26. case 0:
  27. rp.DiffDataCenterCount = count
  28. case 1:
  29. rp.DiffRackCount = count
  30. case 2:
  31. rp.SameRackCount = count
  32. }
  33. }
  34. value := rp.DiffDataCenterCount*100 + rp.DiffRackCount*10 + rp.SameRackCount
  35. if value > 255 {
  36. return rp, fmt.Errorf("unexpected replication type: %s", t)
  37. }
  38. return rp, nil
  39. }
  40. func NewReplicaPlacementFromByte(b byte) (*ReplicaPlacement, error) {
  41. return NewReplicaPlacementFromString(fmt.Sprintf("%03d", b))
  42. }
  43. func (a *ReplicaPlacement) Equals(b *ReplicaPlacement) bool {
  44. if a == nil || b == nil {
  45. return false
  46. }
  47. return (a.SameRackCount == b.SameRackCount &&
  48. a.DiffRackCount == b.DiffRackCount &&
  49. a.DiffDataCenterCount == b.DiffDataCenterCount)
  50. }
  51. func (rp *ReplicaPlacement) Byte() byte {
  52. if rp == nil {
  53. return 0
  54. }
  55. ret := rp.DiffDataCenterCount*100 + rp.DiffRackCount*10 + rp.SameRackCount
  56. return byte(ret)
  57. }
  58. func (rp *ReplicaPlacement) String() string {
  59. b := make([]byte, 3)
  60. b[0] = byte(rp.DiffDataCenterCount + '0')
  61. b[1] = byte(rp.DiffRackCount + '0')
  62. b[2] = byte(rp.SameRackCount + '0')
  63. return string(b)
  64. }
  65. func (rp *ReplicaPlacement) GetCopyCount() int {
  66. return rp.DiffDataCenterCount + rp.DiffRackCount + rp.SameRackCount + 1
  67. }