update dependencies (#296)

This commit is contained in:
tobi
2021-11-13 12:29:08 +01:00
committed by GitHub
parent 2aaec82732
commit 829a934d23
124 changed files with 2453 additions and 1588 deletions

9
vendor/codeberg.org/gruf/go-bytes/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,9 @@
MIT License
Copyright (c) 2021 gruf
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

12
vendor/codeberg.org/gruf/go-bytes/README.md generated vendored Normal file
View File

@@ -0,0 +1,12 @@
drop-in replacement for standard "bytes" library
contains alternative Buffer implementation that provides direct access to the
underlying byte-slice, with some interesting alternative struct methods. provides
no safety guards, if you pass bad values it will blow up in your face...
and alternative `ToUpper()` and `ToLower()` implementations that use lookup
tables for improved performance
provides direct call-throughs to most of the "bytes" library functions to facilitate
this being a direct drop-in. in some time, i may offer alternative implementations
for other functions too

131
vendor/codeberg.org/gruf/go-bytes/buffer.go generated vendored Normal file
View File

@@ -0,0 +1,131 @@
package bytes
import (
"unicode/utf8"
)
// Buffer is a very simple buffer implementation that allows
// access to and reslicing of the underlying byte slice.
type Buffer struct {
B []byte
}
func NewBuffer(b []byte) Buffer {
return Buffer{
B: b,
}
}
func (b *Buffer) Write(p []byte) (int, error) {
b.Grow(len(p))
return copy(b.B[b.Len()-len(p):], p), nil
}
func (b *Buffer) WriteString(s string) (int, error) {
b.Grow(len(s))
return copy(b.B[b.Len()-len(s):], s), nil
}
func (b *Buffer) WriteByte(c byte) error {
l := b.Len()
b.Grow(1)
b.B[l] = c
return nil
}
func (b *Buffer) WriteRune(r rune) (int, error) {
if r < utf8.RuneSelf {
b.WriteByte(byte(r))
return 1, nil
}
l := b.Len()
b.Grow(utf8.UTFMax)
n := utf8.EncodeRune(b.B[l:b.Len()], r)
b.B = b.B[:l+n]
return n, nil
}
func (b *Buffer) WriteAt(p []byte, start int64) (int, error) {
b.Grow(len(p) - int(int64(b.Len())-start))
return copy(b.B[start:], p), nil
}
func (b *Buffer) WriteStringAt(s string, start int64) (int, error) {
b.Grow(len(s) - int(int64(b.Len())-start))
return copy(b.B[start:], s), nil
}
func (b *Buffer) Truncate(size int) {
b.B = b.B[:b.Len()-size]
}
func (b *Buffer) ShiftByte(index int) {
copy(b.B[index:], b.B[index+1:])
}
func (b *Buffer) Shift(start int64, size int) {
copy(b.B[start:], b.B[start+int64(size):])
}
func (b *Buffer) DeleteByte(index int) {
b.ShiftByte(index)
b.Truncate(1)
}
func (b *Buffer) Delete(start int64, size int) {
b.Shift(start, size)
b.Truncate(size)
}
func (b *Buffer) InsertByte(index int64, c byte) {
l := b.Len()
b.Grow(1)
copy(b.B[index+1:], b.B[index:l])
b.B[index] = c
}
func (b *Buffer) Insert(index int64, p []byte) {
l := b.Len()
b.Grow(len(p))
copy(b.B[index+int64(len(p)):], b.B[index:l])
copy(b.B[index:], p)
}
func (b *Buffer) Bytes() []byte {
return b.B
}
func (b *Buffer) String() string {
return string(b.B)
}
func (b *Buffer) StringPtr() string {
return BytesToString(b.B)
}
func (b *Buffer) Cap() int {
return cap(b.B)
}
func (b *Buffer) Len() int {
return len(b.B)
}
func (b *Buffer) Reset() {
b.B = b.B[:0]
}
func (b *Buffer) Grow(size int) {
b.Guarantee(size)
b.B = b.B[:b.Len()+size]
}
func (b *Buffer) Guarantee(size int) {
if size > b.Cap()-b.Len() {
nb := make([]byte, 2*b.Cap()+size)
copy(nb, b.B)
b.B = nb[:b.Len()]
}
}

261
vendor/codeberg.org/gruf/go-bytes/bytes.go generated vendored Normal file
View File

@@ -0,0 +1,261 @@
package bytes
import (
"bytes"
"reflect"
"unsafe"
)
var (
_ Bytes = &Buffer{}
_ Bytes = bytesType{}
)
// Bytes defines a standard way of retrieving the content of a
// byte buffer of some-kind.
type Bytes interface {
// Bytes returns the byte slice content
Bytes() []byte
// String returns byte slice cast directly to string, this
// will cause an allocation but comes with the safety of
// being an immutable Go string
String() string
// StringPtr returns byte slice cast to string via the unsafe
// package. This comes with the same caveats of accessing via
// .Bytes() in that the content is liable change and is NOT
// immutable, despite being a string type
StringPtr() string
}
type bytesType []byte
func (b bytesType) Bytes() []byte {
return b
}
func (b bytesType) String() string {
return string(b)
}
func (b bytesType) StringPtr() string {
return BytesToString(b)
}
// ToBytes casts the provided byte slice as the simplest possible
// Bytes interface implementation
func ToBytes(b []byte) Bytes {
return bytesType(b)
}
// Copy returns a new copy of slice b, does NOT maintain nil values
func Copy(b []byte) []byte {
p := make([]byte, len(b))
copy(p, b)
return p
}
// BytesToString returns byte slice cast to string via the "unsafe" package
func BytesToString(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}
// StringToBytes returns the string cast to string via the "unsafe" and "reflect" packages
func StringToBytes(s string) []byte {
// thank you to https://github.com/valyala/fasthttp/blob/master/bytesconv.go
var b []byte
// Get byte + string headers
bh := (*reflect.SliceHeader)(unsafe.Pointer(&b))
sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
// Manually set bytes to string
bh.Data = sh.Data
bh.Len = sh.Len
bh.Cap = sh.Len
return b
}
// // InsertByte inserts the supplied byte into the slice at provided position
// func InsertByte(b []byte, at int, c byte) []byte {
// return append(append(b[:at], c), b[at:]...)
// }
// // Insert inserts the supplied byte slice into the slice at provided position
// func Insert(b []byte, at int, s []byte) []byte {
// return append(append(b[:at], s...), b[at:]...)
// }
// ToUpper offers a faster ToUpper implementation using a lookup table
func ToUpper(b []byte) {
for i := 0; i < len(b); i++ {
c := &b[i]
*c = toUpperTable[*c]
}
}
// ToLower offers a faster ToLower implementation using a lookup table
func ToLower(b []byte) {
for i := 0; i < len(b); i++ {
c := &b[i]
*c = toLowerTable[*c]
}
}
// HasBytePrefix returns whether b has the provided byte prefix
func HasBytePrefix(b []byte, c byte) bool {
return (len(b) > 0) && (b[0] == c)
}
// HasByteSuffix returns whether b has the provided byte suffix
func HasByteSuffix(b []byte, c byte) bool {
return (len(b) > 0) && (b[len(b)-1] == c)
}
// HasBytePrefix returns b without the provided leading byte
func TrimBytePrefix(b []byte, c byte) []byte {
if HasBytePrefix(b, c) {
return b[1:]
}
return b
}
// TrimByteSuffix returns b without the provided trailing byte
func TrimByteSuffix(b []byte, c byte) []byte {
if HasByteSuffix(b, c) {
return b[:len(b)-1]
}
return b
}
// Compare is a direct call-through to standard library bytes.Compare()
func Compare(b, s []byte) int {
return bytes.Compare(b, s)
}
// Contains is a direct call-through to standard library bytes.Contains()
func Contains(b, s []byte) bool {
return bytes.Contains(b, s)
}
// TrimPrefix is a direct call-through to standard library bytes.TrimPrefix()
func TrimPrefix(b, s []byte) []byte {
return bytes.TrimPrefix(b, s)
}
// TrimSuffix is a direct call-through to standard library bytes.TrimSuffix()
func TrimSuffix(b, s []byte) []byte {
return bytes.TrimSuffix(b, s)
}
// Equal is a direct call-through to standard library bytes.Equal()
func Equal(b, s []byte) bool {
return bytes.Equal(b, s)
}
// EqualFold is a direct call-through to standard library bytes.EqualFold()
func EqualFold(b, s []byte) bool {
return bytes.EqualFold(b, s)
}
// Fields is a direct call-through to standard library bytes.Fields()
func Fields(b []byte) [][]byte {
return bytes.Fields(b)
}
// FieldsFunc is a direct call-through to standard library bytes.FieldsFunc()
func FieldsFunc(b []byte, fn func(rune) bool) [][]byte {
return bytes.FieldsFunc(b, fn)
}
// HasPrefix is a direct call-through to standard library bytes.HasPrefix()
func HasPrefix(b, s []byte) bool {
return bytes.HasPrefix(b, s)
}
// HasSuffix is a direct call-through to standard library bytes.HasSuffix()
func HasSuffix(b, s []byte) bool {
return bytes.HasSuffix(b, s)
}
// Index is a direct call-through to standard library bytes.Index()
func Index(b, s []byte) int {
return bytes.Index(b, s)
}
// IndexByte is a direct call-through to standard library bytes.IndexByte()
func IndexByte(b []byte, c byte) int {
return bytes.IndexByte(b, c)
}
// IndexAny is a direct call-through to standard library bytes.IndexAny()
func IndexAny(b []byte, s string) int {
return bytes.IndexAny(b, s)
}
// IndexRune is a direct call-through to standard library bytes.IndexRune()
func IndexRune(b []byte, r rune) int {
return bytes.IndexRune(b, r)
}
// IndexFunc is a direct call-through to standard library bytes.IndexFunc()
func IndexFunc(b []byte, fn func(rune) bool) int {
return bytes.IndexFunc(b, fn)
}
// LastIndex is a direct call-through to standard library bytes.LastIndex()
func LastIndex(b, s []byte) int {
return bytes.LastIndex(b, s)
}
// LastIndexByte is a direct call-through to standard library bytes.LastIndexByte()
func LastIndexByte(b []byte, c byte) int {
return bytes.LastIndexByte(b, c)
}
// LastIndexAny is a direct call-through to standard library bytes.LastIndexAny()
func LastIndexAny(b []byte, s string) int {
return bytes.LastIndexAny(b, s)
}
// LastIndexFunc is a direct call-through to standard library bytes.LastIndexFunc()
func LastIndexFunc(b []byte, fn func(rune) bool) int {
return bytes.LastIndexFunc(b, fn)
}
// Replace is a direct call-through to standard library bytes.Replace()
func Replace(b, s, r []byte, c int) []byte {
return bytes.Replace(b, s, r, c)
}
// ReplaceAll is a direct call-through to standard library bytes.ReplaceAll()
func ReplaceAll(b, s, r []byte) []byte {
return bytes.ReplaceAll(b, s, r)
}
// Split is a direct call-through to standard library bytes.Split()
func Split(b, s []byte) [][]byte {
return bytes.Split(b, s)
}
// SplitAfter is a direct call-through to standard library bytes.SplitAfter()
func SplitAfter(b, s []byte) [][]byte {
return bytes.SplitAfter(b, s)
}
// SplitN is a direct call-through to standard library bytes.SplitN()
func SplitN(b, s []byte, c int) [][]byte {
return bytes.SplitN(b, s, c)
}
// SplitAfterN is a direct call-through to standard library bytes.SplitAfterN()
func SplitAfterN(b, s []byte, c int) [][]byte {
return bytes.SplitAfterN(b, s, c)
}
// NewReader is a direct call-through to standard library bytes.NewReader()
func NewReader(b []byte) *bytes.Reader {
return bytes.NewReader(b)
}

11
vendor/codeberg.org/gruf/go-bytes/bytesconv_table.go generated vendored Normal file
View File

@@ -0,0 +1,11 @@
package bytes
// Code generated by go run bytesconv_table_gen.go; DO NOT EDIT.
// See bytesconv_table_gen.go for more information about these tables.
//
// Source: https://github.com/valyala/fasthttp/blob/master/bytes_table_gen.go
const (
toLowerTable = "\x00\x01\x02\x03\x04\x05\x06\a\b\t\n\v\f\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&'()*+,-./0123456789:;<=>?@abcdefghijklmnopqrstuvwxyz[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u007f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff"
toUpperTable = "\x00\x01\x02\x03\x04\x05\x06\a\b\t\n\v\f\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`ABCDEFGHIJKLMNOPQRSTUVWXYZ{|}~\u007f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff"
)

9
vendor/codeberg.org/gruf/go-errors/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,9 @@
MIT License
Copyright (c) 2021 gruf
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

1
vendor/codeberg.org/gruf/go-errors/README.md generated vendored Normal file
View File

@@ -0,0 +1 @@
simple but powerful errors library that allows providing context information with errors

74
vendor/codeberg.org/gruf/go-errors/data.go generated vendored Normal file
View File

@@ -0,0 +1,74 @@
package errors
import (
"sync"
"codeberg.org/gruf/go-bytes"
"codeberg.org/gruf/go-logger"
)
// global logfmt data formatter
var logfmt = logger.TextFormat{Strict: false}
// KV is a structure for setting key-value pairs in ErrorData
type KV struct {
Key string
Value interface{}
}
// ErrorData defines a way to set and access contextual error data.
// The default implementation of this is thread-safe
type ErrorData interface {
// Value will attempt to fetch value for given key in ErrorData
Value(string) (interface{}, bool)
// Append adds the supplied key-values to ErrorData, similar keys DO overwrite
Append(...KV)
// String returns a string representation of the ErrorData
String() string
}
// NewData returns a new ErrorData implementation
func NewData() ErrorData {
return &errorData{
data: make(map[string]interface{}, 10),
}
}
// errorData is our ErrorData implementation, this is essentially
// just a thread-safe string-interface map implementation
type errorData struct {
data map[string]interface{}
buf bytes.Buffer
mu sync.Mutex
}
func (d *errorData) Value(key string) (interface{}, bool) {
d.mu.Lock()
v, ok := d.data[key]
d.mu.Unlock()
return v, ok
}
func (d *errorData) Append(kvs ...KV) {
d.mu.Lock()
for i := range kvs {
k := kvs[i].Key
v := kvs[i].Value
d.data[k] = v
}
d.mu.Unlock()
}
func (d *errorData) String() string {
d.mu.Lock()
d.buf.Reset()
d.buf.B = append(d.buf.B, '{')
logfmt.AppendFields(&d.buf, d.data)
d.buf.B = append(d.buf.B, '}')
d.mu.Unlock()
return d.buf.StringPtr()
}

180
vendor/codeberg.org/gruf/go-errors/errors.go generated vendored Normal file
View File

@@ -0,0 +1,180 @@
package errors
import "fmt"
// ErrorContext defines a wrappable error with the ability to hold extra contextual information
type ErrorContext interface {
// implement base error interface
error
// Is identifies whether the receiver contains / is the target
Is(error) bool
// Unwrap reveals the underlying wrapped error (if any!)
Unwrap() error
// Value attempts to fetch contextual data for given key from this ErrorContext
Value(string) (interface{}, bool)
// Append allows adding contextual data to this ErrorContext
Append(...KV) ErrorContext
// Data returns the contextual data structure associated with this ErrorContext
Data() ErrorData
}
// New returns a new ErrorContext created from string
func New(msg string) ErrorContext {
return stringError(msg)
}
// Newf returns a new ErrorContext created from format string
func Newf(s string, a ...interface{}) ErrorContext {
return stringError(fmt.Sprintf(s, a...))
}
// Wrap ensures supplied error is an ErrorContext, wrapping if necessary
func Wrap(err error) ErrorContext {
// Nil error, do nothing
if err == nil {
return nil
}
// Check if this is already wrapped somewhere in stack
if xerr, ok := err.(*errorContext); ok {
return xerr
} else if As(err, &xerr) {
// This is really not an ideal situation,
// but we try to make do by salvaging the
// contextual error data from earlier in
// stack, setting current error to the top
// and setting the unwrapped error to inner
return &errorContext{
data: xerr.data,
innr: Unwrap(err),
err: err,
}
}
// Return new Error type
return &errorContext{
data: NewData(),
innr: nil,
err: err,
}
}
// WrapMsg wraps supplied error as inner, returning an ErrorContext
// with a new outer error made from the supplied message string
func WrapMsg(err error, msg string) ErrorContext {
// Nil error, do nothing
if err == nil {
return nil
}
// Check if this is already wrapped
var xerr *errorContext
if As(err, &xerr) {
return &errorContext{
data: xerr.data,
innr: err,
err: New(msg),
}
}
// Return new wrapped error
return &errorContext{
data: NewData(),
innr: err,
err: stringError(msg),
}
}
// WrapMsgf wraps supplied error as inner, returning an ErrorContext with
// a new outer error made from the supplied message format string
func WrapMsgf(err error, msg string, a ...interface{}) ErrorContext {
return WrapMsg(err, fmt.Sprintf(msg, a...))
}
// ErrorData attempts fetch ErrorData from supplied error, returns nil otherwise
func Data(err error) ErrorData {
x, ok := err.(ErrorContext)
if ok {
return x.Data()
}
return nil
}
// stringError is the simplest ErrorContext implementation
type stringError string
func (e stringError) Error() string {
return string(e)
}
func (e stringError) Is(err error) bool {
se, ok := err.(stringError)
return ok && e == se
}
func (e stringError) Unwrap() error {
return nil
}
func (e stringError) Value(key string) (interface{}, bool) {
return nil, false
}
func (e stringError) Append(kvs ...KV) ErrorContext {
data := NewData()
data.Append(kvs...)
return &errorContext{
data: data,
innr: nil,
err: e,
}
}
func (e stringError) Data() ErrorData {
return nil
}
// errorContext is the *actual* ErrorContext implementation
type errorContext struct {
// data contains any appended context data, there will only ever be one
// instance of data within an ErrorContext stack
data ErrorData
// innr is the inner wrapped error in this structure, it is only accessible
// via .Unwrap() or via .Is()
innr error
// err is the top-level error in this wrapping structure, we identify
// as this error type via .Is() and return its error message
err error
}
func (e *errorContext) Error() string {
return e.err.Error()
}
func (e *errorContext) Is(err error) bool {
return Is(e.err, err) || Is(e.innr, err)
}
func (e *errorContext) Unwrap() error {
return e.innr
}
func (e *errorContext) Value(key string) (interface{}, bool) {
return e.data.Value(key)
}
func (e *errorContext) Append(kvs ...KV) ErrorContext {
e.data.Append(kvs...)
return e
}
func (e *errorContext) Data() ErrorData {
return e.data
}

45
vendor/codeberg.org/gruf/go-errors/once.go generated vendored Normal file
View File

@@ -0,0 +1,45 @@
package errors
import (
"sync/atomic"
"unsafe"
)
// OnceError is an error structure that supports safe multi-threaded
// usage and setting only once (until reset)
type OnceError struct {
err unsafe.Pointer
}
// NewOnce returns a new OnceError instance
func NewOnce() OnceError {
return OnceError{
err: nil,
}
}
func (e *OnceError) Store(err error) {
// Nothing to do
if err == nil {
return
}
// Only set if not already
atomic.CompareAndSwapPointer(
&e.err,
nil,
unsafe.Pointer(&err),
)
}
func (e *OnceError) Load() error {
return *(*error)(atomic.LoadPointer(&e.err))
}
func (e *OnceError) IsSet() bool {
return (atomic.LoadPointer(&e.err) != nil)
}
func (e *OnceError) Reset() {
atomic.StorePointer(&e.err, nil)
}

18
vendor/codeberg.org/gruf/go-errors/std.go generated vendored Normal file
View File

@@ -0,0 +1,18 @@
package errors
import "errors"
// Is wraps "errors".Is()
func Is(err, target error) bool {
return errors.Is(err, target)
}
// As wraps "errors".As()
func As(err error, target interface{}) bool {
return errors.As(err, target)
}
// Unwrap wraps "errors".Unwrap()
func Unwrap(err error) error {
return errors.Unwrap(err)
}

9
vendor/codeberg.org/gruf/go-fastpath/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,9 @@
MIT License
Copyright (c) 2021 gruf
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

1
vendor/codeberg.org/gruf/go-fastpath/README.md generated vendored Normal file
View File

@@ -0,0 +1 @@
Alternative path library with a `strings.Builder` like path builder.

BIN
vendor/codeberg.org/gruf/go-fastpath/benchmarks.png generated vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 106 KiB

326
vendor/codeberg.org/gruf/go-fastpath/path.go generated vendored Normal file
View File

@@ -0,0 +1,326 @@
package fastpath
import (
"unsafe"
)
// allocate these just once
var (
dot = []byte(".")
dotStr = ".'"
)
type Builder struct {
B []byte // B is the underlying byte buffer
dd int // pos of last '..' appended to builder
abs bool // abs stores whether path passed to first .Append() is absolute
set bool // set stores whether b.abs has been set i.e. not first call to .Append()
}
// NewBuilder returns a new Builder object using the supplied byte
// slice as the underlying buffer
func NewBuilder(b []byte) Builder {
if b != nil {
b = b[:0]
}
return Builder{
B: b,
dd: 0,
abs: false,
set: false,
}
}
// Reset resets the Builder object
func (b *Builder) Reset() {
b.B = b.B[:0]
b.dd = 0
b.abs = false
b.set = false
}
// Len returns the number of accumulated bytes in the Builder
func (b *Builder) Len() int {
return len(b.B)
}
// Cap returns the capacity of the underlying Builder buffer
func (b *Builder) Cap() int {
return cap(b.B)
}
// Bytes returns the accumulated path bytes.
func (b *Builder) Bytes() []byte {
if b.Len() < 1 {
return dot
}
return b.B
}
// String returns the accumulated path string.
func (b *Builder) String() string {
if b.Len() < 1 {
return dotStr
}
return string(b.B)
}
// StringPtr returns a ptr to the accumulated path string.
//
// Please note the underlying byte slice for this string is
// tied to the builder, so any changes will result in the
// returned string changing. Consider using .String() if
// this is undesired behaviour.
func (b *Builder) StringPtr() string {
if b.Len() < 1 {
return dotStr
}
return *(*string)(unsafe.Pointer(&b.B))
}
// Absolute returns whether current path is absolute (not relative)
func (b *Builder) Absolute() bool {
return b.abs
}
// SetAbsolute converts the current path to / from absolute
func (b *Builder) SetAbsolute(val bool) {
if !b.set {
if val {
// .Append() has not be called,
// add a '/' and set abs
b.guarantee(1)
b.appendByte('/')
b.abs = true
}
// Set as having been set
b.set = true
return
}
if !val && b.abs {
// Already set and absolute. Update
b.abs = false
// If not empty (i.e. not just '/'),
// then shift bytes 1 left
if b.Len() > 1 {
copy(b.B, b.B[1:])
}
// Truncate 1 byte. In the case of empty,
// i.e. just '/' then it will drop this
b.truncate(1)
} else if val && !b.abs {
// Already set but NOT abs. Update
b.abs = true
// Guarantee 1 byte available
b.guarantee(1)
// If empty, just append '/'
if b.Len() < 1 {
b.appendByte('/')
return
}
// Increase length
l := b.Len()
b.B = b.B[:l+1]
// Shift bytes 1 right
copy(b.B[1:], b.B[:l])
// Set first byte '/'
b.B[0] = '/'
}
}
// Append adds and cleans the supplied path bytes to the
// builder's internal buffer, growing the buffer if necessary
// to accomodate the extra path length
func (b *Builder) Append(p []byte) {
b.AppendString(*(*string)(unsafe.Pointer(&p)))
}
// AppendString adds and cleans the supplied path string to the
// builder's internal buffer, growing the buffer if necessary
// to accomodate the extra path length
func (b *Builder) AppendString(path string) {
defer func() {
// If buffer is empty, and an absolute path,
// ensure it starts with a '/'
if b.Len() < 1 && b.abs {
b.appendByte('/')
}
}()
// Empty path, nothing to do
if len(path) == 0 {
return
}
// Guarantee at least the total length
// of supplied path available in the buffer
b.guarantee(len(path))
// Try store if absolute
if !b.set {
b.abs = len(path) > 0 && path[0] == '/'
b.set = true
}
i := 0
for i < len(path) {
switch {
// Empty path segment
case path[i] == '/':
i++
// Singular '.' path segment, treat as empty
case path[i] == '.' && (i+1 == len(path) || path[i+1] == '/'):
i++
// Backtrack segment
case path[i] == '.' && path[i+1] == '.' && (i+2 == len(path) || path[i+2] == '/'):
i += 2
switch {
// Check if it's possible to backtrack with
// our current state of the buffer. i.e. is
// our buffer length longer than the last
// '..' we placed?
case b.Len() > b.dd:
b.backtrack()
// b.cp = b.lp
// b.lp = 0
// If we reached here, need to check if
// we can append '..' to the path buffer,
// which is ONLY when path is NOT absolute
case !b.abs:
if b.Len() > 0 {
b.appendByte('/')
}
b.appendByte('.')
b.appendByte('.')
b.dd = b.Len()
// b.lp = lp - 2
// b.cp = b.dd
}
default:
if (b.abs && b.Len() != 1) || (!b.abs && b.Len() > 0) {
b.appendByte('/')
}
// b.lp = b.cp
// b.cp = b.Len()
i += b.appendSlice(path[i:])
}
}
}
// Clean creates the shortest possible functional equivalent
// to the supplied path, resetting the builder before performing
// this operation. The builder object is NOT reset after return
func (b *Builder) Clean(path string) string {
b.Reset()
b.AppendString(path)
return b.String()
}
// Join connects and cleans multiple paths, resetting the builder before
// performing this operation and returning the shortest possible combination
// of all the supplied paths. The builder object is NOT reset after return
func (b *Builder) Join(base string, paths ...string) string {
empty := (len(base) < 1)
b.Reset()
b.AppendString(base)
for _, path := range paths {
b.AppendString(path)
empty = empty && (len(path) < 1)
}
if empty {
return ""
}
return b.String()
}
// Guarantee ensures there is at least the requested size
// free bytes available in the buffer, reallocating if
// necessary
func (b *Builder) Guarantee(size int) {
b.guarantee(size)
}
// Truncate reduces the length of the buffer by the requested
// number of bytes. If the builder is set to absolute, the first
// byte (i.e. '/') will never be truncated
func (b *Builder) Truncate(size int) {
// If absolute and just '/', do nothing
if b.abs && b.Len() == 1 {
return
}
// Truncate requested bytes
b.truncate(size)
}
// truncate reduces the length of the buffer by the requested size,
// no sanity checks are performed
func (b *Builder) truncate(size int) {
b.B = b.B[:b.Len()-size]
}
// guarantee ensures there is at least the requested size
// free bytes available in the buffer, reallocating if necessary.
// no sanity checks are performed
func (b *Builder) guarantee(size int) {
if size > b.Cap()-b.Len() {
nb := make([]byte, 2*b.Cap()+size)
copy(nb, b.B)
b.B = nb[:b.Len()]
}
}
// appendByte appends the supplied byte to the end of
// the buffer. appending is achieved by continually reslicing the
// buffer and setting the next byte-at-index, this is safe as guarantee()
// will have been called beforehand
func (b *Builder) appendByte(c byte) {
b.B = b.B[:b.Len()+1]
b.B[b.Len()-1] = c
}
// appendSlice appends the supplied string slice to
// the end of the buffer and returns the number of indices
// we were able to iterate before hitting a path separator '/'.
// appending is achieved by continually reslicing the buffer
// and setting the next byte-at-index, this is safe as guarantee()
// will have been called beforehand
func (b *Builder) appendSlice(slice string) int {
i := 0
for i < len(slice) && slice[i] != '/' {
b.B = b.B[:b.Len()+1]
b.B[b.Len()-1] = slice[i]
i++
}
return i
}
// backtrack reduces the end of the buffer back to the last
// separating '/', or end of buffer
func (b *Builder) backtrack() {
b.B = b.B[:b.Len()-1]
for b.Len()-1 > b.dd && b.B[b.Len()-1] != '/' {
b.B = b.B[:b.Len()-1]
}
if b.Len() > 0 {
b.B = b.B[:b.Len()-1]
}
}

9
vendor/codeberg.org/gruf/go-hashenc/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,9 @@
MIT License
Copyright (c) 2021 gruf
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

1
vendor/codeberg.org/gruf/go-hashenc/README.md generated vendored Normal file
View File

@@ -0,0 +1 @@
HashEncoder provides a means of quickly hash-summing and encoding data

42
vendor/codeberg.org/gruf/go-hashenc/enc.go generated vendored Normal file
View File

@@ -0,0 +1,42 @@
package hashenc
import (
"encoding/base32"
"encoding/base64"
"encoding/hex"
)
// Encoder defines an interface for encoding binary data
type Encoder interface {
// Encode encodes the data at src into dst
Encode(dst []byte, src []byte)
// EncodedLen returns the encoded length for input data of supplied length
EncodedLen(int) int
}
// Base32 returns a new base32 Encoder
func Base32() Encoder {
return base32.StdEncoding.WithPadding(base64.NoPadding)
}
// Base64 returns a new base64 Encoder
func Base64() Encoder {
return base64.URLEncoding.WithPadding(base64.NoPadding)
}
// Hex returns a new hex Encoder
func Hex() Encoder {
return &hexEncoder{}
}
// hexEncoder simply provides an empty receiver to satisfy Encoder
type hexEncoder struct{}
func (*hexEncoder) Encode(dst []byte, src []byte) {
hex.Encode(dst, src)
}
func (*hexEncoder) EncodedLen(len int) int {
return hex.EncodedLen(len)
}

136
vendor/codeberg.org/gruf/go-hashenc/hash.go generated vendored Normal file
View File

@@ -0,0 +1,136 @@
package hashenc
import (
"crypto/md5"
"crypto/sha1"
"crypto/sha256"
"crypto/sha512"
"hash"
"sync"
)
// Hash defines a pooled hash.Hash implementation
type Hash interface {
// Hash ensures we implement the base hash.Hash implementation
hash.Hash
// Release resets the Hash and places it back in the pool
Release()
}
// poolHash is our Hash implementation, providing a hash.Hash and a pool to return to
type poolHash struct {
hash.Hash
pool *sync.Pool
}
func (h *poolHash) Release() {
h.Reset()
h.pool.Put(h)
}
// SHA512Pool defines a pool of SHA512 hashes
type SHA512Pool interface {
// SHA512 returns a Hash implementing the SHA512 hashing algorithm
SHA512() Hash
}
// NewSHA512Pool returns a new SHA512Pool implementation
func NewSHA512Pool() SHA512Pool {
p := &sha512Pool{}
p.New = func() interface{} {
return &poolHash{
Hash: sha512.New(),
pool: &p.Pool,
}
}
return p
}
// sha512Pool is our SHA512Pool implementation, simply wrapping sync.Pool
type sha512Pool struct {
sync.Pool
}
func (p *sha512Pool) SHA512() Hash {
return p.Get().(Hash)
}
// SHA256Pool defines a pool of SHA256 hashes
type SHA256Pool interface {
// SHA256 returns a Hash implementing the SHA256 hashing algorithm
SHA256() Hash
}
// NewSHA256Pool returns a new SHA256Pool implementation
func NewSHA256Pool() SHA256Pool {
p := &sha256Pool{}
p.New = func() interface{} {
return &poolHash{
Hash: sha256.New(),
pool: &p.Pool,
}
}
return p
}
// sha256Pool is our SHA256Pool implementation, simply wrapping sync.Pool
type sha256Pool struct {
sync.Pool
}
func (p *sha256Pool) SHA256() Hash {
return p.Get().(Hash)
}
// SHA1Pool defines a pool of SHA1 hashes
type SHA1Pool interface {
SHA1() Hash
}
// NewSHA1Pool returns a new SHA1Pool implementation
func NewSHA1Pool() SHA1Pool {
p := &sha1Pool{}
p.New = func() interface{} {
return &poolHash{
Hash: sha1.New(),
pool: &p.Pool,
}
}
return p
}
// sha1Pool is our SHA1Pool implementation, simply wrapping sync.Pool
type sha1Pool struct {
sync.Pool
}
func (p *sha1Pool) SHA1() Hash {
return p.Get().(Hash)
}
// MD5Pool defines a pool of MD5 hashes
type MD5Pool interface {
MD5() Hash
}
// NewMD5Pool returns a new MD5 implementation
func NewMD5Pool() MD5Pool {
p := &md5Pool{}
p.New = func() interface{} {
return &poolHash{
Hash: md5.New(),
pool: &p.Pool,
}
}
return p
}
// md5Pool is our MD5Pool implementation, simply wrapping sync.Pool
type md5Pool struct {
sync.Pool
}
func (p *md5Pool) MD5() Hash {
return p.Get().(Hash)
}

58
vendor/codeberg.org/gruf/go-hashenc/hashenc.go generated vendored Normal file
View File

@@ -0,0 +1,58 @@
package hashenc
import (
"hash"
"codeberg.org/gruf/go-bytes"
)
// HashEncoder defines an interface for calculating encoded hash sums of binary data
type HashEncoder interface {
// EncodeSum calculates the hash sum of src and encodes (at most) Size() into dst
EncodeSum(dst []byte, src []byte)
// EncodedSum calculates the encoded hash sum of src and returns data in a newly allocated bytes.Bytes
EncodedSum(src []byte) bytes.Bytes
// Size returns the expected length of encoded hashes
Size() int
}
// New returns a new HashEncoder instance based on supplied hash.Hash and Encoder supplying functions
func New(hash hash.Hash, enc Encoder) HashEncoder {
hashSize := hash.Size()
return &henc{
hash: hash,
hbuf: make([]byte, hashSize),
enc: enc,
size: enc.EncodedLen(hashSize),
}
}
// henc is the HashEncoder implementation
type henc struct {
hash hash.Hash
hbuf []byte
enc Encoder
size int
}
func (henc *henc) EncodeSum(dst []byte, src []byte) {
// Hash supplied bytes
henc.hash.Reset()
henc.hash.Write(src)
henc.hbuf = henc.hash.Sum(henc.hbuf[:0])
// Encode the hashsum and return a copy
henc.enc.Encode(dst, henc.hbuf)
}
func (henc *henc) EncodedSum(src []byte) bytes.Bytes {
dst := make([]byte, henc.size)
henc.EncodeSum(dst, src)
return bytes.ToBytes(dst)
}
func (henc *henc) Size() int {
return henc.size
}

9
vendor/codeberg.org/gruf/go-logger/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,9 @@
MIT License
Copyright (c) 2021 gruf
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

9
vendor/codeberg.org/gruf/go-logger/README.md generated vendored Normal file
View File

@@ -0,0 +1,9 @@
Fast levelled logging package with customizable formatting.
Supports logging in 2 modes:
- no locks, fastest possible logging, no guarantees for io.Writer thread safety
- mutex locks during writes, still far faster than standard library logger
Running without locks isn't likely to cause you any issues*, but if it does, you can wrap your `io.Writer` using `AddSafety()` when instantiating your new Logger. Even when running the benchmarks, this library has no printing issues without locks, so in most cases you'll be fine, but the safety is there if you need it.
*most logging libraries advertising high speeds are likely not performing mutex locks, which is why with this library you have the option to opt-in/out of them.

21
vendor/codeberg.org/gruf/go-logger/clock.go generated vendored Normal file
View File

@@ -0,0 +1,21 @@
package logger
import (
"sync"
"time"
"codeberg.org/gruf/go-nowish"
)
var (
clock = nowish.Clock{}
clockOnce = sync.Once{}
)
// startClock starts the global nowish clock
func startClock() {
clockOnce.Do(func() {
clock.Start(time.Millisecond * 10)
clock.SetFormat("2006-01-02 15:04:05")
})
}

87
vendor/codeberg.org/gruf/go-logger/default.go generated vendored Normal file
View File

@@ -0,0 +1,87 @@
package logger
import (
"os"
"sync"
)
var (
instance *Logger
instanceOnce = sync.Once{}
)
// Default returns the default Logger instance
func Default() *Logger {
instanceOnce.Do(func() { instance = New(os.Stdout) })
return instance
}
// Debug prints the provided arguments with the debug prefix to the global Logger instance
func Debug(a ...interface{}) {
Default().Debug(a...)
}
// Debugf prints the provided format string and arguments with the debug prefix to the global Logger instance
func Debugf(s string, a ...interface{}) {
Default().Debugf(s, a...)
}
// Info prints the provided arguments with the info prefix to the global Logger instance
func Info(a ...interface{}) {
Default().Info(a...)
}
// Infof prints the provided format string and arguments with the info prefix to the global Logger instance
func Infof(s string, a ...interface{}) {
Default().Infof(s, a...)
}
// Warn prints the provided arguments with the warn prefix to the global Logger instance
func Warn(a ...interface{}) {
Default().Warn(a...)
}
// Warnf prints the provided format string and arguments with the warn prefix to the global Logger instance
func Warnf(s string, a ...interface{}) {
Default().Warnf(s, a...)
}
// Error prints the provided arguments with the error prefix to the global Logger instance
func Error(a ...interface{}) {
Default().Error(a...)
}
// Errorf prints the provided format string and arguments with the error prefix to the global Logger instance
func Errorf(s string, a ...interface{}) {
Default().Errorf(s, a...)
}
// Fatal prints the provided arguments with the fatal prefix to the global Logger instance before exiting the program with os.Exit(1)
func Fatal(a ...interface{}) {
Default().Fatal(a...)
}
// Fatalf prints the provided format string and arguments with the fatal prefix to the global Logger instance before exiting the program with os.Exit(1)
func Fatalf(s string, a ...interface{}) {
Default().Fatalf(s, a...)
}
// Log prints the provided arguments with the supplied log level to the global Logger instance
func Log(lvl LEVEL, a ...interface{}) {
Default().Log(lvl, a...)
}
// Logf prints the provided format string and arguments with the supplied log level to the global Logger instance
func Logf(lvl LEVEL, s string, a ...interface{}) {
Default().Logf(lvl, s, a...)
}
// Print simply prints provided arguments to the global Logger instance
func Print(a ...interface{}) {
Default().Print(a...)
}
// Printf simply prints provided the provided format string and arguments to the global Logger instance
func Printf(s string, a ...interface{}) {
Default().Printf(s, a...)
}

231
vendor/codeberg.org/gruf/go-logger/entry.go generated vendored Normal file
View File

@@ -0,0 +1,231 @@
package logger
import (
"context"
"time"
"codeberg.org/gruf/go-bytes"
)
// Entry defines an entry in the log
type Entry struct {
ctx context.Context
lvl LEVEL
buf *bytes.Buffer
log *Logger
}
// Context returns the current set Entry context.Context
func (e *Entry) Context() context.Context {
return e.ctx
}
// WithContext updates Entry context value to the supplied
func (e *Entry) WithContext(ctx context.Context) *Entry {
e.ctx = ctx
return e
}
// Level appends the supplied level to the log entry, and sets the entry level.
// Please note this CAN be called and append log levels multiple times
func (e *Entry) Level(lvl LEVEL) *Entry {
e.log.Format.AppendLevel(e.buf, lvl)
e.buf.WriteByte(' ')
e.lvl = lvl
return e
}
// Timestamp appends the current timestamp to the log entry. Please note this
// CAN be called and append the timestamp multiple times
func (e *Entry) Timestamp() *Entry {
e.log.Format.AppendTimestamp(e.buf, clock.NowFormat())
e.buf.WriteByte(' ')
return e
}
// TimestampIf performs Entry.Timestamp() only IF timestamping is enabled for the Logger.
// Please note this CAN be called multiple times
func (e *Entry) TimestampIf() *Entry {
if e.log.Timestamp {
e.Timestamp()
}
return e
}
// Hooks applies currently set Hooks to the Entry. Please note this CAN be
// called and perform the Hooks multiple times
func (e *Entry) Hooks() *Entry {
for _, hook := range e.log.Hooks {
hook.Do(e)
}
return e
}
// Byte appends a byte value as key-value pair to the log entry
func (e *Entry) Byte(key string, value byte) *Entry {
e.log.Format.AppendByteField(e.buf, key, value)
e.buf.WriteByte(' ')
return e
}
// Bytes appends a byte slice value as key-value pair to the log entry
func (e *Entry) Bytes(key string, value []byte) *Entry {
e.log.Format.AppendBytesField(e.buf, key, value)
e.buf.WriteByte(' ')
return e
}
// Str appends a string value as key-value pair to the log entry
func (e *Entry) Str(key string, value string) *Entry {
e.log.Format.AppendStringField(e.buf, key, value)
e.buf.WriteByte(' ')
return e
}
// Strs appends a string slice value as key-value pair to the log entry
func (e *Entry) Strs(key string, value []string) *Entry {
e.log.Format.AppendStringsField(e.buf, key, value)
e.buf.WriteByte(' ')
return e
}
// Int appends an int value as key-value pair to the log entry
func (e *Entry) Int(key string, value int) *Entry {
e.log.Format.AppendIntField(e.buf, key, value)
e.buf.WriteByte(' ')
return e
}
// Ints appends an int slice value as key-value pair to the log entry
func (e *Entry) Ints(key string, value []int) *Entry {
e.log.Format.AppendIntsField(e.buf, key, value)
e.buf.WriteByte(' ')
return e
}
// Uint appends a uint value as key-value pair to the log entry
func (e *Entry) Uint(key string, value uint) *Entry {
e.log.Format.AppendUintField(e.buf, key, value)
e.buf.WriteByte(' ')
return e
}
// Uints appends a uint slice value as key-value pair to the log entry
func (e *Entry) Uints(key string, value []uint) *Entry {
e.log.Format.AppendUintsField(e.buf, key, value)
e.buf.WriteByte(' ')
return e
}
// Float appends a float value as key-value pair to the log entry
func (e *Entry) Float(key string, value float64) *Entry {
e.log.Format.AppendFloatField(e.buf, key, value)
e.buf.WriteByte(' ')
return e
}
// Floats appends a float slice value as key-value pair to the log entry
func (e *Entry) Floats(key string, value []float64) *Entry {
e.log.Format.AppendFloatsField(e.buf, key, value)
e.buf.WriteByte(' ')
return e
}
// Bool appends a bool value as key-value pair to the log entry
func (e *Entry) Bool(key string, value bool) *Entry {
e.log.Format.AppendBoolField(e.buf, key, value)
e.buf.WriteByte(' ')
return e
}
// Bools appends a bool slice value as key-value pair to the log entry
func (e *Entry) Bools(key string, value []bool) *Entry {
e.log.Format.AppendBoolsField(e.buf, key, value)
e.buf.WriteByte(' ')
return e
}
// Time appends a time.Time value as key-value pair to the log entry
func (e *Entry) Time(key string, value time.Time) *Entry {
e.log.Format.AppendTimeField(e.buf, key, value)
e.buf.WriteByte(' ')
return e
}
// Times appends a time.Time slice value as key-value pair to the log entry
func (e *Entry) Times(key string, value []time.Time) *Entry {
e.log.Format.AppendTimesField(e.buf, key, value)
e.buf.WriteByte(' ')
return e
}
// Duration appends a time.Duration value as key-value pair to the log entry
func (e *Entry) Duration(key string, value time.Duration) *Entry {
e.log.Format.AppendDurationField(e.buf, key, value)
e.buf.WriteByte(' ')
return e
}
// Durations appends a time.Duration slice value as key-value pair to the log entry
func (e *Entry) Durations(key string, value []time.Duration) *Entry {
e.log.Format.AppendDurationsField(e.buf, key, value)
e.buf.WriteByte(' ')
return e
}
// Field appends an interface value as key-value pair to the log entry
func (e *Entry) Field(key string, value interface{}) *Entry {
e.log.Format.AppendField(e.buf, key, value)
e.buf.WriteByte(' ')
return e
}
// Fields appends a map of key-value pairs to the log entry
func (e *Entry) Fields(fields map[string]interface{}) *Entry {
e.log.Format.AppendFields(e.buf, fields)
e.buf.WriteByte(' ')
return e
}
// Msg appends the formatted final message to the log and calls .Send()
func (e *Entry) Msg(a ...interface{}) {
e.log.Format.AppendMsg(e.buf, a...)
e.Send()
}
// Msgf appends the formatted final message to the log and calls .Send()
func (e *Entry) Msgf(s string, a ...interface{}) {
e.log.Format.AppendMsgf(e.buf, s, a...)
e.Send()
}
// Send triggers write of the log entry, skipping if the entry's log LEVEL
// is below the currently set Logger level, and releases the Entry back to
// the Logger's Entry pool. So it is NOT safe to continue using this Entry
// object after calling .Send(), .Msg() or .Msgf()
func (e *Entry) Send() {
// If nothing to do, return
if e.lvl < e.log.Level || e.buf.Len() < 1 {
e.reset()
return
}
// Final new line
if e.buf.B[e.buf.Len()-1] != '\n' {
e.buf.WriteByte('\n')
}
// Write, reset and release
e.log.Output.Write(e.buf.B)
e.reset()
}
func (e *Entry) reset() {
// Reset all
e.ctx = nil
e.buf.Reset()
e.lvl = unset
// Release to pool
e.log.pool.Put(e)
}

640
vendor/codeberg.org/gruf/go-logger/format.go generated vendored Normal file
View File

@@ -0,0 +1,640 @@
package logger
import (
"fmt"
"reflect"
"strconv"
"time"
"codeberg.org/gruf/go-bytes"
)
// Check our types impl LogFormat
var _ LogFormat = &TextFormat{}
// LogFormat defines a method of formatting log entries
type LogFormat interface {
AppendLevel(buf *bytes.Buffer, lvl LEVEL)
AppendTimestamp(buf *bytes.Buffer, fmtNow string)
AppendField(buf *bytes.Buffer, key string, value interface{})
AppendFields(buf *bytes.Buffer, fields map[string]interface{})
AppendByteField(buf *bytes.Buffer, key string, value byte)
AppendBytesField(buf *bytes.Buffer, key string, value []byte)
AppendStringField(buf *bytes.Buffer, key string, value string)
AppendStringsField(buf *bytes.Buffer, key string, value []string)
AppendBoolField(buf *bytes.Buffer, key string, value bool)
AppendBoolsField(buf *bytes.Buffer, key string, value []bool)
AppendIntField(buf *bytes.Buffer, key string, value int)
AppendIntsField(buf *bytes.Buffer, key string, value []int)
AppendUintField(buf *bytes.Buffer, key string, value uint)
AppendUintsField(buf *bytes.Buffer, key string, value []uint)
AppendFloatField(buf *bytes.Buffer, key string, value float64)
AppendFloatsField(buf *bytes.Buffer, key string, value []float64)
AppendTimeField(buf *bytes.Buffer, key string, value time.Time)
AppendTimesField(buf *bytes.Buffer, key string, value []time.Time)
AppendDurationField(buf *bytes.Buffer, key string, value time.Duration)
AppendDurationsField(buf *bytes.Buffer, key string, value []time.Duration)
AppendMsg(buf *bytes.Buffer, a ...interface{})
AppendMsgf(buf *bytes.Buffer, s string, a ...interface{})
}
// TextFormat is the default LogFormat implementation, with very similar formatting to logfmt
type TextFormat struct {
// Strict defines whether to use strict key-value pair formatting,
// i.e. should the level, timestamp and msg be formatted as key-value pairs
// or simply be printed as-is
Strict bool
// Levels defines the map of log LEVELs to level strings this LogFormat will use
Levels Levels
}
// NewLogFmt returns a newly set LogFmt object, with DefaultLevels() set
func NewLogFmt(strict bool) *TextFormat {
return &TextFormat{
Strict: strict,
Levels: DefaultLevels(),
}
}
// appendReflectValue will safely append a reflected value
func appendReflectValue(buf *bytes.Buffer, v reflect.Value, isKey bool) {
switch v.Kind() {
case reflect.Slice:
appendSliceType(buf, v)
case reflect.Map:
appendMapType(buf, v)
case reflect.Struct:
appendStructType(buf, v)
case reflect.Ptr:
if v.IsNil() {
appendNil(buf)
} else {
appendIface(buf, v.Elem().Interface(), isKey)
}
default:
// Just print reflect string
appendString(buf, v.String())
}
}
// appendKey should only be used in the case of directly setting key-value pairs,
// not in the case of appendMapType, appendStructType
func appendKey(buf *bytes.Buffer, key string) {
if len(key) > 0 {
// Only write key if here
appendStringUnquoted(buf, key)
buf.WriteByte('=')
}
}
// appendSlice performs provided fn and writes square brackets [] around it
func appendSlice(buf *bytes.Buffer, fn func()) {
buf.WriteByte('[')
fn()
buf.WriteByte(']')
}
// appendMap performs provided fn and writes curly braces {} around it
func appendMap(buf *bytes.Buffer, fn func()) {
buf.WriteByte('{')
fn()
buf.WriteByte('}')
}
// appendStruct performs provided fn and writes curly braces {} around it
func appendStruct(buf *bytes.Buffer, fn func()) {
buf.WriteByte('{')
fn()
buf.WriteByte('}')
}
// appendNil writes a nil value placeholder to buf
func appendNil(buf *bytes.Buffer) {
buf.WriteString(`<nil>`)
}
// appendByte writes a single byte to buf
func appendByte(buf *bytes.Buffer, b byte) {
buf.WriteByte(b)
}
// appendBytes writes a quoted byte slice to buf
func appendBytes(buf *bytes.Buffer, b []byte) {
buf.WriteByte('"')
buf.Write(b)
buf.WriteByte('"')
}
// appendBytesUnquoted writes a byte slice to buf as-is
func appendBytesUnquoted(buf *bytes.Buffer, b []byte) {
buf.Write(b)
}
// appendString writes a quoted string to buf
func appendString(buf *bytes.Buffer, s string) {
buf.WriteByte('"')
buf.WriteString(s)
buf.WriteByte('"')
}
// appendStringUnquoted writes a string as-is to buf
func appendStringUnquoted(buf *bytes.Buffer, s string) {
buf.WriteString(s)
}
// appendStringSlice writes a slice of strings to buf
func appendStringSlice(buf *bytes.Buffer, s []string) {
appendSlice(buf, func() {
for _, s := range s {
appendString(buf, s)
buf.WriteByte(',')
}
if len(s) > 0 {
buf.Truncate(1)
}
})
}
// appendBool writes a formatted bool to buf
func appendBool(buf *bytes.Buffer, b bool) {
buf.B = strconv.AppendBool(buf.B, b)
}
// appendBool writes a slice of formatted bools to buf
func appendBoolSlice(buf *bytes.Buffer, b []bool) {
appendSlice(buf, func() {
// Write elements
for _, b := range b {
appendBool(buf, b)
buf.WriteByte(',')
}
// Drop last comma
if len(b) > 0 {
buf.Truncate(1)
}
})
}
// appendInt writes a formatted int to buf
func appendInt(buf *bytes.Buffer, i int64) {
buf.B = strconv.AppendInt(buf.B, i, 10)
}
// appendIntSlice writes a slice of formatted int to buf
func appendIntSlice(buf *bytes.Buffer, i []int) {
appendSlice(buf, func() {
// Write elements
for _, i := range i {
appendInt(buf, int64(i))
buf.WriteByte(',')
}
// Drop last comma
if len(i) > 0 {
buf.Truncate(1)
}
})
}
// appendUint writes a formatted uint to buf
func appendUint(buf *bytes.Buffer, u uint64) {
buf.B = strconv.AppendUint(buf.B, u, 10)
}
// appendUintSlice writes a slice of formatted uint to buf
func appendUintSlice(buf *bytes.Buffer, u []uint) {
appendSlice(buf, func() {
// Write elements
for _, u := range u {
appendUint(buf, uint64(u))
buf.WriteByte(',')
}
// Drop last comma
if len(u) > 0 {
buf.Truncate(1)
}
})
}
// appendFloat writes a formatted float to buf
func appendFloat(buf *bytes.Buffer, f float64) {
buf.B = strconv.AppendFloat(buf.B, f, 'G', -1, 64)
}
// appendFloatSlice writes a slice formatted floats to buf
func appendFloatSlice(buf *bytes.Buffer, f []float64) {
appendSlice(buf, func() {
// Write elements
for _, f := range f {
appendFloat(buf, f)
buf.WriteByte(',')
}
// Drop last comma
if len(f) > 0 {
buf.Truncate(1)
}
})
}
// appendTime writes a formatted, quoted time string to buf
func appendTime(buf *bytes.Buffer, t time.Time) {
buf.WriteByte('"')
buf.B = t.AppendFormat(buf.B, time.RFC1123)
buf.WriteByte('"')
}
// appendTimeUnquoted writes a formatted time string to buf as-is
func appendTimeUnquoted(buf *bytes.Buffer, t time.Time) {
buf.B = t.AppendFormat(buf.B, time.RFC1123)
}
// appendTimeSlice writes a slice of formatted time strings to buf
func appendTimeSlice(buf *bytes.Buffer, t []time.Time) {
appendSlice(buf, func() {
// Write elements
for _, t := range t {
appendTime(buf, t)
buf.WriteByte(',')
}
// Drop last comma
if len(t) > 0 {
buf.Truncate(1)
}
})
}
// appendDuration writes a formatted, quoted duration string to buf
func appendDuration(buf *bytes.Buffer, d time.Duration) {
appendString(buf, d.String())
}
// appendDurationUnquoted writes a formatted duration string to buf as-is
func appendDurationUnquoted(buf *bytes.Buffer, d time.Duration) {
appendStringUnquoted(buf, d.String())
}
// appendDurationSlice writes a slice of formatted, quoted duration strings to buf
func appendDurationSlice(buf *bytes.Buffer, d []time.Duration) {
appendSlice(buf, func() {
// Write elements
for _, d := range d {
appendString(buf, d.String())
buf.WriteByte(',')
}
// Drop last comma
if len(d) > 0 {
buf.Truncate(1)
}
})
}
// appendIface parses and writes a formatted interface value to buf
func appendIface(buf *bytes.Buffer, i interface{}, isKey bool) {
switch i := i.(type) {
case nil:
appendNil(buf)
case byte:
appendByte(buf, i)
case []byte:
if isKey {
// Keys don't get quoted
appendBytesUnquoted(buf, i)
} else {
appendBytes(buf, i)
}
case string:
if isKey {
// Keys don't get quoted
appendStringUnquoted(buf, i)
} else {
appendString(buf, i)
}
case []string:
appendStringSlice(buf, i)
case int:
appendInt(buf, int64(i))
case int8:
appendInt(buf, int64(i))
case int16:
appendInt(buf, int64(i))
case int32:
appendInt(buf, int64(i))
case int64:
appendInt(buf, i)
case []int:
appendIntSlice(buf, i)
case uint:
appendUint(buf, uint64(i))
case uint16:
appendUint(buf, uint64(i))
case uint32:
appendUint(buf, uint64(i))
case uint64:
appendUint(buf, i)
case []uint:
appendUintSlice(buf, i)
case float32:
appendFloat(buf, float64(i))
case float64:
appendFloat(buf, i)
case []float64:
appendFloatSlice(buf, i)
case bool:
appendBool(buf, i)
case []bool:
appendBoolSlice(buf, i)
case time.Time:
if isKey {
// Keys don't get quoted
appendTimeUnquoted(buf, i)
} else {
appendTime(buf, i)
}
case *time.Time:
if isKey {
// Keys don't get quoted
appendTimeUnquoted(buf, *i)
} else {
appendTime(buf, *i)
}
case []time.Time:
appendTimeSlice(buf, i)
case time.Duration:
if isKey {
// Keys dont get quoted
appendDurationUnquoted(buf, i)
} else {
appendDuration(buf, i)
}
case []time.Duration:
appendDurationSlice(buf, i)
case map[string]interface{}:
appendIfaceMap(buf, i)
case error:
if isKey {
// Keys don't get quoted
appendStringUnquoted(buf, i.Error())
} else {
appendString(buf, i.Error())
}
case fmt.Stringer:
if isKey {
// Keys don't get quoted
appendStringUnquoted(buf, i.String())
} else {
appendString(buf, i.String())
}
default:
// If we reached here, we need reflection.
appendReflectValue(buf, reflect.ValueOf(i), isKey)
}
}
// appendIfaceMap writes a map of key-value pairs (as a set of fields) to buf
func appendIfaceMap(buf *bytes.Buffer, v map[string]interface{}) {
appendMap(buf, func() {
// Write map pairs!
for key, value := range v {
appendStringUnquoted(buf, key)
buf.WriteByte('=')
appendIface(buf, value, false)
buf.WriteByte(' ')
}
// Drop last space
if len(v) > 0 {
buf.Truncate(1)
}
})
}
// appendSliceType writes a slice of unknown type (parsed by reflection) to buf
func appendSliceType(buf *bytes.Buffer, v reflect.Value) {
n := v.Len()
appendSlice(buf, func() {
for i := 0; i < n; i++ {
appendIface(buf, v.Index(i).Interface(), false)
buf.WriteByte(',')
}
// Drop last comma
if n > 0 {
buf.Truncate(1)
}
})
}
// appendMapType writes a map of unknown types (parsed by reflection) to buf
func appendMapType(buf *bytes.Buffer, v reflect.Value) {
// Get a map iterator
r := v.MapRange()
n := v.Len()
// Now begin creating the map!
appendMap(buf, func() {
// Iterate pairs
for r.Next() {
appendIface(buf, r.Key().Interface(), true)
buf.WriteByte('=')
appendIface(buf, r.Value().Interface(), false)
buf.WriteByte(' ')
}
// Drop last space
if n > 0 {
buf.Truncate(1)
}
})
}
// appendStructType writes a struct (as a set of key-value fields) to buf
func appendStructType(buf *bytes.Buffer, v reflect.Value) {
// Get value type & no. fields
t := v.Type()
n := v.NumField()
w := 0
// Iter and write struct fields
appendStruct(buf, func() {
for i := 0; i < n; i++ {
vfield := v.Field(i)
// Check for unexported fields
if !vfield.CanInterface() {
continue
}
// Append the struct member as field key-value
appendStringUnquoted(buf, t.Field(i).Name)
buf.WriteByte('=')
appendIface(buf, vfield.Interface(), false)
buf.WriteByte(' ')
// Iter written count
w++
}
// Drop last space
if w > 0 {
buf.Truncate(1)
}
})
}
func (f *TextFormat) AppendLevel(buf *bytes.Buffer, lvl LEVEL) {
if f.Strict {
// Strict format, append level key
buf.WriteString(`level=`)
buf.WriteString(f.Levels.LevelString(lvl))
return
}
// Write level string
buf.WriteByte('[')
buf.WriteString(f.Levels.LevelString(lvl))
buf.WriteByte(']')
}
func (f *TextFormat) AppendTimestamp(buf *bytes.Buffer, now string) {
if f.Strict {
// Strict format, use key and quote
appendStringUnquoted(buf, `time`)
buf.WriteByte('=')
appendString(buf, now)
return
}
// Write time as-is
appendStringUnquoted(buf, now)
}
func (f *TextFormat) AppendField(buf *bytes.Buffer, key string, value interface{}) {
appendKey(buf, key)
appendIface(buf, value, false)
}
func (f *TextFormat) AppendFields(buf *bytes.Buffer, fields map[string]interface{}) {
// Append individual fields
for key, value := range fields {
appendKey(buf, key)
appendIface(buf, value, false)
buf.WriteByte(' ')
}
// Drop last space
if len(fields) > 0 {
buf.Truncate(1)
}
}
func (f *TextFormat) AppendByteField(buf *bytes.Buffer, key string, value byte) {
appendKey(buf, key)
appendByte(buf, value)
}
func (f *TextFormat) AppendBytesField(buf *bytes.Buffer, key string, value []byte) {
appendKey(buf, key)
appendBytes(buf, value)
}
func (f *TextFormat) AppendStringField(buf *bytes.Buffer, key string, value string) {
appendKey(buf, key)
appendString(buf, value)
}
func (f *TextFormat) AppendStringsField(buf *bytes.Buffer, key string, value []string) {
appendKey(buf, key)
appendStringSlice(buf, value)
}
func (f *TextFormat) AppendBoolField(buf *bytes.Buffer, key string, value bool) {
appendKey(buf, key)
appendBool(buf, value)
}
func (f *TextFormat) AppendBoolsField(buf *bytes.Buffer, key string, value []bool) {
appendKey(buf, key)
appendBoolSlice(buf, value)
}
func (f *TextFormat) AppendIntField(buf *bytes.Buffer, key string, value int) {
appendKey(buf, key)
appendInt(buf, int64(value))
}
func (f *TextFormat) AppendIntsField(buf *bytes.Buffer, key string, value []int) {
appendKey(buf, key)
appendIntSlice(buf, value)
}
func (f *TextFormat) AppendUintField(buf *bytes.Buffer, key string, value uint) {
appendKey(buf, key)
appendUint(buf, uint64(value))
}
func (f *TextFormat) AppendUintsField(buf *bytes.Buffer, key string, value []uint) {
appendKey(buf, key)
appendUintSlice(buf, value)
}
func (f *TextFormat) AppendFloatField(buf *bytes.Buffer, key string, value float64) {
appendKey(buf, key)
appendFloat(buf, value)
}
func (f *TextFormat) AppendFloatsField(buf *bytes.Buffer, key string, value []float64) {
appendKey(buf, key)
appendFloatSlice(buf, value)
}
func (f *TextFormat) AppendTimeField(buf *bytes.Buffer, key string, value time.Time) {
appendKey(buf, key)
appendTime(buf, value)
}
func (f *TextFormat) AppendTimesField(buf *bytes.Buffer, key string, value []time.Time) {
appendKey(buf, key)
appendTimeSlice(buf, value)
}
func (f *TextFormat) AppendDurationField(buf *bytes.Buffer, key string, value time.Duration) {
appendKey(buf, key)
appendDuration(buf, value)
}
func (f *TextFormat) AppendDurationsField(buf *bytes.Buffer, key string, value []time.Duration) {
appendKey(buf, key)
appendDurationSlice(buf, value)
}
func (f *TextFormat) AppendMsg(buf *bytes.Buffer, a ...interface{}) {
if f.Strict {
// Strict format, use key and quote
buf.WriteString(`msg="`)
fmt.Fprint(buf, a...)
buf.WriteByte('"')
return
}
// Write message as-is
fmt.Fprint(buf, a...)
}
func (f *TextFormat) AppendMsgf(buf *bytes.Buffer, s string, a ...interface{}) {
if f.Strict {
// Strict format, use key and quote
buf.WriteString(`msg="`)
fmt.Fprintf(buf, s, a...)
buf.WriteByte('"')
return
}
// Write message as-is
fmt.Fprintf(buf, s, a...)
}

13
vendor/codeberg.org/gruf/go-logger/hook.go generated vendored Normal file
View File

@@ -0,0 +1,13 @@
package logger
// Hook defines a log Entry modifier
type Hook interface {
Do(*Entry)
}
// HookFunc is a simple adapter to allow functions to satisfy the Hook interface
type HookFunc func(*Entry)
func (hook HookFunc) Do(entry *Entry) {
hook(entry)
}

39
vendor/codeberg.org/gruf/go-logger/level.go generated vendored Normal file
View File

@@ -0,0 +1,39 @@
package logger
// LEVEL defines a level of logging
type LEVEL uint8
// Available levels of logging.
const (
unset LEVEL = 255
DEBUG LEVEL = 5
INFO LEVEL = 10
WARN LEVEL = 15
ERROR LEVEL = 20
FATAL LEVEL = 25
)
var unknownLevel = "unknown"
// Levels defines a mapping of log LEVELs to formatted level strings
type Levels map[LEVEL]string
// DefaultLevels returns the default set of log levels
func DefaultLevels() Levels {
return Levels{
DEBUG: "debug",
INFO: "info",
WARN: "warn",
ERROR: "error",
FATAL: "fatal",
}
}
// LevelString fetches the appropriate level string for the provided level, or "unknown"
func (l Levels) LevelString(lvl LEVEL) string {
str, ok := l[lvl]
if !ok {
return unknownLevel
}
return str
}

153
vendor/codeberg.org/gruf/go-logger/logger.go generated vendored Normal file
View File

@@ -0,0 +1,153 @@
package logger
import (
"context"
"io"
"os"
"sync"
"sync/atomic"
"codeberg.org/gruf/go-bytes"
)
type Logger struct {
// Hooks defines a list of hooks which are called before an entry
// is written. This should NOT be modified while the Logger is in use
Hooks []Hook
// Level is the current log LEVEL, entries at level below the
// currently set level will not be output. This should NOT
// be modified while the Logger is in use
Level LEVEL
// Timestamp defines whether to automatically append timestamps
// to entries written via Logger convience methods and specifically
// Entry.TimestampIf(). This should NOT be modified while Logger in use
Timestamp bool
// Format is the log entry LogFormat to use. This should NOT
// be modified while the Logger is in use
Format LogFormat
// BufferSize is the Entry buffer size to use when allocating
// new Entry objects. This should be modified atomically
BufSize int64
// Output is the log's output writer. This should NOT be
// modified while the Logger is in use
Output io.Writer
// entry pool
pool sync.Pool
}
// New returns a new Logger instance with defaults
func New(out io.Writer) *Logger {
return NewWith(0 /* all */, true, NewLogFmt(false), 512, out)
}
// NewWith returns a new Logger instance with supplied configuration
func NewWith(lvl LEVEL, timestamp bool, fmt LogFormat, bufsize int64, out io.Writer) *Logger {
// Create new logger object
log := &Logger{
Level: lvl,
Timestamp: timestamp,
Format: fmt,
BufSize: bufsize,
Output: out,
pool: sync.Pool{},
}
// Ensure clock running
startClock()
// Set-up logger Entry pool
log.pool.New = func() interface{} {
return &Entry{
lvl: unset,
buf: &bytes.Buffer{B: make([]byte, 0, atomic.LoadInt64(&log.BufSize))},
log: log,
}
}
return log
}
// Entry returns a new Entry from the Logger's pool with background context
func (l *Logger) Entry() *Entry {
return l.pool.Get().(*Entry).WithContext(context.Background())
}
// Debug prints the provided arguments with the debug prefix
func (l *Logger) Debug(a ...interface{}) {
l.Entry().TimestampIf().Level(DEBUG).Hooks().Msg(a...)
}
// Debugf prints the provided format string and arguments with the debug prefix
func (l *Logger) Debugf(s string, a ...interface{}) {
l.Entry().TimestampIf().Level(DEBUG).Hooks().Msgf(s, a...)
}
// Info prints the provided arguments with the info prefix
func (l *Logger) Info(a ...interface{}) {
l.Entry().TimestampIf().Level(INFO).Hooks().Msg(a...)
}
// Infof prints the provided format string and arguments with the info prefix
func (l *Logger) Infof(s string, a ...interface{}) {
l.Entry().TimestampIf().Level(INFO).Hooks().Msgf(s, a...)
}
// Warn prints the provided arguments with the warn prefix
func (l *Logger) Warn(a ...interface{}) {
l.Entry().TimestampIf().Level(WARN).Hooks().Msg(a...)
}
// Warnf prints the provided format string and arguments with the warn prefix
func (l *Logger) Warnf(s string, a ...interface{}) {
l.Entry().TimestampIf().Level(WARN).Hooks().Msgf(s, a...)
}
// Error prints the provided arguments with the error prefix
func (l *Logger) Error(a ...interface{}) {
l.Entry().TimestampIf().Level(ERROR).Hooks().Msg(a...)
}
// Errorf prints the provided format string and arguments with the error prefix
func (l *Logger) Errorf(s string, a ...interface{}) {
l.Entry().TimestampIf().Level(ERROR).Hooks().Msgf(s, a...)
}
// Fatal prints provided arguments with the fatal prefix before exiting the program
// with os.Exit(1)
func (l *Logger) Fatal(a ...interface{}) {
defer os.Exit(1)
l.Entry().TimestampIf().Level(FATAL).Hooks().Msg(a...)
}
// Fatalf prints provided the provided format string and arguments with the fatal prefix
// before exiting the program with os.Exit(1)
func (l *Logger) Fatalf(s string, a ...interface{}) {
defer os.Exit(1)
l.Entry().TimestampIf().Level(FATAL).Hooks().Msgf(s, a...)
}
// Log prints the provided arguments with the supplied log level
func (l *Logger) Log(lvl LEVEL, a ...interface{}) {
l.Entry().TimestampIf().Hooks().Msg(a...)
}
// Logf prints the provided format string and arguments with the supplied log level
func (l *Logger) Logf(lvl LEVEL, s string, a ...interface{}) {
l.Entry().TimestampIf().Hooks().Msgf(s, a...)
}
// Print simply prints provided arguments
func (l *Logger) Print(a ...interface{}) {
l.Entry().Hooks().Msg(a...)
}
// Printf simply prints provided the provided format string and arguments
func (l *Logger) Printf(s string, a ...interface{}) {
l.Entry().Hooks().Msgf(s, a...)
}

661
vendor/codeberg.org/gruf/go-mutexes/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

1
vendor/codeberg.org/gruf/go-mutexes/README.md generated vendored Normal file
View File

@@ -0,0 +1 @@
Library that provides more complex mutex implementations than default libraries

105
vendor/codeberg.org/gruf/go-mutexes/map.go generated vendored Normal file
View File

@@ -0,0 +1,105 @@
package mutexes
import (
"sync"
)
// MutexMap is a structure that allows having a map of self-evicting mutexes
// by key. You do not need to worry about managing the contents of the map,
// only requesting RLock/Lock for keys, and ensuring to call the returned
// unlock functions.
type MutexMap struct {
// NOTE:
// Individual keyed mutexes should ONLY ever
// be locked within the protection of the outer
// mapMu lock. If you lock these outside the
// protection of this, there is a chance for
// deadlocks
mus map[string]RWMutex
mapMu sync.Mutex
pool sync.Pool
}
// NewMap returns a new MutexMap instance based on supplied
// RWMutex allocator function, nil implies use default
func NewMap(newFn func() RWMutex) MutexMap {
if newFn == nil {
newFn = NewRW
}
return MutexMap{
mus: make(map[string]RWMutex),
mapMu: sync.Mutex{},
pool: sync.Pool{
New: func() interface{} {
return newFn()
},
},
}
}
func (mm *MutexMap) evict(key string, mu RWMutex) {
// Acquire map lock
mm.mapMu.Lock()
// Toggle mutex lock to
// ensure it is unused
unlock := mu.Lock()
unlock()
// Delete mutex key
delete(mm.mus, key)
mm.mapMu.Unlock()
// Release to pool
mm.pool.Put(mu)
}
// RLock acquires a mutex read lock for supplied key, returning an RUnlock function
func (mm *MutexMap) RLock(key string) func() {
return mm.getLock(key, func(mu RWMutex) func() {
return mu.RLock()
})
}
// Lock acquires a mutex lock for supplied key, returning an Unlock function
func (mm *MutexMap) Lock(key string) func() {
return mm.getLock(key, func(mu RWMutex) func() {
return mu.Lock()
})
}
func (mm *MutexMap) getLock(key string, doLock func(RWMutex) func()) func() {
// Get map lock
mm.mapMu.Lock()
// Look for mutex
mu, ok := mm.mus[key]
if ok {
// Lock and return
// its unlocker func
unlock := doLock(mu)
mm.mapMu.Unlock()
return unlock
}
// Note: even though the mutex data structure is
// small, benchmarking does actually show that pooled
// alloc of mutexes here is faster
// Acquire mu + add
mu = mm.pool.Get().(RWMutex)
mm.mus[key] = mu
// Lock mutex + unlock map
unlockFn := doLock(mu)
mm.mapMu.Unlock()
return func() {
// Unlock mutex
unlockFn()
// Release function
go mm.evict(key, mu)
}
}

105
vendor/codeberg.org/gruf/go-mutexes/mutex.go generated vendored Normal file
View File

@@ -0,0 +1,105 @@
package mutexes
import (
"sync"
)
// Mutex defines a wrappable mutex. By forcing unlocks
// via returned function it makes wrapping much easier
type Mutex interface {
// Lock performs a mutex lock, returning an unlock function
Lock() (unlock func())
}
// RWMutex defines a wrappable read-write mutex. By forcing
// unlocks via returned functions it makes wrapping much easier
type RWMutex interface {
Mutex
// RLock performs a mutex read lock, returning an unlock function
RLock() (runlock func())
}
// New returns a new base Mutex implementation
func New() Mutex {
return &baseMutex{}
}
// NewRW returns a new base RWMutex implementation
func NewRW() RWMutex {
return &baseRWMutex{}
}
// WithFunc wraps the supplied Mutex to call the provided hooks on lock / unlock
func WithFunc(mu Mutex, onLock, onUnlock func()) Mutex {
return &fnMutex{mu: mu, lo: onLock, un: onUnlock}
}
// WithFuncRW wrapps the supplied RWMutex to call the provided hooks on lock / rlock / unlock/ runlock
func WithFuncRW(mu RWMutex, onLock, onRLock, onUnlock, onRUnlock func()) RWMutex {
return &fnRWMutex{mu: mu, lo: onLock, rlo: onRLock, un: onUnlock, run: onRUnlock}
}
// baseMutex simply wraps a sync.Mutex to implement our Mutex interface
type baseMutex struct{ mu sync.Mutex }
func (mu *baseMutex) Lock() func() {
mu.mu.Lock()
return mu.mu.Unlock
}
// baseRWMutex simply wraps a sync.RWMutex to implement our RWMutex interface
type baseRWMutex struct{ mu sync.RWMutex }
func (mu *baseRWMutex) Lock() func() {
mu.mu.Lock()
return mu.mu.Unlock
}
func (mu *baseRWMutex) RLock() func() {
mu.mu.RLock()
return mu.mu.RUnlock
}
// fnMutex wraps a Mutex to add hooks for Lock and Unlock
type fnMutex struct {
mu Mutex
lo func()
un func()
}
func (mu *fnMutex) Lock() func() {
unlock := mu.mu.Lock()
mu.lo()
return func() {
mu.un()
unlock()
}
}
// fnRWMutex wraps a RWMutex to add hooks for Lock, RLock, Unlock and RUnlock
type fnRWMutex struct {
mu RWMutex
lo func()
rlo func()
un func()
run func()
}
func (mu *fnRWMutex) Lock() func() {
unlock := mu.mu.Lock()
mu.lo()
return func() {
mu.un()
unlock()
}
}
func (mu *fnRWMutex) RLock() func() {
unlock := mu.mu.RLock()
mu.rlo()
return func() {
mu.run()
unlock()
}
}

39
vendor/codeberg.org/gruf/go-mutexes/mutex_safe.go generated vendored Normal file
View File

@@ -0,0 +1,39 @@
package mutexes
import "sync"
// WithSafety wrapps the supplied Mutex to protect unlock fns
// from being called multiple times
func WithSafety(mu Mutex) Mutex {
return &safeMutex{mu: mu}
}
// WithSafetyRW wrapps the supplied RWMutex to protect unlock
// fns from being called multiple times
func WithSafetyRW(mu RWMutex) RWMutex {
return &safeRWMutex{mu: mu}
}
// safeMutex simply wraps a Mutex to add multi-unlock safety
type safeMutex struct{ mu Mutex }
func (mu *safeMutex) Lock() func() {
unlock := mu.mu.Lock()
once := sync.Once{}
return func() { once.Do(unlock) }
}
// safeRWMutex simply wraps a RWMutex to add multi-unlock safety
type safeRWMutex struct{ mu RWMutex }
func (mu *safeRWMutex) Lock() func() {
unlock := mu.mu.Lock()
once := sync.Once{}
return func() { once.Do(unlock) }
}
func (mu *safeRWMutex) RLock() func() {
unlock := mu.mu.RLock()
once := sync.Once{}
return func() { once.Do(unlock) }
}

105
vendor/codeberg.org/gruf/go-mutexes/mutex_timeout.go generated vendored Normal file
View File

@@ -0,0 +1,105 @@
package mutexes
import (
"sync"
"time"
"codeberg.org/gruf/go-nowish"
)
// TimeoutMutex defines a Mutex with timeouts on locks
type TimeoutMutex interface {
Mutex
// LockFunc is functionally the same as Lock(), but allows setting a custom hook called on timeout
LockFunc(func()) func()
}
// TimeoutRWMutex defines a RWMutex with timeouts on locks
type TimeoutRWMutex interface {
RWMutex
// LockFunc is functionally the same as Lock(), but allows setting a custom hook called on timeout
LockFunc(func()) func()
// RLockFunc is functionally the same as RLock(), but allows setting a custom hook called on timeout
RLockFunc(func()) func()
}
// WithTimeout wraps the supplied Mutex to add a timeout
func WithTimeout(mu Mutex, d time.Duration) TimeoutMutex {
return &timeoutMutex{mu: mu, d: d}
}
// WithTimeoutRW wraps the supplied RWMutex to add read/write timeouts
func WithTimeoutRW(mu RWMutex, rd, wd time.Duration) TimeoutRWMutex {
return &timeoutRWMutex{mu: mu, rd: rd, wd: wd}
}
// timeoutMutex wraps a Mutex with timeout
type timeoutMutex struct {
mu Mutex // mu is the wrapped mutex
d time.Duration // d is the timeout duration
}
func (mu *timeoutMutex) Lock() func() {
return mu.LockFunc(func() { panic("lock timed out") })
}
func (mu *timeoutMutex) LockFunc(fn func()) func() {
return mutexTimeout(mu.d, mu.mu.Lock(), fn)
}
// TimeoutRWMutex wraps a RWMutex with timeouts
type timeoutRWMutex struct {
mu RWMutex // mu is the wrapped rwmutex
rd time.Duration // rd is the rlock timeout duration
wd time.Duration // wd is the lock timeout duration
}
func (mu *timeoutRWMutex) Lock() func() {
return mu.LockFunc(func() { panic("lock timed out") })
}
func (mu *timeoutRWMutex) LockFunc(fn func()) func() {
return mutexTimeout(mu.wd, mu.mu.Lock(), fn)
}
func (mu *timeoutRWMutex) RLock() func() {
return mu.RLockFunc(func() { panic("rlock timed out") })
}
func (mu *timeoutRWMutex) RLockFunc(fn func()) func() {
return mutexTimeout(mu.rd, mu.mu.RLock(), fn)
}
// timeoutPool provides nowish.Timeout objects for timeout mutexes
var timeoutPool = sync.Pool{
New: func() interface{} {
t := nowish.NewTimeout()
return &t
},
}
// mutexTimeout performs a timed unlock, calling supplied fn if timeout is reached
func mutexTimeout(d time.Duration, unlock func(), fn func()) func() {
if d < 1 {
// No timeout, just unlock
return unlock
}
// Acquire timeout obj
t := timeoutPool.Get().(*nowish.Timeout)
// Start the timeout with hook
t.Start(d, fn)
// Return func cancelling timeout,
// replacing Timeout in pool and
// finally unlocking mutex
return func() {
t.Cancel()
timeoutPool.Put(t)
unlock()
}
}

9
vendor/codeberg.org/gruf/go-nowish/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,9 @@
MIT License
Copyright (c) 2021 gruf
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

3
vendor/codeberg.org/gruf/go-nowish/README.md generated vendored Normal file
View File

@@ -0,0 +1,3 @@
a simple Go library with useful time utiities:
- Clock: a high performance clock giving a good "ish" representation of "now" (hence the name!)
- Timeout: a reusable structure for enforcing timeouts with a cancel

141
vendor/codeberg.org/gruf/go-nowish/time.go generated vendored Normal file
View File

@@ -0,0 +1,141 @@
package nowish
import (
"sync"
"sync/atomic"
"time"
"unsafe"
)
// Start returns a new Clock instance initialized and
// started with the provided precision, along with the
// stop function for it's underlying timer
func Start(precision time.Duration) (*Clock, func()) {
c := Clock{}
return &c, c.Start(precision)
}
type Clock struct {
noCopy noCopy //nolint noCopy because a copy will fuck with atomics
// format stores the time formatting style string
format string
// valid indicates whether the current value stored in .Format is valid
valid uint32
// mutex protects writes to .Format, not because it would be unsafe, but
// because we want to minimize unnnecessary allocations
mutex sync.Mutex
// nowfmt is an unsafe pointer to the last-updated time format string
nowfmt unsafe.Pointer
// now is an unsafe pointer to the last-updated time.Time object
now unsafe.Pointer
}
// Start starts the clock with the provided precision, the
// returned function is the stop function for the underlying timer
func (c *Clock) Start(precision time.Duration) func() {
// Create ticker from duration
tick := time.NewTicker(precision)
// Set initial time
t := time.Now()
atomic.StorePointer(&c.now, unsafe.Pointer(&t))
// Set initial format
s := ""
atomic.StorePointer(&c.nowfmt, unsafe.Pointer(&s))
// If formatting string unset, set default
c.mutex.Lock()
if c.format == "" {
c.format = time.RFC822
}
c.mutex.Unlock()
// Start main routine
go c.run(tick)
// Return stop fn
return tick.Stop
}
// run is the internal clock ticking loop
func (c *Clock) run(tick *time.Ticker) {
for {
// Wait on tick
_, ok := <-tick.C
// Channel closed
if !ok {
break
}
// Update time
t := time.Now()
atomic.StorePointer(&c.now, unsafe.Pointer(&t))
// Invalidate format string
atomic.StoreUint32(&c.valid, 0)
}
}
// Now returns a good (ish) estimate of the current 'now' time
func (c *Clock) Now() time.Time {
return *(*time.Time)(atomic.LoadPointer(&c.now))
}
// NowFormat returns the formatted "now" time, cached until next tick and "now" updates
func (c *Clock) NowFormat() string {
// If format still valid, return this
if atomic.LoadUint32(&c.valid) == 1 {
return *(*string)(atomic.LoadPointer(&c.nowfmt))
}
// Get mutex lock
c.mutex.Lock()
// Double check still invalid
if atomic.LoadUint32(&c.valid) == 1 {
c.mutex.Unlock()
return *(*string)(atomic.LoadPointer(&c.nowfmt))
}
// Calculate time format
b := c.Now().AppendFormat(
make([]byte, 0, len(c.format)),
c.format,
)
// Update the stored value and set valid!
atomic.StorePointer(&c.nowfmt, unsafe.Pointer(&b))
atomic.StoreUint32(&c.valid, 1)
// Unlock and return
c.mutex.Unlock()
// Note:
// it's safe to do this conversion here
// because this byte slice will never change.
// and we have the direct pointer to it, we're
// not requesting it atomicly via c.Format
return *(*string)(unsafe.Pointer(&b))
}
// SetFormat sets the time format string used by .NowFormat()
func (c *Clock) SetFormat(format string) {
// Get mutex lock
c.mutex.Lock()
// Update time format
c.format = format
// Invalidate current format string
atomic.StoreUint32(&c.valid, 0)
// Unlock
c.mutex.Unlock()
}

118
vendor/codeberg.org/gruf/go-nowish/timeout.go generated vendored Normal file
View File

@@ -0,0 +1,118 @@
package nowish
import (
"sync"
"sync/atomic"
"time"
)
// Timeout provides a reusable structure for enforcing timeouts with a cancel
type Timeout struct {
noCopy noCopy //nolint noCopy because a copy will mess with atomics
tk *time.Timer // tk is the underlying timeout-timer
ch syncer // ch is the cancel synchronization channel
wg sync.WaitGroup // wg is the waitgroup to hold .Start() until timeout goroutine started
st timeoutState // st stores the current timeout state (and protects concurrent use)
}
// NewTimeout returns a new Timeout instance
func NewTimeout() Timeout {
tk := time.NewTimer(time.Minute)
tk.Stop() // don't keep it running
return Timeout{
tk: tk,
ch: make(syncer),
}
}
func (t *Timeout) runTimeout(hook func()) {
t.wg.Add(1)
go func() {
cancelled := false
// Signal started
t.wg.Done()
select {
// Timeout reached
case <-t.tk.C:
if !t.st.stop() /* a sneaky cancel! */ {
t.ch.recv()
cancelled = true
defer t.ch.send()
}
// Cancel called
case <-t.ch:
cancelled = true
defer t.ch.send()
}
// Ensure timer stopped
if cancelled && !t.tk.Stop() {
<-t.tk.C
}
// Defer reset state
defer t.st.reset()
// If timed out call hook
if !cancelled {
hook()
}
}()
t.wg.Wait()
}
// Start starts the timer with supplied timeout. If timeout is reached before
// cancel then supplied timeout hook will be called. Error may be called if
// Timeout is already running when this function is called
func (t *Timeout) Start(d time.Duration, hook func()) {
if !t.st.start() {
panic("nowish: timeout already started")
}
t.runTimeout(hook)
t.tk.Reset(d)
}
// Cancel cancels the currently running timer. If a cancel is achieved, then
// this function will return after the timeout goroutine is finished
func (t *Timeout) Cancel() {
if !t.st.stop() {
return
}
t.ch.send()
t.ch.recv()
}
// timeoutState provides a thread-safe timeout state mechanism
type timeoutState uint32
// start attempts to start the state, must be already reset, returns success
func (t *timeoutState) start() bool {
return atomic.CompareAndSwapUint32((*uint32)(t), 0, 1)
}
// stop attempts to stop the state, must already be started, returns success
func (t *timeoutState) stop() bool {
return atomic.CompareAndSwapUint32((*uint32)(t), 1, 2)
}
// reset is fairly self explanatory
func (t *timeoutState) reset() {
atomic.StoreUint32((*uint32)(t), 0)
}
// syncer provides helpful receiver methods for a synchronization channel
type syncer (chan struct{})
// send blocks on sending an empty value down channel
func (s syncer) send() {
s <- struct{}{}
}
// recv blocks on receiving (and dropping) empty value from channel
func (s syncer) recv() {
<-s
}

10
vendor/codeberg.org/gruf/go-nowish/util.go generated vendored Normal file
View File

@@ -0,0 +1,10 @@
package nowish
//nolint
type noCopy struct{}
//nolint
func (*noCopy) Lock() {}
//nolint
func (*noCopy) Unlock() {}

9
vendor/codeberg.org/gruf/go-pools/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,9 @@
MIT License
Copyright (c) 2021 gruf
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

2
vendor/codeberg.org/gruf/go-pools/README.md generated vendored Normal file
View File

@@ -0,0 +1,2 @@
A selection of type-defined `sync.Pool` implementations with redefined "getter" and "putter"
methods to handle their appropriate types.

75
vendor/codeberg.org/gruf/go-pools/bufio.go generated vendored Normal file
View File

@@ -0,0 +1,75 @@
package pools
import (
"bufio"
"io"
"sync"
)
// BufioReaderPool is a pooled allocator for bufio.Reader objects
type BufioReaderPool interface {
// Get fetches a bufio.Reader from pool and resets to supplied reader
Get(io.Reader) *bufio.Reader
// Put places supplied bufio.Reader back in pool
Put(*bufio.Reader)
}
// NewBufioReaderPool returns a newly instantiated bufio.Reader pool
func NewBufioReaderPool(size int) BufioReaderPool {
return &bufioReaderPool{
Pool: sync.Pool{
New: func() interface{} {
return bufio.NewReaderSize(nil, size)
},
},
}
}
// bufioReaderPool is our implementation of BufioReaderPool
type bufioReaderPool struct{ sync.Pool }
func (p *bufioReaderPool) Get(r io.Reader) *bufio.Reader {
br := p.Pool.Get().(*bufio.Reader)
br.Reset(r)
return br
}
func (p *bufioReaderPool) Put(br *bufio.Reader) {
br.Reset(nil)
p.Pool.Put(br)
}
// BufioWriterPool is a pooled allocator for bufio.Writer objects
type BufioWriterPool interface {
// Get fetches a bufio.Writer from pool and resets to supplied writer
Get(io.Writer) *bufio.Writer
// Put places supplied bufio.Writer back in pool
Put(*bufio.Writer)
}
// NewBufioWriterPool returns a newly instantiated bufio.Writer pool
func NewBufioWriterPool(size int) BufioWriterPool {
return &bufioWriterPool{
Pool: sync.Pool{
New: func() interface{} {
return bufio.NewWriterSize(nil, size)
},
},
}
}
// bufioWriterPool is our implementation of BufioWriterPool
type bufioWriterPool struct{ sync.Pool }
func (p *bufioWriterPool) Get(w io.Writer) *bufio.Writer {
bw := p.Pool.Get().(*bufio.Writer)
bw.Reset(w)
return bw
}
func (p *bufioWriterPool) Put(bw *bufio.Writer) {
bw.Reset(nil)
p.Pool.Put(bw)
}

46
vendor/codeberg.org/gruf/go-pools/bytes.go generated vendored Normal file
View File

@@ -0,0 +1,46 @@
package pools
import (
"sync"
"codeberg.org/gruf/go-bytes"
)
// BufferPool is a pooled allocator for bytes.Buffer objects
type BufferPool interface {
// Get fetches a bytes.Buffer from pool
Get() *bytes.Buffer
// Put places supplied bytes.Buffer in pool
Put(*bytes.Buffer)
}
// NewBufferPool returns a newly instantiated bytes.Buffer pool
func NewBufferPool(size int) BufferPool {
return &bufferPool{
pool: sync.Pool{
New: func() interface{} {
return &bytes.Buffer{B: make([]byte, 0, size)}
},
},
size: size,
}
}
// bufferPool is our implementation of BufferPool
type bufferPool struct {
pool sync.Pool
size int
}
func (p *bufferPool) Get() *bytes.Buffer {
return p.pool.Get().(*bytes.Buffer)
}
func (p *bufferPool) Put(buf *bytes.Buffer) {
if buf.Cap() < p.size {
return
}
buf.Reset()
p.pool.Put(buf)
}

46
vendor/codeberg.org/gruf/go-pools/fastpath.go generated vendored Normal file
View File

@@ -0,0 +1,46 @@
package pools
import (
"sync"
"codeberg.org/gruf/go-fastpath"
)
// PathBuilderPool is a pooled allocator for fastpath.Builder objects
type PathBuilderPool interface {
// Get fetches a fastpath.Builder from pool
Get() *fastpath.Builder
// Put places supplied fastpath.Builder back in pool
Put(*fastpath.Builder)
}
// NewPathBuilderPool returns a newly instantiated fastpath.Builder pool
func NewPathBuilderPool(size int) PathBuilderPool {
return &pathBuilderPool{
pool: sync.Pool{
New: func() interface{} {
return &fastpath.Builder{B: make([]byte, 0, size)}
},
},
size: size,
}
}
// pathBuilderPool is our implementation of PathBuilderPool
type pathBuilderPool struct {
pool sync.Pool
size int
}
func (p *pathBuilderPool) Get() *fastpath.Builder {
return p.pool.Get().(*fastpath.Builder)
}
func (p *pathBuilderPool) Put(pb *fastpath.Builder) {
if pb.Cap() < p.size {
return
}
pb.Reset()
p.pool.Put(pb)
}

9
vendor/codeberg.org/gruf/go-store/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,9 @@
MIT License
Copyright (c) 2021 gruf
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

64
vendor/codeberg.org/gruf/go-store/kv/iterator.go generated vendored Normal file
View File

@@ -0,0 +1,64 @@
package kv
import (
"codeberg.org/gruf/go-errors"
"codeberg.org/gruf/go-store/storage"
)
var ErrIteratorClosed = errors.New("store/kv: iterator closed")
// KVIterator provides a read-only iterator to all the key-value
// pairs in a KVStore. While the iterator is open the store is read
// locked, you MUST release the iterator when you are finished with
// it.
//
// Please note:
// - individual iterators are NOT concurrency safe, though it is safe to
// have multiple iterators running concurrently
type KVIterator struct {
store *KVStore // store is the linked KVStore
entries []storage.StorageEntry
index int
key string
onClose func()
}
// Next attempts to set the next key-value pair, the
// return value is if there was another pair remaining
func (i *KVIterator) Next() bool {
next := i.index + 1
if next >= len(i.entries) {
i.key = ""
return false
}
i.key = i.entries[next].Key()
i.index = next
return true
}
// Key returns the next key from the store
func (i *KVIterator) Key() string {
return i.key
}
// Release releases the KVIterator and KVStore's read lock
func (i *KVIterator) Release() {
// Reset key, path, entries
i.store = nil
i.key = ""
i.entries = nil
// Perform requested callback
i.onClose()
}
// Value returns the next value from the KVStore
func (i *KVIterator) Value() ([]byte, error) {
// Check store isn't closed
if i.store == nil {
return nil, ErrIteratorClosed
}
// Attempt to fetch from store
return i.store.get(i.key)
}

125
vendor/codeberg.org/gruf/go-store/kv/state.go generated vendored Normal file
View File

@@ -0,0 +1,125 @@
package kv
import (
"io"
"codeberg.org/gruf/go-errors"
)
var ErrStateClosed = errors.New("store/kv: state closed")
// StateRO provides a read-only window to the store. While this
// state is active during the Read() function window, the entire
// store will be read-locked. The state is thread-safe for concurrent
// use UNTIL the moment that your supplied function to Read() returns,
// then the state has zero guarantees
type StateRO struct {
store *KVStore
}
func (st *StateRO) Get(key string) ([]byte, error) {
// Check not closed
if st.store == nil {
return nil, ErrStateClosed
}
// Pass request to store
return st.store.get(key)
}
func (st *StateRO) GetStream(key string) (io.ReadCloser, error) {
// Check not closed
if st.store == nil {
return nil, ErrStateClosed
}
// Pass request to store
return st.store.getStream(key)
}
func (st *StateRO) Has(key string) (bool, error) {
// Check not closed
if st.store == nil {
return false, ErrStateClosed
}
// Pass request to store
return st.store.has(key)
}
func (st *StateRO) close() {
st.store = nil
}
// StateRW provides a read-write window to the store. While this
// state is active during the Update() function window, the entire
// store will be locked. The state is thread-safe for concurrent
// use UNTIL the moment that your supplied function to Update() returns,
// then the state has zero guarantees
type StateRW struct {
store *KVStore
}
func (st *StateRW) Get(key string) ([]byte, error) {
// Check not closed
if st.store == nil {
return nil, ErrStateClosed
}
// Pass request to store
return st.store.get(key)
}
func (st *StateRW) GetStream(key string) (io.ReadCloser, error) {
// Check not closed
if st.store == nil {
return nil, ErrStateClosed
}
// Pass request to store
return st.store.getStream(key)
}
func (st *StateRW) Put(key string, value []byte) error {
// Check not closed
if st.store == nil {
return ErrStateClosed
}
// Pass request to store
return st.store.put(key, value)
}
func (st *StateRW) PutStream(key string, r io.Reader) error {
// Check not closed
if st.store == nil {
return ErrStateClosed
}
// Pass request to store
return st.store.putStream(key, r)
}
func (st *StateRW) Has(key string) (bool, error) {
// Check not closed
if st.store == nil {
return false, ErrStateClosed
}
// Pass request to store
return st.store.has(key)
}
func (st *StateRW) Delete(key string) error {
// Check not closed
if st.store == nil {
return ErrStateClosed
}
// Pass request to store
return st.store.delete(key)
}
func (st *StateRW) close() {
st.store = nil
}

243
vendor/codeberg.org/gruf/go-store/kv/store.go generated vendored Normal file
View File

@@ -0,0 +1,243 @@
package kv
import (
"io"
"sync"
"codeberg.org/gruf/go-mutexes"
"codeberg.org/gruf/go-store/storage"
"codeberg.org/gruf/go-store/util"
)
// KVStore is a very simple, yet performant key-value store
type KVStore struct {
mutexMap mutexes.MutexMap // mutexMap is a map of keys to mutexes to protect file access
mutex sync.RWMutex // mutex is the total store mutex
storage storage.Storage // storage is the underlying storage
}
func OpenFile(path string, cfg *storage.DiskConfig) (*KVStore, error) {
// Attempt to open disk storage
storage, err := storage.OpenFile(path, cfg)
if err != nil {
return nil, err
}
// Return new KVStore
return OpenStorage(storage)
}
func OpenBlock(path string, cfg *storage.BlockConfig) (*KVStore, error) {
// Attempt to open block storage
storage, err := storage.OpenBlock(path, cfg)
if err != nil {
return nil, err
}
// Return new KVStore
return OpenStorage(storage)
}
func OpenStorage(storage storage.Storage) (*KVStore, error) {
// Perform initial storage clean
err := storage.Clean()
if err != nil {
return nil, err
}
// Return new KVStore
return &KVStore{
mutexMap: mutexes.NewMap(mutexes.NewRW),
mutex: sync.RWMutex{},
storage: storage,
}, nil
}
// Get fetches the bytes for supplied key in the store
func (st *KVStore) Get(key string) ([]byte, error) {
// Acquire store read lock
st.mutex.RLock()
defer st.mutex.RUnlock()
// Pass to unprotected fn
return st.get(key)
}
func (st *KVStore) get(key string) ([]byte, error) {
// Acquire read lock for key
runlock := st.mutexMap.RLock(key)
defer runlock()
// Read file bytes
return st.storage.ReadBytes(key)
}
// GetStream fetches a ReadCloser for the bytes at the supplied key location in the store
func (st *KVStore) GetStream(key string) (io.ReadCloser, error) {
// Acquire store read lock
st.mutex.RLock()
defer st.mutex.RUnlock()
// Pass to unprotected fn
return st.getStream(key)
}
func (st *KVStore) getStream(key string) (io.ReadCloser, error) {
// Acquire read lock for key
runlock := st.mutexMap.RLock(key)
// Attempt to open stream for read
rd, err := st.storage.ReadStream(key)
if err != nil {
runlock()
return nil, err
}
// Wrap readcloser in our own callback closer
return util.ReadCloserWithCallback(rd, runlock), nil
}
// Put places the bytes at the supplied key location in the store
func (st *KVStore) Put(key string, value []byte) error {
// Acquire store write lock
st.mutex.Lock()
defer st.mutex.Unlock()
// Pass to unprotected fn
return st.put(key, value)
}
func (st *KVStore) put(key string, value []byte) error {
// Acquire write lock for key
unlock := st.mutexMap.Lock(key)
defer unlock()
// Write file bytes
return st.storage.WriteBytes(key, value)
}
// PutStream writes the bytes from the supplied Reader at the supplied key location in the store
func (st *KVStore) PutStream(key string, r io.Reader) error {
// Acquire store write lock
st.mutex.Lock()
defer st.mutex.Unlock()
// Pass to unprotected fn
return st.putStream(key, r)
}
func (st *KVStore) putStream(key string, r io.Reader) error {
// Acquire write lock for key
unlock := st.mutexMap.Lock(key)
defer unlock()
// Write file stream
return st.storage.WriteStream(key, r)
}
// Has checks whether the supplied key exists in the store
func (st *KVStore) Has(key string) (bool, error) {
// Acquire store read lock
st.mutex.RLock()
defer st.mutex.RUnlock()
// Pass to unprotected fn
return st.has(key)
}
func (st *KVStore) has(key string) (bool, error) {
// Acquire read lock for key
runlock := st.mutexMap.RLock(key)
defer runlock()
// Stat file on disk
return st.storage.Stat(key)
}
// Delete removes the supplied key-value pair from the store
func (st *KVStore) Delete(key string) error {
// Acquire store write lock
st.mutex.Lock()
defer st.mutex.Unlock()
// Pass to unprotected fn
return st.delete(key)
}
func (st *KVStore) delete(key string) error {
// Acquire write lock for key
unlock := st.mutexMap.Lock(key)
defer unlock()
// Remove file from disk
return st.storage.Remove(key)
}
// Iterator returns an Iterator for key-value pairs in the store, using supplied match function
func (st *KVStore) Iterator(matchFn func(string) bool) (*KVIterator, error) {
// If no function, match all
if matchFn == nil {
matchFn = func(string) bool { return true }
}
// Get store read lock
st.mutex.RLock()
// Setup the walk keys function
entries := []storage.StorageEntry{}
walkFn := func(entry storage.StorageEntry) {
// Ignore unmatched entries
if !matchFn(entry.Key()) {
return
}
// Add to entries
entries = append(entries, entry)
}
// Walk keys in the storage
err := st.storage.WalkKeys(&storage.WalkKeysOptions{WalkFn: walkFn})
if err != nil {
st.mutex.RUnlock()
return nil, err
}
// Return new iterator
return &KVIterator{
store: st,
entries: entries,
index: -1,
key: "",
onClose: st.mutex.RUnlock,
}, nil
}
// Read provides a read-only window to the store, holding it in a read-locked state until
// the supplied function returns
func (st *KVStore) Read(do func(*StateRO)) {
// Get store read lock
st.mutex.RLock()
defer st.mutex.RUnlock()
// Create new store state (defer close)
state := &StateRO{store: st}
defer state.close()
// Pass state
do(state)
}
// Update provides a read-write window to the store, holding it in a read-write-locked state
// until the supplied functions returns
func (st *KVStore) Update(do func(*StateRW)) {
// Get store lock
st.mutex.Lock()
defer st.mutex.Unlock()
// Create new store state (defer close)
state := &StateRW{store: st}
defer state.close()
// Pass state
do(state)
}

797
vendor/codeberg.org/gruf/go-store/storage/block.go generated vendored Normal file
View File

@@ -0,0 +1,797 @@
package storage
import (
"crypto/sha256"
"io"
"io/fs"
"os"
"strings"
"sync"
"syscall"
"codeberg.org/gruf/go-bytes"
"codeberg.org/gruf/go-errors"
"codeberg.org/gruf/go-hashenc"
"codeberg.org/gruf/go-pools"
"codeberg.org/gruf/go-store/util"
)
var (
nodePathPrefix = "node/"
blockPathPrefix = "block/"
)
// DefaultBlockConfig is the default BlockStorage configuration
var DefaultBlockConfig = &BlockConfig{
BlockSize: 1024 * 16,
WriteBufSize: 4096,
Overwrite: false,
Compression: NoCompression(),
}
// BlockConfig defines options to be used when opening a BlockStorage
type BlockConfig struct {
// BlockSize is the chunking size to use when splitting and storing blocks of data
BlockSize int
// WriteBufSize is the buffer size to use when writing file streams (PutStream)
WriteBufSize int
// Overwrite allows overwriting values of stored keys in the storage
Overwrite bool
// Compression is the Compressor to use when reading / writing files, default is no compression
Compression Compressor
}
// getBlockConfig returns a valid BlockConfig for supplied ptr
func getBlockConfig(cfg *BlockConfig) BlockConfig {
// If nil, use default
if cfg == nil {
cfg = DefaultBlockConfig
}
// Assume nil compress == none
if cfg.Compression == nil {
cfg.Compression = NoCompression()
}
// Assume 0 chunk size == use default
if cfg.BlockSize < 1 {
cfg.BlockSize = DefaultBlockConfig.BlockSize
}
// Assume 0 buf size == use default
if cfg.WriteBufSize < 1 {
cfg.WriteBufSize = DefaultDiskConfig.WriteBufSize
}
// Return owned config copy
return BlockConfig{
BlockSize: cfg.BlockSize,
WriteBufSize: cfg.WriteBufSize,
Overwrite: cfg.Overwrite,
Compression: cfg.Compression,
}
}
// BlockStorage is a Storage implementation that stores input data as chunks on
// a filesystem. Each value is chunked into blocks of configured size and these
// blocks are stored with name equal to their base64-encoded SHA256 hash-sum. A
// "node" file is finally created containing an array of hashes contained within
// this value
type BlockStorage struct {
path string // path is the root path of this store
blockPath string // blockPath is the joined root path + block path prefix
nodePath string // nodePath is the joined root path + node path prefix
config BlockConfig // cfg is the supplied configuration for this store
hashPool sync.Pool // hashPool is this store's hashEncoder pool
bufpool pools.BufferPool // bufpool is this store's bytes.Buffer pool
// NOTE:
// BlockStorage does not need to lock each of the underlying block files
// as the filename itself directly relates to the contents. If there happens
// to be an overwrite, it will just be of the same data since the filename is
// the hash of the data.
}
// OpenBlock opens a BlockStorage instance for given folder path and configuration
func OpenBlock(path string, cfg *BlockConfig) (*BlockStorage, error) {
// Acquire path builder
pb := util.GetPathBuilder()
defer util.PutPathBuilder(pb)
// Clean provided path, ensure ends in '/' (should
// be dir, this helps with file path trimming later)
path = pb.Clean(path) + "/"
// Get checked config
config := getBlockConfig(cfg)
// Attempt to open path
file, err := os.OpenFile(path, defaultFileROFlags, defaultDirPerms)
if err != nil {
// If not a not-exist error, return
if !os.IsNotExist(err) {
return nil, err
}
// Attempt to make store path dirs
err = os.MkdirAll(path, defaultDirPerms)
if err != nil {
return nil, err
}
// Reopen dir now it's been created
file, err = os.OpenFile(path, defaultFileROFlags, defaultDirPerms)
if err != nil {
return nil, err
}
}
defer file.Close()
// Double check this is a dir (NOT a file!)
stat, err := file.Stat()
if err != nil {
return nil, err
} else if !stat.IsDir() {
return nil, errPathIsFile
}
// Figure out the largest size for bufpool slices
bufSz := encodedHashLen
if bufSz < config.BlockSize {
bufSz = config.BlockSize
}
if bufSz < config.WriteBufSize {
bufSz = config.WriteBufSize
}
// Return new BlockStorage
return &BlockStorage{
path: path,
blockPath: pb.Join(path, blockPathPrefix),
nodePath: pb.Join(path, nodePathPrefix),
config: config,
hashPool: sync.Pool{
New: func() interface{} {
return newHashEncoder()
},
},
bufpool: pools.NewBufferPool(bufSz),
}, nil
}
// Clean implements storage.Clean()
func (st *BlockStorage) Clean() error {
nodes := map[string]*node{}
// Acquire path builder
pb := util.GetPathBuilder()
defer util.PutPathBuilder(pb)
// Walk nodes dir for entries
onceErr := errors.OnceError{}
err := util.WalkDir(pb, st.nodePath, func(npath string, fsentry fs.DirEntry) {
// Only deal with regular files
if !fsentry.Type().IsRegular() {
return
}
// Stop if we hit error previously
if onceErr.IsSet() {
return
}
// Get joined node path name
npath = pb.Join(npath, fsentry.Name())
// Attempt to open RO file
file, err := open(npath, defaultFileROFlags)
if err != nil {
onceErr.Store(err)
return
}
defer file.Close()
// Alloc new Node + acquire hash buffer for writes
hbuf := st.bufpool.Get()
defer st.bufpool.Put(hbuf)
hbuf.Guarantee(encodedHashLen)
node := node{}
// Write file contents to node
_, err = io.CopyBuffer(
&nodeWriter{
node: &node,
buf: hbuf,
},
file,
nil,
)
if err != nil {
onceErr.Store(err)
return
}
// Append to nodes slice
nodes[fsentry.Name()] = &node
})
// Handle errors (though nodePath may not have been created yet)
if err != nil && !os.IsNotExist(err) {
return err
} else if onceErr.IsSet() {
return onceErr.Load()
}
// Walk blocks dir for entries
onceErr.Reset()
err = util.WalkDir(pb, st.blockPath, func(bpath string, fsentry fs.DirEntry) {
// Only deal with regular files
if !fsentry.Type().IsRegular() {
return
}
// Stop if we hit error previously
if onceErr.IsSet() {
return
}
inUse := false
for key, node := range nodes {
if node.removeHash(fsentry.Name()) {
if len(node.hashes) < 1 {
// This node contained hash, and after removal is now empty.
// Remove this node from our tracked nodes slice
delete(nodes, key)
}
inUse = true
}
}
// Block hash is used by node
if inUse {
return
}
// Get joined block path name
bpath = pb.Join(bpath, fsentry.Name())
// Remove this unused block path
err := os.Remove(bpath)
if err != nil {
onceErr.Store(err)
return
}
})
// Handle errors (though blockPath may not have been created yet)
if err != nil && !os.IsNotExist(err) {
return err
} else if onceErr.IsSet() {
return onceErr.Load()
}
// If there are nodes left at this point, they are corrupt
// (i.e. they're referencing block hashes that don't exist)
if len(nodes) > 0 {
nodeKeys := []string{}
for key := range nodes {
nodeKeys = append(nodeKeys, key)
}
return errCorruptNodes.Extend("%v", nodeKeys)
}
return nil
}
// ReadBytes implements Storage.ReadBytes()
func (st *BlockStorage) ReadBytes(key string) ([]byte, error) {
// Get stream reader for key
rc, err := st.ReadStream(key)
if err != nil {
return nil, err
}
// Read all bytes and return
return io.ReadAll(rc)
}
// ReadStream implements Storage.ReadStream()
func (st *BlockStorage) ReadStream(key string) (io.ReadCloser, error) {
// Get node file path for key
npath, err := st.nodePathForKey(key)
if err != nil {
return nil, err
}
// Attempt to open RO file
file, err := open(npath, defaultFileROFlags)
if err != nil {
return nil, err
}
defer file.Close()
// Acquire hash buffer for writes
hbuf := st.bufpool.Get()
defer st.bufpool.Put(hbuf)
// Write file contents to node
node := node{}
_, err = io.CopyBuffer(
&nodeWriter{
node: &node,
buf: hbuf,
},
file,
nil,
)
if err != nil {
return nil, err
}
// Return new block reader
return util.NopReadCloser(&blockReader{
storage: st,
node: &node,
}), nil
}
func (st *BlockStorage) readBlock(key string) ([]byte, error) {
// Get block file path for key
bpath := st.blockPathForKey(key)
// Attempt to open RO file
file, err := open(bpath, defaultFileROFlags)
if err != nil {
return nil, err
}
defer file.Close()
// Wrap the file in a compressor
cFile, err := st.config.Compression.Reader(file)
if err != nil {
return nil, err
}
defer cFile.Close()
// Read the entire file
return io.ReadAll(cFile)
}
// WriteBytes implements Storage.WriteBytes()
func (st *BlockStorage) WriteBytes(key string, value []byte) error {
return st.WriteStream(key, bytes.NewReader(value))
}
// WriteStream implements Storage.WriteStream()
func (st *BlockStorage) WriteStream(key string, r io.Reader) error {
// Get node file path for key
npath, err := st.nodePathForKey(key)
if err != nil {
return err
}
// Check if this exists
ok, err := stat(key)
if err != nil {
return err
}
// Check if we allow overwrites
if ok && !st.config.Overwrite {
return ErrAlreadyExists
}
// Ensure nodes dir (and any leading up to) exists
err = os.MkdirAll(st.nodePath, defaultDirPerms)
if err != nil {
return err
}
// Ensure blocks dir (and any leading up to) exists
err = os.MkdirAll(st.blockPath, defaultDirPerms)
if err != nil {
return err
}
// Alloc new node
node := node{}
// Acquire HashEncoder
hc := st.hashPool.Get().(*hashEncoder)
defer st.hashPool.Put(hc)
// Create new waitgroup and OnceError for
// goroutine error tracking and propagating
wg := sync.WaitGroup{}
onceErr := errors.OnceError{}
loop:
for !onceErr.IsSet() {
// Fetch new buffer for this loop
buf := st.bufpool.Get()
buf.Grow(st.config.BlockSize)
// Read next chunk
n, err := io.ReadFull(r, buf.B)
switch err {
case nil, io.ErrUnexpectedEOF:
// do nothing
case io.EOF:
st.bufpool.Put(buf)
break loop
default:
st.bufpool.Put(buf)
return err
}
// Hash the encoded data
sum := hc.EncodeSum(buf.B)
// Append to the node's hashes
node.hashes = append(node.hashes, sum.String())
// If already on disk, skip
has, err := st.statBlock(sum.StringPtr())
if err != nil {
st.bufpool.Put(buf)
return err
} else if has {
st.bufpool.Put(buf)
continue loop
}
// Write in separate goroutine
wg.Add(1)
go func() {
// Defer buffer release + signal done
defer func() {
st.bufpool.Put(buf)
wg.Done()
}()
// Write block to store at hash
err = st.writeBlock(sum.StringPtr(), buf.B[:n])
if err != nil {
onceErr.Store(err)
return
}
}()
// We reached EOF
if n < buf.Len() {
break loop
}
}
// Wait, check errors
wg.Wait()
if onceErr.IsSet() {
return onceErr.Load()
}
// If no hashes created, return
if len(node.hashes) < 1 {
return errNoHashesWritten
}
// Prepare to swap error if need-be
errSwap := errSwapNoop
// Build file RW flags
// NOTE: we performed an initial check for
// this before writing blocks, but if
// the utilizer of this storage didn't
// correctly mutex protect this key then
// someone may have beaten us to the
// punch at writing the node file.
flags := defaultFileRWFlags
if !st.config.Overwrite {
flags |= syscall.O_EXCL
// Catch + replace err exist
errSwap = errSwapExist
}
// Attempt to open RW file
file, err := open(npath, flags)
if err != nil {
return errSwap(err)
}
defer file.Close()
// Acquire write buffer
buf := st.bufpool.Get()
defer st.bufpool.Put(buf)
buf.Grow(st.config.WriteBufSize)
// Finally, write data to file
_, err = io.CopyBuffer(file, &nodeReader{node: &node}, nil)
return err
}
// writeBlock writes the block with hash and supplied value to the filesystem
func (st *BlockStorage) writeBlock(hash string, value []byte) error {
// Get block file path for key
bpath := st.blockPathForKey(hash)
// Attempt to open RW file
file, err := open(bpath, defaultFileRWFlags)
if err != nil {
if err == ErrAlreadyExists {
err = nil /* race issue describe in struct NOTE */
}
return err
}
defer file.Close()
// Wrap the file in a compressor
cFile, err := st.config.Compression.Writer(file)
if err != nil {
return err
}
defer cFile.Close()
// Write value to file
_, err = cFile.Write(value)
return err
}
// statBlock checks for existence of supplied block hash
func (st *BlockStorage) statBlock(hash string) (bool, error) {
return stat(st.blockPathForKey(hash))
}
// Stat implements Storage.Stat()
func (st *BlockStorage) Stat(key string) (bool, error) {
// Get node file path for key
kpath, err := st.nodePathForKey(key)
if err != nil {
return false, err
}
// Check for file on disk
return stat(kpath)
}
// Remove implements Storage.Remove()
func (st *BlockStorage) Remove(key string) error {
// Get node file path for key
kpath, err := st.nodePathForKey(key)
if err != nil {
return err
}
// Attempt to remove file
return os.Remove(kpath)
}
// WalkKeys implements Storage.WalkKeys()
func (st *BlockStorage) WalkKeys(opts *WalkKeysOptions) error {
// Acquire path builder
pb := util.GetPathBuilder()
defer util.PutPathBuilder(pb)
// Walk dir for entries
return util.WalkDir(pb, st.nodePath, func(npath string, fsentry fs.DirEntry) {
// Only deal with regular files
if fsentry.Type().IsRegular() {
opts.WalkFn(entry(fsentry.Name()))
}
})
}
// nodePathForKey calculates the node file path for supplied key
func (st *BlockStorage) nodePathForKey(key string) (string, error) {
// Path separators are illegal
if strings.Contains(key, "/") {
return "", ErrInvalidKey
}
// Acquire path builder
pb := util.GetPathBuilder()
defer util.PutPathBuilder(pb)
// Return joined + cleaned node-path
return pb.Join(st.nodePath, key), nil
}
// blockPathForKey calculates the block file path for supplied hash
func (st *BlockStorage) blockPathForKey(hash string) string {
pb := util.GetPathBuilder()
defer util.PutPathBuilder(pb)
return pb.Join(st.blockPath, hash)
}
// hashSeparator is the separating byte between block hashes
const hashSeparator = byte(':')
// node represents the contents of a node file in storage
type node struct {
hashes []string
}
// removeHash attempts to remove supplied block hash from the node's hash array
func (n *node) removeHash(hash string) bool {
haveDropped := false
for i := 0; i < len(n.hashes); {
if n.hashes[i] == hash {
// Drop this hash from slice
n.hashes = append(n.hashes[:i], n.hashes[i+1:]...)
haveDropped = true
} else {
// Continue iter
i++
}
}
return haveDropped
}
// nodeReader is an io.Reader implementation for the node file representation,
// which is useful when calculated node file is being written to the store
type nodeReader struct {
node *node
idx int
last int
}
func (r *nodeReader) Read(b []byte) (int, error) {
n := 0
// '-1' means we missed writing
// hash separator on last iteration
if r.last == -1 {
b[n] = hashSeparator
n++
r.last = 0
}
for r.idx < len(r.node.hashes) {
hash := r.node.hashes[r.idx]
// Copy into buffer + update read count
m := copy(b[n:], hash[r.last:])
n += m
// If incomplete copy, return here
if m < len(hash)-r.last {
r.last = m
return n, nil
}
// Check we can write last separator
if n == len(b) {
r.last = -1
return n, nil
}
// Write separator, iter, reset
b[n] = hashSeparator
n++
r.idx++
r.last = 0
}
// We reached end of hashes
return n, io.EOF
}
// nodeWriter is an io.Writer implementation for the node file representation,
// which is useful when calculated node file is being read from the store
type nodeWriter struct {
node *node
buf *bytes.Buffer
}
func (w *nodeWriter) Write(b []byte) (int, error) {
n := 0
for {
// Find next hash separator position
idx := bytes.IndexByte(b[n:], hashSeparator)
if idx == -1 {
// Check we shouldn't be expecting it
if w.buf.Len() > encodedHashLen {
return n, errInvalidNode
}
// Write all contents to buffer
w.buf.Write(b[n:])
return len(b), nil
}
// Found hash separator, write
// current buf contents to Node hashes
w.buf.Write(b[n : n+idx])
n += idx + 1
if w.buf.Len() != encodedHashLen {
return n, errInvalidNode
}
// Append to hashes & reset
w.node.hashes = append(w.node.hashes, w.buf.String())
w.buf.Reset()
}
}
// blockReader is an io.Reader implementation for the combined, linked block
// data contained with a node file. Basically, this allows reading value data
// from the store for a given node file
type blockReader struct {
storage *BlockStorage
node *node
buf []byte
prev int
}
func (r *blockReader) Read(b []byte) (int, error) {
n := 0
// Data left in buf, copy as much as we
// can into supplied read buffer
if r.prev < len(r.buf)-1 {
n += copy(b, r.buf[r.prev:])
r.prev += n
if n >= len(b) {
return n, nil
}
}
for {
// Check we have any hashes left
if len(r.node.hashes) < 1 {
return n, io.EOF
}
// Get next key from slice
key := r.node.hashes[0]
r.node.hashes = r.node.hashes[1:]
// Attempt to fetch next batch of data
var err error
r.buf, err = r.storage.readBlock(key)
if err != nil {
return n, err
}
r.prev = 0
// Copy as much as can from new buffer
m := copy(b[n:], r.buf)
r.prev += m
n += m
// If we hit end of supplied buf, return
if n >= len(b) {
return n, nil
}
}
}
// hashEncoder is a HashEncoder with built-in encode buffer
type hashEncoder struct {
henc hashenc.HashEncoder
ebuf []byte
}
// encodedHashLen is the once-calculated encoded hash-sum length
var encodedHashLen = hashenc.Base64().EncodedLen(
sha256.New().Size(),
)
// newHashEncoder returns a new hashEncoder instance
func newHashEncoder() *hashEncoder {
hash := sha256.New()
enc := hashenc.Base64()
return &hashEncoder{
henc: hashenc.New(hash, enc),
ebuf: make([]byte, enc.EncodedLen(hash.Size())),
}
}
// EncodeSum encodes the src data and returns resulting bytes, only valid until next call to EncodeSum()
func (henc *hashEncoder) EncodeSum(src []byte) bytes.Bytes {
henc.henc.EncodeSum(henc.ebuf, src)
return bytes.ToBytes(henc.ebuf)
}

104
vendor/codeberg.org/gruf/go-store/storage/compressor.go generated vendored Normal file
View File

@@ -0,0 +1,104 @@
package storage
import (
"compress/gzip"
"compress/zlib"
"io"
"codeberg.org/gruf/go-store/util"
"github.com/golang/snappy"
)
// Compressor defines a means of compressing/decompressing values going into a key-value store
type Compressor interface {
// Reader returns a new decompressing io.ReadCloser based on supplied (compressed) io.Reader
Reader(io.Reader) (io.ReadCloser, error)
// Writer returns a new compressing io.WriteCloser based on supplied (uncompressed) io.Writer
Writer(io.Writer) (io.WriteCloser, error)
}
type gzipCompressor struct {
level int
}
// GZipCompressor returns a new Compressor that implements GZip at default compression level
func GZipCompressor() Compressor {
return GZipCompressorLevel(gzip.DefaultCompression)
}
// GZipCompressorLevel returns a new Compressor that implements GZip at supplied compression level
func GZipCompressorLevel(level int) Compressor {
return &gzipCompressor{
level: level,
}
}
func (c *gzipCompressor) Reader(r io.Reader) (io.ReadCloser, error) {
return gzip.NewReader(r)
}
func (c *gzipCompressor) Writer(w io.Writer) (io.WriteCloser, error) {
return gzip.NewWriterLevel(w, c.level)
}
type zlibCompressor struct {
level int
dict []byte
}
// ZLibCompressor returns a new Compressor that implements ZLib at default compression level
func ZLibCompressor() Compressor {
return ZLibCompressorLevelDict(zlib.DefaultCompression, nil)
}
// ZLibCompressorLevel returns a new Compressor that implements ZLib at supplied compression level
func ZLibCompressorLevel(level int) Compressor {
return ZLibCompressorLevelDict(level, nil)
}
// ZLibCompressorLevelDict returns a new Compressor that implements ZLib at supplied compression level with supplied dict
func ZLibCompressorLevelDict(level int, dict []byte) Compressor {
return &zlibCompressor{
level: level,
dict: dict,
}
}
func (c *zlibCompressor) Reader(r io.Reader) (io.ReadCloser, error) {
return zlib.NewReaderDict(r, c.dict)
}
func (c *zlibCompressor) Writer(w io.Writer) (io.WriteCloser, error) {
return zlib.NewWriterLevelDict(w, c.level, c.dict)
}
type snappyCompressor struct{}
// SnappyCompressor returns a new Compressor that implements Snappy
func SnappyCompressor() Compressor {
return &snappyCompressor{}
}
func (c *snappyCompressor) Reader(r io.Reader) (io.ReadCloser, error) {
return util.NopReadCloser(snappy.NewReader(r)), nil
}
func (c *snappyCompressor) Writer(w io.Writer) (io.WriteCloser, error) {
return snappy.NewBufferedWriter(w), nil
}
type nopCompressor struct{}
// NoCompression is a Compressor that simply does nothing
func NoCompression() Compressor {
return &nopCompressor{}
}
func (c *nopCompressor) Reader(r io.Reader) (io.ReadCloser, error) {
return util.NopReadCloser(r), nil
}
func (c *nopCompressor) Writer(w io.Writer) (io.WriteCloser, error) {
return util.NopWriteCloser(w), nil
}

291
vendor/codeberg.org/gruf/go-store/storage/disk.go generated vendored Normal file
View File

@@ -0,0 +1,291 @@
package storage
import (
"io"
"io/fs"
"os"
"path"
"syscall"
"codeberg.org/gruf/go-bytes"
"codeberg.org/gruf/go-pools"
"codeberg.org/gruf/go-store/util"
)
// DefaultDiskConfig is the default DiskStorage configuration
var DefaultDiskConfig = &DiskConfig{
Overwrite: true,
WriteBufSize: 4096,
Transform: NopTransform(),
Compression: NoCompression(),
}
// DiskConfig defines options to be used when opening a DiskStorage
type DiskConfig struct {
// Transform is the supplied key<-->path KeyTransform
Transform KeyTransform
// WriteBufSize is the buffer size to use when writing file streams (PutStream)
WriteBufSize int
// Overwrite allows overwriting values of stored keys in the storage
Overwrite bool
// Compression is the Compressor to use when reading / writing files, default is no compression
Compression Compressor
}
// getDiskConfig returns a valid DiskConfig for supplied ptr
func getDiskConfig(cfg *DiskConfig) DiskConfig {
// If nil, use default
if cfg == nil {
cfg = DefaultDiskConfig
}
// Assume nil transform == none
if cfg.Transform == nil {
cfg.Transform = NopTransform()
}
// Assume nil compress == none
if cfg.Compression == nil {
cfg.Compression = NoCompression()
}
// Assume 0 buf size == use default
if cfg.WriteBufSize < 1 {
cfg.WriteBufSize = DefaultDiskConfig.WriteBufSize
}
// Return owned config copy
return DiskConfig{
Transform: cfg.Transform,
WriteBufSize: cfg.WriteBufSize,
Overwrite: cfg.Overwrite,
Compression: cfg.Compression,
}
}
// DiskStorage is a Storage implementation that stores directly to a filesystem
type DiskStorage struct {
path string // path is the root path of this store
dots int // dots is the "dotdot" count for the root store path
bufp pools.BufferPool // bufp is the buffer pool for this DiskStorage
config DiskConfig // cfg is the supplied configuration for this store
}
// OpenFile opens a DiskStorage instance for given folder path and configuration
func OpenFile(path string, cfg *DiskConfig) (*DiskStorage, error) {
// Acquire path builder
pb := util.GetPathBuilder()
defer util.PutPathBuilder(pb)
// Clean provided path, ensure ends in '/' (should
// be dir, this helps with file path trimming later)
path = pb.Clean(path) + "/"
// Get checked config
config := getDiskConfig(cfg)
// Attempt to open dir path
file, err := os.OpenFile(path, defaultFileROFlags, defaultDirPerms)
if err != nil {
// If not a not-exist error, return
if !os.IsNotExist(err) {
return nil, err
}
// Attempt to make store path dirs
err = os.MkdirAll(path, defaultDirPerms)
if err != nil {
return nil, err
}
// Reopen dir now it's been created
file, err = os.OpenFile(path, defaultFileROFlags, defaultDirPerms)
if err != nil {
return nil, err
}
}
defer file.Close()
// Double check this is a dir (NOT a file!)
stat, err := file.Stat()
if err != nil {
return nil, err
} else if !stat.IsDir() {
return nil, errPathIsFile
}
// Return new DiskStorage
return &DiskStorage{
path: path,
dots: util.CountDotdots(path),
bufp: pools.NewBufferPool(config.WriteBufSize),
config: config,
}, nil
}
// Clean implements Storage.Clean()
func (st *DiskStorage) Clean() error {
return util.CleanDirs(st.path)
}
// ReadBytes implements Storage.ReadBytes()
func (st *DiskStorage) ReadBytes(key string) ([]byte, error) {
// Get stream reader for key
rc, err := st.ReadStream(key)
if err != nil {
return nil, err
}
defer rc.Close()
// Read all bytes and return
return io.ReadAll(rc)
}
// ReadStream implements Storage.ReadStream()
func (st *DiskStorage) ReadStream(key string) (io.ReadCloser, error) {
// Get file path for key
kpath, err := st.filepath(key)
if err != nil {
return nil, err
}
// Attempt to open file (replace ENOENT with our own)
file, err := open(kpath, defaultFileROFlags)
if err != nil {
return nil, errSwapNotFound(err)
}
// Wrap the file in a compressor
cFile, err := st.config.Compression.Reader(file)
if err != nil {
file.Close() // close this here, ignore error
return nil, err
}
// Wrap compressor to ensure file close
return util.ReadCloserWithCallback(cFile, func() {
file.Close()
}), nil
}
// WriteBytes implements Storage.WriteBytes()
func (st *DiskStorage) WriteBytes(key string, value []byte) error {
return st.WriteStream(key, bytes.NewReader(value))
}
// WriteStream implements Storage.WriteStream()
func (st *DiskStorage) WriteStream(key string, r io.Reader) error {
// Get file path for key
kpath, err := st.filepath(key)
if err != nil {
return err
}
// Ensure dirs leading up to file exist
err = os.MkdirAll(path.Dir(kpath), defaultDirPerms)
if err != nil {
return err
}
// Prepare to swap error if need-be
errSwap := errSwapNoop
// Build file RW flags
flags := defaultFileRWFlags
if !st.config.Overwrite {
flags |= syscall.O_EXCL
// Catch + replace err exist
errSwap = errSwapExist
}
// Attempt to open file
file, err := open(kpath, flags)
if err != nil {
return errSwap(err)
}
defer file.Close()
// Wrap the file in a compressor
cFile, err := st.config.Compression.Writer(file)
if err != nil {
return err
}
defer cFile.Close()
// Acquire write buffer
buf := st.bufp.Get()
defer st.bufp.Put(buf)
buf.Grow(st.config.WriteBufSize)
// Copy reader to file
_, err = io.CopyBuffer(cFile, r, buf.B)
return err
}
// Stat implements Storage.Stat()
func (st *DiskStorage) Stat(key string) (bool, error) {
// Get file path for key
kpath, err := st.filepath(key)
if err != nil {
return false, err
}
// Check for file on disk
return stat(kpath)
}
// Remove implements Storage.Remove()
func (st *DiskStorage) Remove(key string) error {
// Get file path for key
kpath, err := st.filepath(key)
if err != nil {
return err
}
// Attempt to remove file
return os.Remove(kpath)
}
// WalkKeys implements Storage.WalkKeys()
func (st *DiskStorage) WalkKeys(opts *WalkKeysOptions) error {
// Acquire path builder
pb := util.GetPathBuilder()
defer util.PutPathBuilder(pb)
// Walk dir for entries
return util.WalkDir(pb, st.path, func(kpath string, fsentry fs.DirEntry) {
// Only deal with regular files
if fsentry.Type().IsRegular() {
// Get full item path (without root)
kpath = pb.Join(kpath, fsentry.Name())[len(st.path):]
// Perform provided walk function
opts.WalkFn(entry(st.config.Transform.PathToKey(kpath)))
}
})
}
// filepath checks and returns a formatted filepath for given key
func (st *DiskStorage) filepath(key string) (string, error) {
// Acquire path builder
pb := util.GetPathBuilder()
defer util.PutPathBuilder(pb)
// Calculate transformed key path
key = st.config.Transform.KeyToPath(key)
// Generated joined root path
pb.AppendString(st.path)
pb.AppendString(key)
// If path is dir traversal, and traverses FURTHER
// than store root, this is an error
if util.CountDotdots(pb.StringPtr()) > st.dots {
return "", ErrInvalidKey
}
return pb.String(), nil
}

63
vendor/codeberg.org/gruf/go-store/storage/errors.go generated vendored Normal file
View File

@@ -0,0 +1,63 @@
package storage
import (
"fmt"
"syscall"
)
// errorString is our own simple error type
type errorString string
// Error implements error
func (e errorString) Error() string {
return string(e)
}
// Extend appends extra information to an errorString
func (e errorString) Extend(s string, a ...interface{}) errorString {
return errorString(string(e) + ": " + fmt.Sprintf(s, a...))
}
var (
// ErrNotFound is the error returned when a key cannot be found in storage
ErrNotFound = errorString("store/storage: key not found")
// ErrAlreadyExist is the error returned when a key already exists in storage
ErrAlreadyExists = errorString("store/storage: key already exists")
// ErrInvalidkey is the error returned when an invalid key is passed to storage
ErrInvalidKey = errorString("store/storage: invalid key")
// errPathIsFile is returned when a path for a disk config is actually a file
errPathIsFile = errorString("store/storage: path is file")
// errNoHashesWritten is returned when no blocks are written for given input value
errNoHashesWritten = errorString("storage/storage: no hashes written")
// errInvalidNode is returned when read on an invalid node in the store is attempted
errInvalidNode = errorString("store/storage: invalid node")
// errCorruptNodes is returned when nodes with missing blocks are found during a BlockStorage clean
errCorruptNodes = errorString("store/storage: corrupted nodes")
)
// errSwapNoop performs no error swaps
func errSwapNoop(err error) error {
return err
}
// ErrSwapNotFound swaps syscall.ENOENT for ErrNotFound
func errSwapNotFound(err error) error {
if err == syscall.ENOENT {
return ErrNotFound
}
return err
}
// errSwapExist swaps syscall.EEXIST for ErrAlreadyExists
func errSwapExist(err error) error {
if err == syscall.EEXIST {
return ErrAlreadyExists
}
return err
}

48
vendor/codeberg.org/gruf/go-store/storage/fs.go generated vendored Normal file
View File

@@ -0,0 +1,48 @@
package storage
import (
"os"
"syscall"
"codeberg.org/gruf/go-store/util"
)
const (
defaultDirPerms = 0755
defaultFilePerms = 0644
defaultFileROFlags = syscall.O_RDONLY
defaultFileRWFlags = syscall.O_CREAT | syscall.O_RDWR
defaultFileLockFlags = syscall.O_RDONLY | syscall.O_EXCL | syscall.O_CREAT
)
// NOTE:
// These functions are for opening storage files,
// not necessarily for e.g. initial setup (OpenFile)
// open should not be called directly
func open(path string, flags int) (*os.File, error) {
var fd int
err := util.RetryOnEINTR(func() (err error) {
fd, err = syscall.Open(path, flags, defaultFilePerms)
return
})
if err != nil {
return nil, err
}
return os.NewFile(uintptr(fd), path), nil
}
// stat checks for a file on disk
func stat(path string) (bool, error) {
var stat syscall.Stat_t
err := util.RetryOnEINTR(func() error {
return syscall.Stat(path, &stat)
})
if err != nil {
if err == syscall.ENOENT {
err = nil
}
return false, err
}
return true, nil
}

34
vendor/codeberg.org/gruf/go-store/storage/lock.go generated vendored Normal file
View File

@@ -0,0 +1,34 @@
package storage
import (
"os"
"syscall"
"codeberg.org/gruf/go-store/util"
)
type lockableFile struct {
*os.File
}
func openLock(path string) (*lockableFile, error) {
file, err := open(path, defaultFileLockFlags)
if err != nil {
return nil, err
}
return &lockableFile{file}, nil
}
func (f *lockableFile) lock() error {
return f.flock(syscall.LOCK_EX | syscall.LOCK_NB)
}
func (f *lockableFile) unlock() error {
return f.flock(syscall.LOCK_UN | syscall.LOCK_NB)
}
func (f *lockableFile) flock(how int) error {
return util.RetryOnEINTR(func() error {
return syscall.Flock(int(f.Fd()), how)
})
}

51
vendor/codeberg.org/gruf/go-store/storage/storage.go generated vendored Normal file
View File

@@ -0,0 +1,51 @@
package storage
import (
"io"
)
// StorageEntry defines a key in Storage
type StorageEntry interface {
// Key returns the storage entry's key
Key() string
}
// entry is the simplest possible StorageEntry
type entry string
func (e entry) Key() string {
return string(e)
}
// Storage defines a means of storing and accessing key value pairs
type Storage interface {
// Clean removes unused values and unclutters the storage (e.g. removing empty folders)
Clean() error
// ReadBytes returns the byte value for key in storage
ReadBytes(key string) ([]byte, error)
// ReadStream returns an io.ReadCloser for the value bytes at key in the storage
ReadStream(key string) (io.ReadCloser, error)
// WriteBytes writes the supplied value bytes at key in the storage
WriteBytes(key string, value []byte) error
// WriteStream writes the bytes from supplied reader at key in the storage
WriteStream(key string, r io.Reader) error
// Stat checks if the supplied key is in the storage
Stat(key string) (bool, error)
// Remove attempts to remove the supplied key-value pair from storage
Remove(key string) error
// WalkKeys walks the keys in the storage
WalkKeys(opts *WalkKeysOptions) error
}
// WalkKeysOptions defines how to walk the keys in a storage implementation
type WalkKeysOptions struct {
// WalkFn is the function to apply on each StorageEntry
WalkFn func(StorageEntry)
}

25
vendor/codeberg.org/gruf/go-store/storage/transform.go generated vendored Normal file
View File

@@ -0,0 +1,25 @@
package storage
// KeyTransform defines a method of converting store keys to storage paths (and vice-versa)
type KeyTransform interface {
// KeyToPath converts a supplied key to storage path
KeyToPath(string) string
// PathToKey converts a supplied storage path to key
PathToKey(string) string
}
type nopKeyTransform struct{}
// NopTransform returns a nop key transform (i.e. key = path)
func NopTransform() KeyTransform {
return &nopKeyTransform{}
}
func (t *nopKeyTransform) KeyToPath(key string) string {
return key
}
func (t *nopKeyTransform) PathToKey(path string) string {
return path
}

105
vendor/codeberg.org/gruf/go-store/util/fs.go generated vendored Normal file
View File

@@ -0,0 +1,105 @@
package util
import (
"io/fs"
"os"
"strings"
"syscall"
"codeberg.org/gruf/go-fastpath"
)
var dotdot = "../"
// CountDotdots returns the number of "dot-dots" (../) in a cleaned filesystem path
func CountDotdots(path string) int {
if !strings.HasSuffix(path, dotdot) {
return 0
}
return strings.Count(path, dotdot)
}
// WalkDir traverses the dir tree of the supplied path, performing the supplied walkFn on each entry
func WalkDir(pb *fastpath.Builder, path string, walkFn func(string, fs.DirEntry)) error {
// Read supplied dir path
dirEntries, err := os.ReadDir(path)
if err != nil {
return err
}
// Iter entries
for _, entry := range dirEntries {
// Pass to walk fn
walkFn(path, entry)
// Recurse dir entries
if entry.IsDir() {
err = WalkDir(pb, pb.Join(path, entry.Name()), walkFn)
if err != nil {
return err
}
}
}
return nil
}
// CleanDirs traverses the dir tree of the supplied path, removing any folders with zero children
func CleanDirs(path string) error {
// Acquire builder
pb := GetPathBuilder()
defer PutPathBuilder(pb)
// Get dir entries
entries, err := os.ReadDir(path)
if err != nil {
return err
}
// Recurse dirs
for _, entry := range entries {
if entry.IsDir() {
err := cleanDirs(pb, pb.Join(path, entry.Name()))
if err != nil {
return err
}
}
}
return nil
}
// cleanDirs performs the actual dir cleaning logic for the exported version
func cleanDirs(pb *fastpath.Builder, path string) error {
// Get dir entries
entries, err := os.ReadDir(path)
if err != nil {
return err
}
// If no entries, delete
if len(entries) < 1 {
return os.Remove(path)
}
// Recurse dirs
for _, entry := range entries {
if entry.IsDir() {
err := cleanDirs(pb, pb.Join(path, entry.Name()))
if err != nil {
return err
}
}
}
return nil
}
// RetryOnEINTR is a low-level filesystem function for retrying syscalls on O_EINTR received
func RetryOnEINTR(do func() error) error {
for {
err := do()
if err == syscall.EINTR {
continue
}
return err
}
}

42
vendor/codeberg.org/gruf/go-store/util/io.go generated vendored Normal file
View File

@@ -0,0 +1,42 @@
package util
import "io"
// NopReadCloser turns a supplied io.Reader into io.ReadCloser with a nop Close() implementation
func NopReadCloser(r io.Reader) io.ReadCloser {
return &nopReadCloser{r}
}
// NopWriteCloser turns a supplied io.Writer into io.WriteCloser with a nop Close() implementation
func NopWriteCloser(w io.Writer) io.WriteCloser {
return &nopWriteCloser{w}
}
// ReadCloserWithCallback adds a customizable callback to be called upon Close() of a supplied io.ReadCloser
func ReadCloserWithCallback(rc io.ReadCloser, cb func()) io.ReadCloser {
return &callbackReadCloser{
ReadCloser: rc,
callback: cb,
}
}
// nopReadCloser turns an io.Reader -> io.ReadCloser with a nop Close()
type nopReadCloser struct{ io.Reader }
func (r *nopReadCloser) Close() error { return nil }
// nopWriteCloser turns an io.Writer -> io.WriteCloser with a nop Close()
type nopWriteCloser struct{ io.Writer }
func (w nopWriteCloser) Close() error { return nil }
// callbackReadCloser allows adding our own custom callback to an io.ReadCloser
type callbackReadCloser struct {
io.ReadCloser
callback func()
}
func (c *callbackReadCloser) Close() error {
defer c.callback()
return c.ReadCloser.Close()
}

20
vendor/codeberg.org/gruf/go-store/util/pool.go generated vendored Normal file
View File

@@ -0,0 +1,20 @@
package util
import (
"codeberg.org/gruf/go-fastpath"
"codeberg.org/gruf/go-pools"
)
// pathBuilderPool is the global fastpath.Builder pool
var pathBuilderPool = pools.NewPathBuilderPool(512)
// GetPathBuilder fetches a fastpath.Builder object from the pool
func GetPathBuilder() *fastpath.Builder {
return pathBuilderPool.Get()
}
// PutPathBuilder places supplied fastpath.Builder back in the pool
func PutPathBuilder(pb *fastpath.Builder) {
pb.Reset()
pathBuilderPool.Put(pb)
}