Line data Source code
1 : // Copyright 2020 The LevelDB-Go and Pebble Authors. All rights reserved. Use 2 : // of this source code is governed by a BSD-style license that can be found in 3 : // the LICENSE file. 4 : 5 : package cache 6 : 7 : import "unsafe" 8 : 9 : // ValueMetadataSize denotes the number of bytes of metadata allocated for a 10 : // cache entry. Note that builds with cgo disabled allocate no metadata, and 11 : // 32-bit builds allocate less for a cache.Value. However, we keep the value 12 : // constant to reduce friction for writing tests. 13 : const ValueMetadataSize = 32 14 : 15 : // Assert that the size of a Value{} is less than or equal to the 16 : // ValueMetadataSize. 17 : var _ uint = ValueMetadataSize - uint(unsafe.Sizeof(Value{})) 18 : 19 : // Value holds a reference counted immutable value. 20 : type Value struct { 21 : buf []byte 22 : // Reference count for the value. The value is freed when the reference count 23 : // drops to zero. 24 : ref refcnt 25 : } 26 : 27 : // Buf returns the buffer associated with the value. The contents of the buffer 28 : // should not be changed once the value has been added to the cache. Instead, a 29 : // new Value should be created and added to the cache to replace the existing 30 : // value. 31 1 : func (v *Value) Buf() []byte { 32 1 : if v == nil { 33 0 : return nil 34 0 : } 35 1 : return v.buf 36 : } 37 : 38 : // Truncate the buffer to the specified length. The buffer length should not be 39 : // changed once the value has been added to the cache as there may be 40 : // concurrent readers of the Value. Instead, a new Value should be created and 41 : // added to the cache to replace the existing value. 42 1 : func (v *Value) Truncate(n int) { 43 1 : v.buf = v.buf[:n] 44 1 : } 45 : 46 1 : func (v *Value) refs() int32 { 47 1 : return v.ref.refs() 48 1 : } 49 : 50 1 : func (v *Value) acquire() { 51 1 : v.ref.acquire() 52 1 : } 53 : 54 1 : func (v *Value) release() { 55 1 : if v != nil && v.ref.release() { 56 1 : v.free() 57 1 : } 58 : }