replica_placement.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package super_block
  2. import (
  3. "errors"
  4. "fmt"
  5. )
  6. type ReplicaPlacement struct {
  7. SameRackCount int `json:"node,omitempty"`
  8. DiffRackCount int `json:"rack,omitempty"`
  9. DiffDataCenterCount int `json:"dc,omitempty"`
  10. }
  11. func NewReplicaPlacementFromString(t string) (*ReplicaPlacement, error) {
  12. rp := &ReplicaPlacement{}
  13. for i, c := range t {
  14. count := int(c - '0')
  15. if 0 <= count && count <= 2 {
  16. switch i {
  17. case 0:
  18. rp.DiffDataCenterCount = count
  19. case 1:
  20. rp.DiffRackCount = count
  21. case 2:
  22. rp.SameRackCount = count
  23. }
  24. } else {
  25. return rp, errors.New("Unknown Replication Type:" + t)
  26. }
  27. }
  28. return rp, nil
  29. }
  30. func NewReplicaPlacementFromByte(b byte) (*ReplicaPlacement, error) {
  31. return NewReplicaPlacementFromString(fmt.Sprintf("%03d", b))
  32. }
  33. func (rp *ReplicaPlacement) Byte() byte {
  34. if rp == nil {
  35. return 0
  36. }
  37. ret := rp.DiffDataCenterCount*100 + rp.DiffRackCount*10 + rp.SameRackCount
  38. return byte(ret)
  39. }
  40. func (rp *ReplicaPlacement) String() string {
  41. b := make([]byte, 3)
  42. b[0] = byte(rp.DiffDataCenterCount + '0')
  43. b[1] = byte(rp.DiffRackCount + '0')
  44. b[2] = byte(rp.SameRackCount + '0')
  45. return string(b)
  46. }
  47. func (rp *ReplicaPlacement) GetCopyCount() int {
  48. return rp.DiffDataCenterCount + rp.DiffRackCount + rp.SameRackCount + 1
  49. }