typx

package module
v1.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 22, 2026 License: BSD-3-Clause Imports: 15 Imported by: 1

README

typX

typX is a Go package that provides useful types, helpers and utilities. It currently includes the following:

  • Nil - Represents a nullable value. Implements SQL, JSON, and BSON encoding. Use instead of *T for nullable fields.
  • Opt - Represents an optional (present vs. absent) value. Implements JSON (omitzero) and BSON (omitempty) encoding. Use for optional fields in API payloads.
  • Dyn - A dynamic type that holds any value with full support for JSON, SQL, and BSON encoding. Useful for storing arbitrary JSON/BSON data in databases.
  • KV / KVs - A generic key-value pair and slice type with full JSON, SQL, and BSON encoding support. Useful for query parameters, metadata, and ordered maps.
  • Range / MultiRange - PostgreSQL-compatible range and multirange types for any cmp.Ordered type (e.g. int, float64, string). Support SQL scan/value using native PG range literals.
  • OrderedRange / OrderedMultiRange - Range and multirange types for custom types implementing the Ordered[T] interface. When the bound type also implements PGBoundMarshaler / PGBoundUnmarshaler, native PG range literals are used; otherwise values are JSON-encoded.
  • Ordered / PGBoundMarshaler / PGBoundUnmarshaler - Interfaces for custom ordered types and PostgreSQL bound serialization.
  • DateTime - A time.Time wrapper implementing Ordered[DateTime], PGBoundMarshaler, PGBoundUnmarshaler, sql.Scanner, and driver.Valuer. Ready to use as bounds in OrderedRange[DateTime] / OrderedMultiRange[DateTime] (maps to tstzrange / tstzmultirange).
  • Str64 - A []byte type that transparently encodes as unpadded base64url (alphabet: A-Z a-z 0-9 - _) in JSON and any text transport via encoding.TextMarshaler / encoding.TextUnmarshaler. Useful for compact UUID representation, URL-safe tokens, and loggable binary values.
  • Must / Must2 / Must3 - Generic panic-on-error helpers for unwrapping one, two, or three return values alongside an error.
  • Pointer Helpers - FromPtr and FromPtrOrZero for safe pointer dereferencing. (Ptr is deprecated since Go 1.26 provides value initialization via the built-in new.)
  • Duration - A duration type that combines a time.Duration with separate Day and Month fields, enabling calendar-aware durations (e.g. PostgreSQL interval). Marshals to/from ISO 8601 (P1Y2M3DT4H5M6S) via encoding.TextMarshaler / encoding.TextUnmarshaler.
  • URL - A url.URL wrapper that serialises as a plain URL string in all common transports. Implements encoding.TextMarshaler / encoding.TextUnmarshaler (JSON), driver.Valuer, and sql.Scanner. Use Nil[URL] for nullable SQL columns.

Example

// Main model
type User struct {
    ID             typx.Str64                      // compact base64url representation of raw ID bytes
    Name           string
    Mobile         string
    Landline       typx.Nil[string]                // nullable, instead of *string
    AdditionalInfo typx.Dyn                        // arbitrary JSON/BSON data
    ActiveWindow   typx.OrderedRange[typx.DateTime] // tstzrange column
}

// A sample DTO for PATCH /api/v1/user/{id}
// Fields absent from the request body remain unset (Opt.Set == false).
type UpdateUserDTO struct {
    Name           typx.Opt[string]
    Mobile         typx.Opt[string]
    Landline       typx.Opt[typx.Nil[string]]
    AdditionalInfo typx.Opt[typx.Dyn]
}

// KV / KVs example
func NewDatabaseConnection(config ...typx.KV[string, string]) (*sql.DB, error) {
    for _, kv := range config {
        cfg.Set(kv.Key, kv.Val)
    }
    // ...
}

// Range example (built-in ordered types, e.g. int)
var r typx.Range[int]
_ = r.Scan("[10,20)")         // lower inclusive, upper exclusive
contains := r.Contains(15)   // true

