replica_placement.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 (rp *ReplicaPlacement) Byte() byte {
  44. if rp == nil {
  45. return 0
  46. }
  47. ret := rp.DiffDataCenterCount*100 + rp.DiffRackCount*10 + rp.SameRackCount
  48. return byte(ret)
  49. }
  50. func (rp *ReplicaPlacement) String() string {
  51. b := make([]byte, 3)
  52. b[0] = byte(rp.DiffDataCenterCount + '0')
  53. b[1] = byte(rp.DiffRackCount + '0')
  54. b[2] = byte(rp.SameRackCount + '0')
  55. return string(b)
  56. }
  57. func (rp *ReplicaPlacement) GetCopyCount() int {
  58. return rp.DiffDataCenterCount + rp.DiffRackCount + rp.SameRackCount + 1
  59. }