package z
Import Path
github.com/dgraph-io/ristretto/v2/z (on go.dev)
Dependency Relation
imports 26 packages, and imported by 5 packages
Involved Source Files
allocator.go
bbloom.go
btree.go
buffer.go
calloc.go
calloc_64bit.go
calloc_nojemalloc.go
file.go
file_linux.go
flags.go
histogram.go
mmap.go
mmap_linux.go
mremap_size.go
rtutil.go
z.go
rtutil.s
Package-Level Type Names (total 15)
Allocator amortizes the cost of small allocations by allocating memory in
bigger chunks. Internally it uses z.Calloc to allocate memory. Once
allocated, the memory is not moved, so it is safe to use the allocated bytes
to unsafe cast them to Go struct pointers. Maintaining a freelist is slow.
Instead, Allocator only allocates memory, with the idea that finally we
would just release the entire Allocator.
Mutex sync.Mutex
Ref uint64
Tag string
(*Allocator) Allocate(sz int) []byte
(*Allocator) AllocateAligned(sz int) []byte
(*Allocator) Allocated() uint64
(*Allocator) Copy(buf []byte) []byte
Lock locks m.
If the lock is already in use, the calling goroutine
blocks until the mutex is available.
(*Allocator) MaxAlloc() int
Release would release the memory back. Remember to make this call to avoid memory leaks.
(*Allocator) Reset()
Size returns the size of the allocations so far.
(*Allocator) String() string
(*Allocator) TrimTo(max int)
TryLock tries to lock m and reports whether it succeeded.
Note that while correct uses of TryLock do exist, they are rare,
and use of TryLock is often a sign of a deeper problem
in a particular use of mutexes.
Unlock unlocks m.
It is a run-time error if m is not locked on entry to Unlock.
A locked [Mutex] is not associated with a particular goroutine.
It is allowed for one goroutine to lock a Mutex and then
arrange for another goroutine to unlock it.
*Allocator : github.com/gogo/protobuf/proto.Sizer
*Allocator : expvar.Var
*Allocator : fmt.Stringer
*Allocator : sync.Locker
func AllocatorFrom(ref uint64) *Allocator
func NewAllocator(sz int, tag string) *Allocator
func (*AllocatorPool).Get(sz int, tag string) *Allocator
func (*AllocatorPool).Return(a *Allocator)
func github.com/dgraph-io/badger/v4/y.NewKV(alloc *Allocator) *pb.KV
(*AllocatorPool) Get(sz int, tag string) *Allocator
(*AllocatorPool) Release()
(*AllocatorPool) Return(a *Allocator)
func NewAllocatorPool(sz int) *AllocatorPool
Bloom filter
ElemNum uint64
Add adds hash of a key to the bloomfilter.
AddIfNotHas only Adds hash, if it's not present in the bloomfilter.
Returns true if hash was added.
Returns false if hash was already registered in the bloomfilter.
Clear resets the Bloom filter.
Has checks if bit(s) for entry hash is/are set,
returns true if the hash was added to the Bloom Filter.
IsSet checks if bit[idx] of bitset is set, returns true/false.
JSONMarshal returns JSON-object (type bloomJSONImExport) as []byte.
Set sets the bit[idx] of bitset.
Size makes Bloom filter with as bitset of size sz.
TotalSize returns the total size of the bloom filter.
func JSONUnmarshal(dbData []byte) (*Bloom, error)
func NewBloomFilter(params ...float64) (bloomfilter *Bloom)
Buffer is equivalent of bytes.Buffer without the ability to read. It is NOT thread-safe.
In UseCalloc mode, z.Calloc is used to allocate memory, which depending upon how the code is
compiled could use jemalloc for allocations.
In UseMmap mode, Buffer uses file mmap to allocate memory. This allows us to store big data
structures without using physical memory.
MaxSize can be set to limit the memory usage.
Allocate is a way to get a slice of size n back from the buffer. This slice can be directly
written to. Warning: Allocate is not thread-safe. The byte slice returned MUST be used before
further calls to Buffer.
AllocateOffset works the same way as allocate, but instead of returning a byte slice, it returns
the offset of the allocation.
Bytes would return all the written bytes as a slice.
(*Buffer) Data(offset int) []byte
Grow would grow the buffer to have at least n more bytes. In case the buffer is at capacity, it
would reallocate twice the size of current capacity + n, to ensure n bytes can be written to the
buffer without further allocation. In UseMmap mode, this might result in underlying file
expansion.
(*Buffer) IsEmpty() bool
LenNoPadding would return the number of bytes written to the buffer so far
(without the padding).
LenWithPadding would return the number of bytes written to the buffer so far
plus the padding at the start of the buffer.
Release would free up the memory allocated by the buffer. Once the usage of buffer is done, it is
important to call Release, otherwise a memory leak can happen.
Reset would reset the buffer to be reused.
Slice would return the slice written at offset.
SliceAllocate would encode the size provided into the buffer, followed by a call to Allocate,
hence returning the slice of size sz. This can be used to allocate a lot of small buffers into
this big buffer.
Note that SliceAllocate should NOT be mixed with normal calls to Write.
(*Buffer) SliceIterate(f func(slice []byte) error) error
SliceOffsets is an expensive function. Use sparingly.
SortSlice is like SortSliceBetween but sorting over the entire buffer.
(*Buffer) SortSliceBetween(start, end int, less LessFunc)
(*Buffer) StartOffset() int
(*Buffer) WithAutoMmap(threshold int, path string) *Buffer
(*Buffer) WithMaxSize(size int) *Buffer
Write would write p bytes to the buffer.
(*Buffer) WriteSlice(slice []byte)
*Buffer : github.com/apache/arrow-go/v18/internal/hashing.ByteSlice
*Buffer : github.com/miekg/dns.Writer
*Buffer : internal/bisect.Writer
*Buffer : io.Writer
func NewBuffer(capacity int, tag string) *Buffer
func NewBufferPersistent(path string, capacity int) (*Buffer, error)
func NewBufferSlice(slice []byte) *Buffer
func NewBufferTmp(dir string, capacity int) (*Buffer, error)
func (*Buffer).WithAutoMmap(threshold int, path string) *Buffer
func (*Buffer).WithMaxSize(size int) *Buffer
func github.com/dgraph-io/badger/v4.BufferToKVList(buf *Buffer) (*pb.KVList, error)
func github.com/dgraph-io/badger/v4.KVToBuffer(kv *pb.KV, buf *Buffer)
func github.com/dgraph-io/badger/v4.(*StreamWriter).Write(buf *Buffer) error
func github.com/dgraph-io/badger/v4.(*WriteBatch).Write(buf *Buffer) error
( BufferType) String() string
BufferType : expvar.Var
BufferType : fmt.Stringer
const UseCalloc
const UseInvalid
const UseMmap
Closer holds the two things we need to close a goroutine and wait for it to
finish: a chan to tell the goroutine to shut down, and a WaitGroup with
which to wait for it to finish shutting down.
AddRunning Add()'s delta to the WaitGroup.
Ctx can be used to get a context, which would automatically get cancelled when Signal is called.
Done calls Done() on the WaitGroup.
HasBeenClosed gets signaled when Signal() is called.
Signal signals the HasBeenClosed signal.
SignalAndWait calls Signal(), then Wait().
Wait waits on the WaitGroup. (It waits for NewCloser's initial value, AddRunning, and Done
calls to balance out.)
func NewCloser(initial int) *Closer
func github.com/dgraph-io/badger/v4/y.(*WaterMark).Init(closer *Closer)
HistogramData stores the information needed to represent the sizes of the keys and values
as a histogram.
Bounds []float64
Count int64
CountPerBucket []int64
Max int64
Min int64
Sum int64
Clear reset the histogram. Helpful in situations where we need to reset the metrics
(*HistogramData) Copy() *HistogramData
Mean returns the mean value for the histogram.
Percentile returns the percentile value for the histogram.
value of p should be between [0.0-1.0]
String converts the histogram data into human-readable string.
Update changes the Min and Max fields if value is less than or greater than the current values.
*HistogramData : expvar.Var
*HistogramData : fmt.Stringer
func NewHistogramData(bounds []float64) *HistogramData
func (*HistogramData).Copy() *HistogramData
func github.com/dgraph-io/ristretto/v2.(*Metrics).LifeExpectancySeconds() *HistogramData
type Key (interface)
func (*Buffer).SortSliceBetween(start, end int, less LessFunc)
MemStats is used to fetch JE Malloc Stats. The stats are fetched from
the mallctl namespace http://jemalloc.net/jemalloc.3.html#mallctl_namespace.
Total number of bytes in active pages allocated by the application. This
is a multiple of the page size, and greater than or equal to
Allocated.
http://jemalloc.net/jemalloc.3.html#stats.active
Total number of bytes allocated by the application.
http://jemalloc.net/jemalloc.3.html#stats.allocated
Maximum number of bytes in physically resident data pages mapped by the
allocator, comprising all pages dedicated to allocator metadata, pages
backing active allocations, and unused dirty pages. This is a maximum
rather than precise because pages may not actually be physically
resident if they correspond to demand-zeroed virtual memory that has not
yet been touched. This is a multiple of the page size, and is larger
than stats.active.
http://jemalloc.net/jemalloc.3.html#stats.resident
Total number of bytes in virtual memory mappings that were retained
rather than being returned to the operating system via e.g. munmap(2) or
similar. Retained virtual memory is typically untouched, decommitted, or
purged, so it has no strongly associated physical memory (see extent
hooks http://jemalloc.net/jemalloc.3.html#arena.i.extent_hooks for
details). Retained memory is excluded from mapped memory statistics,
e.g. stats.mapped (http://jemalloc.net/jemalloc.3.html#stats.mapped).
http://jemalloc.net/jemalloc.3.html#stats.retained
func ReadMemStats(_ *MemStats)
MmapFile represents an mmapd file and includes both the buffer to the data
and the file descriptor.
Data []byte
Fd *os.File
AllocateSlice allocates a slice of the given size at the given offset.
Bytes returns data starting from offset off of size sz. If there's not enough data, it would
return nil slice and io.EOF.
Close would close the file. It would also truncate the file if maxSz >= 0.
(*MmapFile) Delete() error
(*MmapFile) NewReader(offset int) io.Reader
Slice returns the slice at the given offset.
(*MmapFile) Sync() error
Truncate would truncate the mmapped file to the given size. On Linux, we truncate
the underlying file and then call mremap, but on other systems, we unmap first,
then truncate, then re-map.
*MmapFile : github.com/polarsignals/frostdb.Sync
func OpenMmapFile(filename string, flag int, maxSz int) (*MmapFile, error)
func OpenMmapFileUsing(fd *os.File, sz int, writable bool) (*MmapFile, error)
func github.com/dgraph-io/badger/v4/table.OpenTable(mf *MmapFile, opts table.Options) (*table.Table, error)
(*SuperFlag) GetBool(opt string) bool
(*SuperFlag) GetDuration(opt string) time.Duration
(*SuperFlag) GetFloat64(opt string) float64
(*SuperFlag) GetInt64(opt string) int64
(*SuperFlag) GetPath(opt string) string
(*SuperFlag) GetString(opt string) string
(*SuperFlag) GetUint32(opt string) uint32
(*SuperFlag) GetUint64(opt string) uint64
(*SuperFlag) Has(opt string) bool
(*SuperFlag) MergeAndCheckDefault(flag string) *SuperFlag
(*SuperFlag) String() string
*SuperFlag : expvar.Var
*SuperFlag : fmt.Stringer
func NewSuperFlag(flag string) *SuperFlag
func (*SuperFlag).MergeAndCheckDefault(flag string) *SuperFlag
SuperFlagHelp makes it really easy to generate command line `--help` output for a SuperFlag. For
example:
const flagDefaults = `enabled=true; path=some/path;`
var help string = z.NewSuperFlagHelp(flagDefaults).
Flag("enabled", "Turns on <something>.").
Flag("path", "The path to <something>.").
Flag("another", "Not present in defaults, but still included.").
String()
The `help` string would then contain:
enabled=true; Turns on <something>.
path=some/path; The path to <something>.
another=; Not present in defaults, but still included.
All flags are sorted alphabetically for consistent `--help` output. Flags with default values are
placed at the top, and everything else goes under.
(*SuperFlagHelp) Flag(name, description string) *SuperFlagHelp
(*SuperFlagHelp) Head(head string) *SuperFlagHelp
(*SuperFlagHelp) String() string
*SuperFlagHelp : expvar.Var
*SuperFlagHelp : fmt.Stringer
func NewSuperFlagHelp(defaults string) *SuperFlagHelp
func (*SuperFlagHelp).Flag(name, description string) *SuperFlagHelp
func (*SuperFlagHelp).Head(head string) *SuperFlagHelp
Tree represents the structure for custom mmaped B+ tree.
It supports keys in range [1, math.MaxUint64-1] and values [1, math.Uint64].
Close releases the memory used by the tree.
DeleteBelow deletes all keys with value under ts.
Get looks for key and returns the corresponding value.
If key is not found, 0 is returned.
Iterate iterates over the tree and executes the fn on each node.
IterateKV iterates through all keys and values in the tree.
If newVal is non-zero, it will be set in the tree.
Print iterates over the tree and prints all valid KVs.
Reset resets the tree and truncates it to maxSz.
Set sets the key-value pair in the tree.
Stats returns stats about the tree.
*Tree : github.com/prometheus/common/expfmt.Closer
*Tree : io.Closer
func NewTree(tag string) *Tree
func NewTreePersistent(path string) (*Tree, error)
Package-Level Functions (total 42)
AllocatorFrom would return the allocator corresponding to the ref.
func Allocators() string
BytesToUint64Slice converts a byte slice to a uint64 slice.
Calloc allocates a slice of size n.
CallocNoRef will not give you memory back without jemalloc.
CPUTicks is a faster alternative to NanoTime to measure time duration.
FastRand is a fast thread local random function.
Free does not do anything in this mode.
Creates bounds for an histogram. The bounds are powers of two of the form
[2^min_exponent, ..., 2^max_exponent].
JSONUnmarshal takes JSON-Object (type bloomJSONImExport) as []bytes
returns bloom32 / bloom64 object.
Type Parameters:
K: Key
TODO: Figure out a way to re-use memhash for the second uint64 hash,
we already know that appending bytes isn't reliable for generating a
second hash (see Ristretto PR #88).
We also know that while the Go runtime has a runtime memhash128
function, it's not possible to use it to generate [2]uint64 or
anything resembling a 128bit hash, even though that's exactly what
we need in this situation.
Madvise uses the madvise system call to give advise about the use of memory
when using a slice that is memory-mapped to a file. Set the readahead flag to
false if page references are expected in random order.
MemHash is the hash function used by go map, it utilizes available hardware instructions(behaves
as aeshash if aes instruction is available).
NOTE: The hash seed changes for every process. So, this cannot be used as a persistent hash.
MemHashString is the hash function used by go map, it utilizes available hardware instructions
(behaves as aeshash if aes instruction is available).
NOTE: The hash seed changes for every process. So, this cannot be used as a persistent hash.
Mmap uses the mmap system call to memory-map a file. If writable is true,
memory protection of the pages is set so that they may be written to as well.
Msync would call sync on the mmapped data.
Munmap unmaps a previously mapped slice.
NanoTime returns the current time in nanoseconds from a monotonic clock.
NewAllocator creates an allocator starting with the given size.
func NewAllocatorPool(sz int) *AllocatorPool
NewBloomFilter returns a new bloomfilter.
It is the caller's responsibility to set offset after this, because Buffer
doesn't remember what it was.
func NewBufferSlice(slice []byte) *Buffer func NewBufferTmp(dir string, capacity int) (*Buffer, error)
NewCloser constructs a new Closer, with an initial count on the WaitGroup.
NewHistogramData returns a new instance of HistogramData with properly initialized fields.
func NewSuperFlag(flag string) *SuperFlag func NewSuperFlagHelp(defaults string) *SuperFlagHelp
NewTree returns an in-memory B+ tree.
NewTree returns a persistent on-disk B+ tree.
NumAllocBytes returns the number of bytes allocated using calls to z.Calloc. The allocations
could be happening via either Go or jemalloc, depending upon the build flags.
OpenMmapFile opens an existing file or creates a new file. If the file is
created, it would truncate the file to maxSz. In both cases, it would mmap
the file to maxSz and returned it. In case the file is created, z.NewFile is
returned.
ReadMemStats doesn't do anything since all the memory is being managed
by the Go runtime.
SetTmpDir sets the temporary directory for the temporary buffers.
func StatsPrint()
ZeroOut zeroes out all the bytes in the range [start, end).
Package-Level Constants (total 5)
MaxArrayLen is a safe maximum length for slices on this architecture.
MaxBufferSize is the size of virtually unlimited buffer on this architecture.
const UseCalloc BufferType = 0 const UseInvalid BufferType = 2 const UseMmap BufferType = 1
![]() |
The pages are generated with Golds v0.8.4. (GOOS=linux GOARCH=amd64) Golds is a Go 101 project developed by Tapir Liu. PR and bug reports are welcome and can be submitted to the issue list. Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds. |