replica_placement.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package super_block
  2. import (
  3. "errors"
  4. "fmt"
  5. )
  6. type ReplicaPlacement struct {
  7. SameRackCount int
  8. DiffRackCount int
  9. DiffDataCenterCount int
  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. ret := rp.DiffDataCenterCount*100 + rp.DiffRackCount*10 + rp.SameRackCount
  35. return byte(ret)
  36. }
  37. func (rp *ReplicaPlacement) String() string {
  38. b := make([]byte, 3)
  39. b[0] = byte(rp.DiffDataCenterCount + '0')
  40. b[1] = byte(rp.DiffRackCount + '0')
  41. b[2] = byte(rp.SameRackCount + '0')
  42. return string(b)
  43. }
  44. func (rp *ReplicaPlacement) GetCopyCount() int {
  45. return rp.DiffDataCenterCount + rp.DiffRackCount + rp.SameRackCount + 1
  46. }