github.com/go-kivik/kivik/v4@v4.3.2/x/fsdb/cdb/revid.go (about) 1 // Licensed under the Apache License, Version 2.0 (the "License"); you may not 2 // use this file except in compliance with the License. You may obtain a copy of 3 // the License at 4 // 5 // http://www.apache.org/licenses/LICENSE-2.0 6 // 7 // Unless required by applicable law or agreed to in writing, software 8 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 9 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 10 // License for the specific language governing permissions and limitations under 11 // the License. 12 13 package cdb 14 15 import ( 16 "bytes" 17 "encoding/json" 18 "fmt" 19 "strconv" 20 "strings" 21 ) 22 23 // RevID is a CouchDB document revision identifier. 24 type RevID struct { 25 Seq int64 26 Sum string 27 original string 28 } 29 30 // Changed returns true if the rev has changed since being read. 31 func (r *RevID) Changed() bool { 32 return r.String() != r.original 33 } 34 35 // UnmarshalText satisfies the json.Unmarshaler interface. 36 func (r *RevID) UnmarshalText(p []byte) error { 37 r.original = string(p) 38 if bytes.Contains(p, []byte("-")) { 39 const maxParts = 2 40 parts := bytes.SplitN(p, []byte("-"), maxParts) 41 seq, err := strconv.ParseInt(string(parts[0]), 10, 64) 42 if err != nil { 43 return err 44 } 45 r.Seq = seq 46 if len(parts) > 1 { 47 r.Sum = string(parts[1]) 48 } 49 return nil 50 } 51 r.Sum = "" 52 seq, err := strconv.ParseInt(string(p), 10, 64) 53 if err != nil { 54 return err 55 } 56 r.Seq = seq 57 return nil 58 } 59 60 // UnmarshalJSON satisfies the json.Unmarshaler interface. 61 func (r *RevID) UnmarshalJSON(p []byte) error { 62 if p[0] == '"' { 63 var str string 64 if e := json.Unmarshal(p, &str); e != nil { 65 return e 66 } 67 r.original = str 68 const maxParts = 2 69 parts := strings.SplitN(str, "-", maxParts) 70 seq, err := strconv.ParseInt(parts[0], 10, 64) 71 if err != nil { 72 return err 73 } 74 r.Seq = seq 75 if len(parts) > 1 { 76 r.Sum = parts[1] 77 } 78 return nil 79 } 80 r.original = string(p) 81 r.Sum = "" 82 return json.Unmarshal(p, &r.Seq) 83 } 84 85 // MarshalText satisfies the encoding.TextMarshaler interface. 86 func (r RevID) MarshalText() ([]byte, error) { 87 return []byte(r.String()), nil 88 } 89 90 func (r RevID) String() string { 91 if r.Seq == 0 { 92 return "" 93 } 94 return fmt.Sprintf("%d-%s", r.Seq, r.Sum) 95 } 96 97 // IsZero returns true if r is uninitialized. 98 func (r *RevID) IsZero() bool { 99 return r.Seq == 0 100 } 101 102 // Equal returns true if rev and revid are equal. 103 func (r RevID) Equal(revid RevID) bool { 104 return r.Seq == revid.Seq && r.Sum == revid.Sum 105 }