You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 lines
1.8 KiB

  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) HasReplication() bool {
  44. return rp.DiffDataCenterCount != 0 || rp.DiffRackCount != 0 || rp.SameRackCount != 0
  45. }
  46. func (a *ReplicaPlacement) Equals(b *ReplicaPlacement) bool {
  47. if a == nil || b == nil {
  48. return false
  49. }
  50. return (a.SameRackCount == b.SameRackCount &&
  51. a.DiffRackCount == b.DiffRackCount &&
  52. a.DiffDataCenterCount == b.DiffDataCenterCount)
  53. }
  54. func (rp *ReplicaPlacement) Byte() byte {
  55. if rp == nil {
  56. return 0
  57. }
  58. ret := rp.DiffDataCenterCount*100 + rp.DiffRackCount*10 + rp.SameRackCount
  59. return byte(ret)
  60. }
  61. func (rp *ReplicaPlacement) String() string {
  62. b := make([]byte, 3)
  63. b[0] = byte(rp.DiffDataCenterCount + '0')
  64. b[1] = byte(rp.DiffRackCount + '0')
  65. b[2] = byte(rp.SameRackCount + '0')
  66. return string(b)
  67. }
  68. func (rp *ReplicaPlacement) GetCopyCount() int {
  69. return rp.DiffDataCenterCount + rp.DiffRackCount + rp.SameRackCount + 1
  70. }