compare.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. // Copyright 2016 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package clientv3
  15. import (
  16. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  17. )
  18. type CompareTarget int
  19. type CompareResult int
  20. const (
  21. CompareVersion CompareTarget = iota
  22. CompareCreated
  23. CompareModified
  24. CompareValue
  25. )
  26. type Cmp pb.Compare
  27. func Compare(cmp Cmp, result string, v interface{}) Cmp {
  28. var r pb.Compare_CompareResult
  29. switch result {
  30. case "=":
  31. r = pb.Compare_EQUAL
  32. case ">":
  33. r = pb.Compare_GREATER
  34. case "<":
  35. r = pb.Compare_LESS
  36. default:
  37. panic("Unknown result op")
  38. }
  39. cmp.Result = r
  40. switch cmp.Target {
  41. case pb.Compare_VALUE:
  42. val, ok := v.(string)
  43. if !ok {
  44. panic("bad compare value")
  45. }
  46. cmp.TargetUnion = &pb.Compare_Value{Value: []byte(val)}
  47. case pb.Compare_VERSION:
  48. cmp.TargetUnion = &pb.Compare_Version{Version: mustInt64(v)}
  49. case pb.Compare_CREATE:
  50. cmp.TargetUnion = &pb.Compare_CreateRevision{CreateRevision: mustInt64(v)}
  51. case pb.Compare_MOD:
  52. cmp.TargetUnion = &pb.Compare_ModRevision{ModRevision: mustInt64(v)}
  53. default:
  54. panic("Unknown compare type")
  55. }
  56. return cmp
  57. }
  58. func Value(key string) Cmp {
  59. return Cmp{Key: []byte(key), Target: pb.Compare_VALUE}
  60. }
  61. func Version(key string) Cmp {
  62. return Cmp{Key: []byte(key), Target: pb.Compare_VERSION}
  63. }
  64. func CreateRevision(key string) Cmp {
  65. return Cmp{Key: []byte(key), Target: pb.Compare_CREATE}
  66. }
  67. func ModRevision(key string) Cmp {
  68. return Cmp{Key: []byte(key), Target: pb.Compare_MOD}
  69. }
  70. func mustInt64(val interface{}) int64 {
  71. if v, ok := val.(int64); ok {
  72. return v
  73. }
  74. if v, ok := val.(int); ok {
  75. return int64(v)
  76. }
  77. panic("bad value")
  78. }