structs.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. /*
  2. * Copyright 2019 Dgraph Labs, Inc. and Contributors
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package badger
  17. import (
  18. "encoding/binary"
  19. "fmt"
  20. "time"
  21. "unsafe"
  22. )
  23. type valuePointer struct {
  24. Fid uint32
  25. Len uint32
  26. Offset uint32
  27. }
  28. const vptrSize = unsafe.Sizeof(valuePointer{})
  29. func (p valuePointer) Less(o valuePointer) bool {
  30. if p.Fid != o.Fid {
  31. return p.Fid < o.Fid
  32. }
  33. if p.Offset != o.Offset {
  34. return p.Offset < o.Offset
  35. }
  36. return p.Len < o.Len
  37. }
  38. func (p valuePointer) IsZero() bool {
  39. return p.Fid == 0 && p.Offset == 0 && p.Len == 0
  40. }
  41. // Encode encodes Pointer into byte buffer.
  42. func (p valuePointer) Encode() []byte {
  43. b := make([]byte, vptrSize)
  44. // Copy over the content from p to b.
  45. *(*valuePointer)(unsafe.Pointer(&b[0])) = p
  46. return b
  47. }
  48. // Decode decodes the value pointer into the provided byte buffer.
  49. func (p *valuePointer) Decode(b []byte) {
  50. // Copy over data from b into p. Using *p=unsafe.pointer(...) leads to
  51. // pointer alignment issues. See https://github.com/dgraph-io/badger/issues/1096
  52. // and comment https://github.com/dgraph-io/badger/pull/1097#pullrequestreview-307361714
  53. copy(((*[vptrSize]byte)(unsafe.Pointer(p))[:]), b[:vptrSize])
  54. }
  55. // header is used in value log as a header before Entry.
  56. type header struct {
  57. klen uint32
  58. vlen uint32
  59. expiresAt uint64
  60. meta byte
  61. userMeta byte
  62. }
  63. const (
  64. // Maximum possible size of the header. The maximum size of header struct will be 18 but the
  65. // maximum size of varint encoded header will be 22.
  66. maxHeaderSize = 22
  67. )
  68. // Encode encodes the header into []byte. The provided []byte should be atleast 5 bytes. The
  69. // function will panic if out []byte isn't large enough to hold all the values.
  70. // The encoded header looks like
  71. // +------+----------+------------+--------------+-----------+
  72. // | Meta | UserMeta | Key Length | Value Length | ExpiresAt |
  73. // +------+----------+------------+--------------+-----------+
  74. func (h header) Encode(out []byte) int {
  75. out[0], out[1] = h.meta, h.userMeta
  76. index := 2
  77. index += binary.PutUvarint(out[index:], uint64(h.klen))
  78. index += binary.PutUvarint(out[index:], uint64(h.vlen))
  79. index += binary.PutUvarint(out[index:], h.expiresAt)
  80. return index
  81. }
  82. // Decode decodes the given header from the provided byte slice.
  83. // Returns the number of bytes read.
  84. func (h *header) Decode(buf []byte) int {
  85. h.meta, h.userMeta = buf[0], buf[1]
  86. index := 2
  87. klen, count := binary.Uvarint(buf[index:])
  88. h.klen = uint32(klen)
  89. index += count
  90. vlen, count := binary.Uvarint(buf[index:])
  91. h.vlen = uint32(vlen)
  92. index += count
  93. h.expiresAt, count = binary.Uvarint(buf[index:])
  94. return index + count
  95. }
  96. // DecodeFrom reads the header from the hashReader.
  97. // Returns the number of bytes read.
  98. func (h *header) DecodeFrom(reader *hashReader) (int, error) {
  99. var err error
  100. h.meta, err = reader.ReadByte()
  101. if err != nil {
  102. return 0, err
  103. }
  104. h.userMeta, err = reader.ReadByte()
  105. if err != nil {
  106. return 0, err
  107. }
  108. klen, err := binary.ReadUvarint(reader)
  109. if err != nil {
  110. return 0, err
  111. }
  112. h.klen = uint32(klen)
  113. vlen, err := binary.ReadUvarint(reader)
  114. if err != nil {
  115. return 0, err
  116. }
  117. h.vlen = uint32(vlen)
  118. h.expiresAt, err = binary.ReadUvarint(reader)
  119. if err != nil {
  120. return 0, err
  121. }
  122. return reader.bytesRead, nil
  123. }
  124. // Entry provides Key, Value, UserMeta and ExpiresAt. This struct can be used by
  125. // the user to set data.
  126. type Entry struct {
  127. Key []byte
  128. Value []byte
  129. ExpiresAt uint64 // time.Unix
  130. version uint64
  131. offset uint32 // offset is an internal field.
  132. UserMeta byte
  133. meta byte
  134. // Fields maintained internally.
  135. hlen int // Length of the header.
  136. valThreshold int64
  137. }
  138. func (e *Entry) isZero() bool {
  139. return len(e.Key) == 0
  140. }
  141. func (e *Entry) estimateSizeAndSetThreshold(threshold int64) int64 {
  142. if e.valThreshold == 0 {
  143. e.valThreshold = threshold
  144. }
  145. k := int64(len(e.Key))
  146. v := int64(len(e.Value))
  147. if v < e.valThreshold {
  148. return k + v + 2 // Meta, UserMeta
  149. }
  150. return k + 12 + 2 // 12 for ValuePointer, 2 for metas.
  151. }
  152. func (e *Entry) skipVlogAndSetThreshold(threshold int64) bool {
  153. if e.valThreshold == 0 {
  154. e.valThreshold = threshold
  155. }
  156. return int64(len(e.Value)) < e.valThreshold
  157. }
  158. //nolint:unused
  159. func (e Entry) print(prefix string) {
  160. fmt.Printf("%s Key: %s Meta: %d UserMeta: %d Offset: %d len(val)=%d",
  161. prefix, e.Key, e.meta, e.UserMeta, e.offset, len(e.Value))
  162. }
  163. // NewEntry creates a new entry with key and value passed in args. This newly created entry can be
  164. // set in a transaction by calling txn.SetEntry(). All other properties of Entry can be set by
  165. // calling WithMeta, WithDiscard, WithTTL methods on it.
  166. // This function uses key and value reference, hence users must
  167. // not modify key and value until the end of transaction.
  168. func NewEntry(key, value []byte) *Entry {
  169. return &Entry{
  170. Key: key,
  171. Value: value,
  172. }
  173. }
  174. // WithMeta adds meta data to Entry e. This byte is stored alongside the key
  175. // and can be used as an aid to interpret the value or store other contextual
  176. // bits corresponding to the key-value pair of entry.
  177. func (e *Entry) WithMeta(meta byte) *Entry {
  178. e.UserMeta = meta
  179. return e
  180. }
  181. // WithDiscard adds a marker to Entry e. This means all the previous versions of the key (of the
  182. // Entry) will be eligible for garbage collection.
  183. // This method is only useful if you have set a higher limit for options.NumVersionsToKeep. The
  184. // default setting is 1, in which case, this function doesn't add any more benefit. If however, you
  185. // have a higher setting for NumVersionsToKeep (in Dgraph, we set it to infinity), you can use this
  186. // method to indicate that all the older versions can be discarded and removed during compactions.
  187. func (e *Entry) WithDiscard() *Entry {
  188. e.meta = bitDiscardEarlierVersions
  189. return e
  190. }
  191. // WithTTL adds time to live duration to Entry e. Entry stored with a TTL would automatically expire
  192. // after the time has elapsed, and will be eligible for garbage collection.
  193. func (e *Entry) WithTTL(dur time.Duration) *Entry {
  194. e.ExpiresAt = uint64(time.Now().Add(dur).Unix())
  195. return e
  196. }
  197. // withMergeBit sets merge bit in entry's metadata. This
  198. // function is called by MergeOperator's Add method.
  199. func (e *Entry) withMergeBit() *Entry {
  200. e.meta = bitMergeEntry
  201. return e
  202. }