compare.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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_NOT_EQUAL
  34. case ">":
  35. r = pb.Compare_GREATER
  36. case "<":
  37. r = pb.Compare_LESS
  38. default:
  39. panic("Unknown result op")
  40. }
  41. cmp.Result = r
  42. switch cmp.Target {
  43. case pb.Compare_VALUE:
  44. val, ok := v.(string)
  45. if !ok {
  46. panic("bad compare value")
  47. }
  48. cmp.TargetUnion = &pb.Compare_Value{Value: []byte(val)}
  49. case pb.Compare_VERSION:
  50. cmp.TargetUnion = &pb.Compare_Version{Version: mustInt64(v)}
  51. case pb.Compare_CREATE:
  52. cmp.TargetUnion = &pb.Compare_CreateRevision{CreateRevision: mustInt64(v)}
  53. case pb.Compare_MOD:
  54. cmp.TargetUnion = &pb.Compare_ModRevision{ModRevision: mustInt64(v)}
  55. default:
  56. panic("Unknown compare type")
  57. }
  58. return cmp
  59. }
  60. func Value(key string) Cmp {
  61. return Cmp{Key: []byte(key), Target: pb.Compare_VALUE}
  62. }
  63. func Version(key string) Cmp {
  64. return Cmp{Key: []byte(key), Target: pb.Compare_VERSION}
  65. }
  66. func CreateRevision(key string) Cmp {
  67. return Cmp{Key: []byte(key), Target: pb.Compare_CREATE}
  68. }
  69. func ModRevision(key string) Cmp {
  70. return Cmp{Key: []byte(key), Target: pb.Compare_MOD}
  71. }
  72. func mustInt64(val interface{}) int64 {
  73. if v, ok := val.(int64); ok {
  74. return v
  75. }
  76. if v, ok := val.(int); ok {
  77. return int64(v)
  78. }
  79. panic("bad value")
  80. }