// MultiRange example
var mr typx.MultiRange[int]
_ = mr.Scan("{[1,5],[10,20)}")
contains = mr.Contains(12)   // true

// OrderedRange with DateTime (maps to tstzrange)
var tr typx.OrderedRange[typx.DateTime]
_ = tr.Scan(`["2024-01-01 00:00:00+00","2025-01-01 00:00:00+00")`)

// Str64 — compact URL-safe UUID
uid := uuid.New()
s := typx.Str64(uid[:])      // 16 bytes → 22-char base64url string
fmt.Println(s)               // e.g. "BpLnfgDsc2WD8F2qNkHydQ"
s2, _ := typx.FromString(s.String())
uid2, _ := uuid.FromBytes(s2)

// Must helpers
val := typx.Must(strconv.Atoi("42")) // panics on error

// Duration — calendar-aware duration, marshals as ISO 8601
d := typx.Duration{Month: 14, Day: 3, Time: 4*time.Hour + 30*time.Minute}
text, _ := d.MarshalText() // "P1Y2M3DT4H30M"
var d2 typx.Duration
_ = d2.UnmarshalText(text)

// URL — plain-string transport for url.URL
cb, _ := typx.URLFrom("https://example.com/callback?token=abc")
fmt.Println(cb) // https://example.com/callback?token=abc
// Stores as TEXT in SQL; use Nil[URL] for nullable columns
type Webhook struct {
    ID       int
    Callback typx.Nil[typx.URL]
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FromPtr

func FromPtr[T any](ptr *T) (T, bool)

FromPtr safely dereferences the given pointer and returns it along with a boolean indicating whether the pointer was non-nil.

func FromPtrOrZero added in v1.2.0

func FromPtrOrZero[T any](ptr *T) T

FromPtrOrZero safely dereferences the given pointer and returns its value. If the pointer is nil, it returns the zero value of T.

func Must added in v1.4.0

func Must[T any](val T, err error) T

Must is a helper that panics if the error is non-nil, otherwise returning the value.

func Must2 added in v1.4.0

func Must2[T, U any](val T, val2 U, err error) (T, U)

Must2 is a helper that panics if the error is non-nil, otherwise returning the two values.

func Must3 added in v1.4.0

func Must3[T, U, V any](val T, val2 U, val3 V, err error) (T, U, V)

Must3 is a helper that panics if the error is non-nil, otherwise returning the three values.

func Ptr deprecated

func Ptr[T any](value T) *T

Ptr creates a pointer to the receiver copy of the given value. Useful for inline pointer creation such as function calls.

Deprecated: Since Go 1.26, you can use the built-in new(value) instead.

Types

type Bound added in v1.4.0

type Bound[O cmp.Ordered] struct {
	Val       O    `json:"val" bson:"val"`                                 // the bound value
	Exclusive bool `json:"exclusive,omitempty" bson:"exclusive,omitempty"` // whether the bound is exclusive (true) or inclusive (false); ignored when Unbounded is true
	Unbounded bool `json:"unbounded,omitempty" bson:"unbounded,omitempty"` // whether this is an infinite/unbounded bound (true) or a finite bound (false)
}

Bound represents one end of a range with its value and whether it is exclusive. The zero value is inclusive (Exclusive == false) and bounded. When Unbounded is true the bound is ±∞; Val and Exclusive are ignored.

type DateTime added in v1.4.0

type DateTime struct{ time.Time }

DateTime is a time.Time wrapper for use as an OrderedRange / OrderedMultiRange with tsrange, tstzrange, tsmultirange, and tstzmultirange backing types. All constructors and methods strip the monotonic clock reading so that two DateTime values representing the same instant compare and marshal identically.

This type also supports operations with the Duration type, which supports dynamic Month and Day components.

func (DateTime) AddDuration added in v1.5.0

func (t DateTime) AddDuration(d Duration) DateTime

AddDuration adds a Duration with dynamic Month and Day components to the DateTime, returning a new DateTime.

func (DateTime) Compare added in v1.4.0

func (t DateTime) Compare(other DateTime) int

Compare implements the Ordered interface by comparing the time values with the monotonic clock stripped.

func (DateTime) MarshalPGBound added in v1.4.0

func (t DateTime) MarshalPGBound() ([]byte, error)

MarshalPGBound implements PGBoundMarshaler. Produces a PostgreSQL timestamptz literal.

func (*DateTime) Scan added in v1.4.0

func (t *DateTime) Scan(value any) error

Scan implements sql.Scanner. The driver is expected to deliver a time.Time value (which pgx and database/sql do for DATE, TIMESTAMP, and TIMESTAMPTZ columns alike). A nil value (SQL NULL) zeroes the receiver. Use Nil[DateTime] for a type that can be nil instead of zero.

func (DateTime) SubDateTime added in v1.5.0

func (t DateTime) SubDateTime(other DateTime) Duration

SubDateTime returns the Duration d such that t.Equal(other.AddDuration(d)).

func (*DateTime) UnmarshalPGBound added in v1.4.0

func (t *DateTime) UnmarshalPGBound(text []byte) error

UnmarshalPGBound implements PGBoundUnmarshaler. Accepts a PostgreSQL timestamptz literal, including the double-quoted form that PostgreSQL uses for timestamp bounds inside range literals

func (DateTime) Value added in v1.4.0

func (t DateTime) Value() (driver.Value, error)

Value implements driver.Valuer. Returns the time with the monotonic clock stripped.

type Duration added in v1.5.0

type Duration struct {
	Time  time.Duration // The [time.Duration] field represents the time part of duration in terms of hours, minutes, seconds, etc.
	Day   int64         // The Day field represents the number of days in the duration. This is useful for calculations that need to account for varying lengths of days (e.g., due to daylight saving time changes).
	Month int64         // The Month field represents the number of months in the duration. This is useful for calculations that need to account for varying lengths of months (e.g., due to the number of days in each month).
}

Duration is a struct that represents a duration of time, including both a time.Duration and additional fields for days and months. This allows for more flexible time calculations that can account for varying lengths of days and months.

func (Duration) Abs added in v1.5.0

func (d Duration) Abs() Duration

Abs returns a new Duration with the absolute values of the time, day, and month components. This is useful for ensuring that all components of the duration are non-negative, regardless of their original signs.

func (Duration) Add added in v1.5.0

func (d Duration) Add(other Duration) Duration

Add adds another Duration to the current Duration, combining their time, day, and month components. The operation is similar to a vector addition, as they are independent unless a point in time is being calculated.

func (Duration) MarshalText added in v1.5.0

func (d Duration) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface. Produces an ISO 8601 duration string (e.g. "P1Y2M3DT4H5M6.789S"). Month values >= 12 are expressed as years + remaining months.

func (Duration) String added in v1.5.0

func (d Duration) String() string

String returns a string representation of the Duration, combining the time, day, and month components into a human-readable format.

func (Duration) Sub added in v1.5.0

func (d Duration) Sub(other Duration) Duration

Sub subtracts another Duration from the current Duration, combining their time, day, and month components. The operation is similar to a vector subtraction, as they are independent unless a point in time is being calculated.

func (*Duration) UnmarshalText added in v1.5.0

func (d *Duration) UnmarshalText(text []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface. Accepts an ISO 8601 duration string (e.g. "P1Y2M3DT4H5M6.789S"). Years are converted to months (1Y = 12M). A leading "-P" negates all components.

type Dyn added in v1.1.0

type Dyn struct{ Val any }

Dyn is a dynamic type that can hold any value type. When using with SQL, the column should be a type that can hold JSON data (JSONB, JSON, TEXT, etc).

func (Dyn) MarshalBSON added in v1.4.0

func (d Dyn) MarshalBSON() ([]byte, error)

MarshalBSON implements the bson.Marshaler interface for use as a standalone document.

func (Dyn) MarshalBSONValue added in v1.1.0

func (d Dyn) MarshalBSONValue() (byte, []byte, error)

MarshalBSONValue implements the bson.ValueMarshaler interface.

func (Dyn) MarshalBinary added in v1.1.0

func (d Dyn) MarshalBinary() ([]byte, error)

MarshalBinary implements the encoding.BinaryMarshaler interface.

func (Dyn) MarshalJSON added in v1.1.0

func (d Dyn) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (Dyn) MarshalText added in v1.1.0

func (d Dyn) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface.

func (*Dyn) Scan added in v1.1.0

func (d *Dyn) Scan(src any) error

Scan implements the sql.Scanner interface.

func (*Dyn) UnmarshalBSON added in v1.4.0

func (d *Dyn) UnmarshalBSON(data []byte) error

UnmarshalBSON implements the bson.Unmarshaler interface for use as a standalone document.

func (*Dyn) UnmarshalBSONValue added in v1.1.0

func (d *Dyn) UnmarshalBSONValue(t byte, data []byte) error

UnmarshalBSONValue implements the bson.ValueUnmarshaler interface.

func (*Dyn) UnmarshalBinary added in v1.1.0

func (d *Dyn) UnmarshalBinary(data []byte) error

UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.

func (*Dyn) UnmarshalJSON added in v1.1.0

func (d *Dyn) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

func (*Dyn) UnmarshalText added in v1.1.0

func (d *Dyn) UnmarshalText(data []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

func (Dyn) Value added in v1.1.0

func (d Dyn) Value() (driver.Value, error)

Value implements the driver.Valuer interface.

type KV added in v1.3.0

type KV[K comparable, V any] struct {
	Key K
	Val V
}

KV represents a key-value pair with a comparable key and any value.

func KVFrom added in v1.3.0

func KVFrom[K comparable, V any](key K, val V) KV[K, V]

KVFrom creates a KV pair from the given key and value.

type KVs added in v1.3.0

type KVs[K comparable, V any] []KV[K, V]

KVs is a slice of KV pairs that provides utility methods for working with key-value collections.

func KVsFrom added in v1.3.0

func KVsFrom[K comparable, V any](kvs ...KV[K, V]) KVs[K, V]

KVsFrom creates a KVs slice from the given KV pairs.

func KVsFromMap added in v1.3.0

func KVsFromMap[K comparable, V any](m map[K]V) KVs[K, V]

KVsFromMap creates a KVs slice from the given map of key-value pairs.

func (KVs[K, V]) Keys added in v1.3.0

func (kvs KVs[K, V]) Keys() []K

Keys returns a slice of all keys in the KVs collection.

func (KVs[K, V]) Map added in v1.3.0

func (kvs KVs[K, V]) Map() map[K]V

Map converts the KVs collection into a map of key-value pairs.

func (KVs[K, V]) MarshalBSON added in v1.4.0

func (kvs KVs[K, V]) MarshalBSON() ([]byte, error)

MarshalBSON implements the bson.Marshaler interface for use as a standalone document.

func (KVs[K, V]) MarshalBSONValue added in v1.4.0

func (kvs KVs[K, V]) MarshalBSONValue() (byte, []byte, error)

MarshalBSONValue implements the bson.ValueMarshaler interface. KVs is serialized as a single BSON document: {k1: v1, k2: v2, ...}.

func (KVs[K, V]) MarshalJSON added in v1.4.0

func (kvs KVs[K, V]) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface. KVs is serialized as a single JSON object: {"k1": v1, "k2": v2, ...}.

func (*KVs[K, V]) Scan added in v1.4.0

func (kvs *KVs[K, V]) Scan(src any) error

Scan implements the sql.Scanner interface. The column should be a type that can hold JSON data (JSONB, JSON, TEXT, etc).

func (*KVs[K, V]) UnmarshalBSON added in v1.4.0

func (kvs *KVs[K, V]) UnmarshalBSON(data []byte) error

UnmarshalBSON implements the bson.Unmarshaler interface for use as a standalone document.

func (*KVs[K, V]) UnmarshalBSONValue added in v1.4.0

func (kvs *KVs[K, V]) UnmarshalBSONValue(t byte, data []byte) error

UnmarshalBSONValue implements the bson.ValueUnmarshaler interface.

func (*KVs[K, V]) UnmarshalJSON added in v1.4.0

func (kvs *KVs[K, V]) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

func (KVs[K, V]) Vals added in v1.3.0

func (kvs KVs[K, V]) Vals() []V

Vals returns a slice of all values in the KVs collection.

func (KVs[K, V]) Value added in v1.4.0

func (kvs KVs[K, V]) Value() (driver.Value, error)

Value implements the driver.Valuer interface.

type MultiRange added in v1.4.0

type MultiRange[O cmp.Ordered] []Range[O]

func NewMultiRange added in v1.4.0

func NewMultiRange[O cmp.Ordered](src []Range[O]) MultiRange[O]

NewMultiRange takes a slice of [Range]s and returns a new MultiRange that is optimized by merging overlapping ranges.

func (MultiRange[O]) Contains added in v1.4.0

func (mr MultiRange[O]) Contains(val O) bool

Contains returns true if the given value is contained within any of the ranges in the multirange.

func (*MultiRange[O]) Scan added in v1.4.0

func (mr *MultiRange[O]) Scan(src any) error

Scan implements the sql.Scanner interface for MultiRange. It expects a PostgreSQL multirange literal such as {[1,5],[10,20]}.

func (MultiRange[O]) Value added in v1.4.0

func (mr MultiRange[O]) Value() (driver.Value, error)

Value implements the driver.Valuer interface for MultiRange. It returns a PostgreSQL multirange literal such as {[1,5],[10,20]}.

type Nil

type Nil[T any] struct {
	Val    T
	NotNil bool
}

Nil is a type that can be used to represent a nil/nullable value. It implements most of the interfaces that are used to marshal and unmarshal values. For optional values that are not present, use Opt instead.

func NilFrom

func NilFrom[T any](value T) Nil[T]

NilFrom creates a Nil from a non-nil value.

func NilFromPtr

func NilFromPtr[T any](value *T) Nil[T]

NilFromPtr creates a Nil from a pointer. If the pointer is nil, NotNil is false.

func (Nil[T]) MarshalBSONValue

func (n Nil[T]) MarshalBSONValue() (byte, []byte, error)

MarshalBSONValue implements the bson.ValueMarshaler interface.

func (Nil[T]) MarshalBinary

func (n Nil[T]) MarshalBinary() ([]byte, error)

MarshalBinary implements the encoding.BinaryMarshaler interface.

func (Nil[T]) MarshalJSON

func (n Nil[T]) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface.

func (Nil[T]) MarshalText

func (n Nil[T]) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface.

func (Nil[T]) Ptr

func (n Nil[T]) Ptr() *T

Ptr returns a pointer to the value if NotNil is true, otherwise nil. It uses a non-pointer receiver so that the modified pointer does not affect the original value.

func (*Nil[T]) Scan

func (n *Nil[T]) Scan(src any) error

Scan implements the sql.Scanner interface.

func (*Nil[T]) UnmarshalBSONValue

func (n *Nil[T]) UnmarshalBSONValue(t byte, data []byte) error

UnmarshalBSONValue implements the bson.ValueUnmarshaler interface.

func (*Nil[T]) UnmarshalBinary

func (n *Nil[T]) UnmarshalBinary(data []byte) error

UnmarshalBinary implements the encoding.BinaryUnmarshaler interface.

func (*Nil[T]) UnmarshalJSON

func (n *Nil[T]) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface.

func (*Nil[T]) UnmarshalText

func (n *Nil[T]) UnmarshalText(data []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface.

func (Nil[T]) Value

func (n Nil[T]) Value() (driver.Value, error)

Value implements the driver.Valuer interface.

type Opt

type Opt[T any] struct {
	Val T
	Set bool
}

Opt is a type that can be used to represent an optional value (present vs. absent). It should be used for fields that may be missing entirely in serialized form. For nullable values (present but null), use Nil instead. Combining both is possible: Opt[Nil[T]] represents a field that can be absent, null, or a value.

Use the `omitzero` JSON struct tag to omit absent fields. Example:

type Struct struct {
	Field Opt[int] `json:"field,omitzero"`
}

func OptFrom

func OptFrom[T any](value T) Opt[T]

OptFrom creates an Opt that is set to the given value.

func OptFromPtr

func OptFromPtr[T any](ptr *T) Opt[T]

OptFromPtr creates an Opt from a pointer. If the pointer is nil, the result is unset.

func (Opt[T]) IsZero added in v1.4.0

func (o Opt[T]) IsZero() bool

IsZero returns true when the value is absent. This enables the `omitzero` struct tag in encoding/json (Go 1.24+).

func (Opt[T]) MarshalBSONValue added in v1.4.0

func (o Opt[T]) MarshalBSONValue() (byte, []byte, error)

MarshalBSONValue implements the bson.ValueMarshaler interface. Returns an error if the value is not set, to prevent silent null serialization. Use the `omitempty` struct tag to omit absent fields instead of marshaling them directly.

func (Opt[T]) MarshalJSON added in v1.4.0

func (o Opt[T]) MarshalJSON() ([]byte, error)

MarshalJSON marshals the inner value transparently. Returns an error if the value is not set, to prevent silent null serialization. Use the `omitzero` struct tag to omit absent fields instead of marshaling them directly.

func (*Opt[T]) UnmarshalBSONValue added in v1.4.0

func (o *Opt[T]) UnmarshalBSONValue(t byte, data []byte) error

UnmarshalBSONValue implements the bson.ValueUnmarshaler interface. It always marks the Opt as set and delegates to the inner type.

func (*Opt[T]) UnmarshalJSON added in v1.4.0

func (o *Opt[T]) UnmarshalJSON(data []byte) error

UnmarshalJSON is called only when the field is present in the JSON input (even as null). It always marks the Opt as set and delegates to the inner type.

type Ordered added in v1.4.0

type Ordered[T any] interface {
	Compare(T) int
}

Ordered is a type constraint that matches any type that implements a total ordering via the Compare method. Types implementing Ordered can use the OrderedRange and OrderedMultiRange types in this package. Additionally, if an Ordered type implements PGBoundMarshaler and PGBoundUnmarshaler, it can be used with PostgreSQL range types in a way that produces native range literals instead of JSON-encoded values.

type OrderedBound added in v1.4.0

type OrderedBound[O Ordered[O]] struct {
	Val       O    `json:"val" bson:"val"`                                 // the bound value
	Exclusive bool `json:"exclusive,omitempty" bson:"exclusive,omitempty"` // whether the bound is exclusive (true) or inclusive (false); ignored when Unbounded is true
	Unbounded bool `json:"unbounded,omitempty" bson:"unbounded,omitempty"` // whether this is an infinite/unbounded bound (true) or a finite bound (false)
}

OrderedBound represents one end of an OrderedRange with its value and whether it is exclusive. The zero value is inclusive (Exclusive == false) and bounded. When Unbounded is true the bound is ±∞; Val and Exclusive are ignored.

type OrderedMultiRange added in v1.4.0

type OrderedMultiRange[O Ordered[O]] []OrderedRange[O]

OrderedMultiRange represents a slice of non-overlapping [OrderedRange]s of the same type, sorted by lower bound.

func NewOrderedMultiRange added in v1.4.0

func NewOrderedMultiRange[O Ordered[O]](src []OrderedRange[O]) OrderedMultiRange[O]

NewOrderedMultiRange takes a slice of [OrderedRange]s and returns an OrderedMultiRange with overlapping or adjacent ranges merged.

func (OrderedMultiRange[O]) Contains added in v1.4.0

func (mr OrderedMultiRange[O]) Contains(val O) bool

Contains returns true if the given value is contained within any of the ranges in the multi range.

func (*OrderedMultiRange[O]) Scan added in v1.4.0

func (mr *OrderedMultiRange[O]) Scan(src any) error

Scan implements the sql.Scanner interface for OrderedMultiRange. If *O implements PGBoundUnmarshaler it parses a PostgreSQL multirange literal (e.g. {[1,5],[10,20]}). Otherwise it JSON-decodes a JSON array of range objects, suitable for text/jsonb columns.

func (OrderedMultiRange[O]) Value added in v1.4.0

func (mr OrderedMultiRange[O]) Value() (driver.Value, error)

Value implements the driver.Valuer interface for OrderedMultiRange. If O or *O implements PGBoundMarshaler it returns a PostgreSQL multirange literal (e.g. {[1,5],[10,20]}). Otherwise it JSON-encodes the multirange as a JSON array for storage in a text/jsonb column.

type OrderedRange added in v1.4.0

type OrderedRange[O Ordered[O]] struct {
	Lower OrderedBound[O] `json:"lower" bson:"lower"` // lower bound
	Upper OrderedBound[O] `json:"upper" bson:"upper"` // upper bound
}

OrderedRange supports any Ordered type for in-process use, JSON, and BSON storage. The Scan and Value methods implement PostgreSQL range literals; note that string-based types have no corresponding PostgreSQL range type and should not be used with SQL. In the case of a type implementing PGBoundUnmarshaler/PGBoundMarshaler, those are used to parse/format the bounds of the range literal.

func (OrderedRange[O]) Contains added in v1.4.0

func (r OrderedRange[O]) Contains(val O) bool

Contains returns true if the given value is contained within the range.

func (*OrderedRange[O]) Scan added in v1.4.0

func (r *OrderedRange[O]) Scan(src any) error

Scan implements the sql.Scanner interface for OrderedRange. If *O implements PGBoundUnmarshaler it parses a PostgreSQL range literal (e.g. [min,max]). Otherwise it JSON-decodes a range object, suitable for text/jsonb columns.

func (OrderedRange[O]) Value added in v1.4.0

func (r OrderedRange[O]) Value() (driver.Value, error)

Value implements the driver.Valuer interface for OrderedRange. If O or *O implements PGBoundMarshaler it returns a PostgreSQL range literal (e.g. [min,max)). Otherwise it JSON-encodes the range for storage in a text/jsonb column.

type PGBoundMarshaler added in v1.4.0

type PGBoundMarshaler interface {
	MarshalPGBound() ([]byte, error)
}

PGBoundMarshaler is implemented by values that can serialize themselves as a PostgreSQL range bound literal (e.g. "2024-01-01 00:00:00+00" for tstzrange, "12345" for numrange). OrderedRange.Value and OrderedMultiRange.Value use this to produce a native PG range literal; types that don't implement it are JSON-encoded instead. In non-PostgreSQL but still SQL contexts, the same PostgreSQL range literal syntax is used but without relying on the database to parse it.

type PGBoundUnmarshaler added in v1.4.0

type PGBoundUnmarshaler interface {
	UnmarshalPGBound([]byte) error
}

PGBoundUnmarshaler is implemented by values that can deserialize themselves from a PostgreSQL range bound literal. OrderedRange.Scan and OrderedMultiRange.Scan use this to parse a native PG range literal; types that don't implement it are JSON-decoded instead. In non-PostgreSQL but still SQL contexts, the same PostgreSQL range literal syntax is used but without relying on the database to parse it.

type Range added in v1.4.0

type Range[O cmp.Ordered] struct {
	Lower Bound[O] `json:"lower" bson:"lower"` // lower bound
	Upper Bound[O] `json:"upper" bson:"upper"` // upper bound
}

Range supports any cmp.Ordered type for in-process use, JSON, and BSON storage. The Scan and Value methods implement PostgreSQL range literals; note that string-based types have no corresponding PostgreSQL range type and should not be used with SQL.

func (Range[O]) Contains added in v1.4.0

func (r Range[O]) Contains(val O) bool

Contains returns true if the given value is contained within the range.

func (*Range[O]) Scan added in v1.4.0

func (r *Range[O]) Scan(src any) error

Scan implements the sql.Scanner interface for Range. It expects a PostgreSQL range literal such as [min,max] or (min,max).

func (Range[O]) Value added in v1.4.0

func (r Range[O]) Value() (driver.Value, error)

Value implements the driver.Valuer interface for Range. It returns a PostgreSQL range literal respecting the bound types, e.g. [min,max) or (min,max].

type Str64 added in v1.4.0

type Str64 []byte

Str64 is a named []byte type that encodes arbitrary byte slices as unpadded base64url strings (alphabet: A-Z, a-z, 0-9, -, _) via base64.RawURLEncoding. Because it implements encoding.TextMarshaler / encoding.TextUnmarshaler, it serialises automatically in JSON, and any other text-based transport or storage without extra conversion, while having the possibility of being saved as raw bytes, such as in Redis or a database.

Typical use cases:

  1. Shorter UUID representation. A UUID is 16 bytes. As a standard hyphenated string it is 36 characters; as Str64 it is 22 characters — a 39 % reduction — while still being URL-safe.

  2. Custom Variable-length identifiers. When a UUID's 128 bits of entropy is more (or less) than needed, Str64 works for any byte length: 8 bytes (64-bit) encodes to 11 chars, 32 bytes to 43 chars.

  3. Compact string storage. If a string's content is limited to the Str64 alphabet (A-Z, a-z, 0-9, -, _), storing it as Str64 bytes saves 25 % of space (6 bits stored per byte instead of 8).

  4. Loggable binary values. Any []byte field (hashes, tokens, raw IDs) becomes a human-readable, URL- and filename-safe string automatically in logs, JSON responses, and etc.

func Str64From added in v1.5.0

func Str64From(s string) (Str64, error)

Str64From decodes a base64 RawURL string back to the original raw bytes.

func (Str64) MarshalText added in v1.4.0

func (s Str64) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (Str64) String added in v1.4.0

func (s Str64) String() string

String encodes the raw bytes to their base64 RawURL text representation.

func (*Str64) UnmarshalText added in v1.4.0

func (s *Str64) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

type URL added in v1.5.0

type URL struct{ url.URL }

URL is a url.URL wrapper that serialises as a plain URL string in all common transports.

Because it implements encoding.TextMarshaler / encoding.TextUnmarshaler, JSON (and any other text-based format) represents the value as a quoted URL string with no extra nesting.

It also implements driver.Valuer and sql.Scanner so it can be stored directly in any SQL column that holds text (VARCHAR, TEXT, etc.), without manual .String() / url.Parse calls at the call site:

type Row struct {
    ID       int
    Callback typx.URL
}

Use Nil[URL] for a nullable SQL column.

func URLFrom added in v1.5.0

func URLFrom(str string) (URL, error)

URLFrom parses str and returns a URL or an error.

func (URL) MarshalText added in v1.5.0

func (u URL) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (*URL) Scan added in v1.5.0

func (u *URL) Scan(src any) error

Scan implements sql.Scanner. Accepts string or []byte from the driver. A nil src (SQL NULL) zeroes the receiver. Use Nil[URL] for a type that can be nil instead of zero.

func (URL) String added in v1.5.0

func (u URL) String() string

String returns the URL in its canonical string form.

func (*URL) UnmarshalText added in v1.5.0

func (u *URL) UnmarshalText(text []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

func (URL) Value added in v1.5.0

func (u URL) Value() (driver.Value, error)

Value implements driver.Valuer. The URL is stored as a plain string in the database.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL