gt

package module
v0.1.24 Latest Latest
Warning

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

Go to latest
Published: Aug 30, 2023 License: Unlicense Imports: 14 Imported by: 0

README

Overview

Short for "Go Types". Important data types missing from the Go standard library. Tiny and dependency-free.

  • NullDate: civil date without time, where zero value is empty/null.
  • NullTime: time where zero value is empty/null.
  • Interval: ISO 8601 duration, corresponds to Postgres interval.
  • NullInterval: interval where zero value is empty/null.
  • Uuid: simple implementation of UUID version 4.
  • NullUuid: UUID where zero value is empty/null.
  • NullInt: int where zero value is empty/null.
  • NullUint: uint where zero value is empty/null.
  • NullFloat: float where zero value is empty/null.
  • NullUrl: actually usable variant of url.URL, used by value rather than pointer, where zero value is empty/null.
  • Ter: nullable boolean (ternary), more usable and efficient than either *bool or sql.NullBool.

API docs: https://pkg.go.dev/github.com/mitranim/gt

Important features:

All types implement all relevant encoding/decoding interfaces for text, JSON, and SQL. Types can be seamlessly used for database fields, JSON fields, and so on, without the need for manual conversions.

All "nullable" gt types are type aliases of "normal" types, where the zero value is considered "null". This eliminates some invalid states at the type system level.

For example, for nullable DB enums, gt.NullString is a better choice than *string or sql.NullString, because it doesn't have the often-invalid state of non-null "". Eliminating invalid states eliminates bugs. Similarly, gt.NullTime is a better choice than time.Time, *time.Time or sql.NullTime. It avoids the hassle of pointers or manual JSON conversions, while preventing your from accidentally inserting 0001-01-01.

License

https://unlicense.org

Misc

I'm receptive to suggestions. If this library almost satisfies you but needs changes, open an issue or chat me up. Contacts: https://mitranim.com/#contacts

Documentation

Index

Constants

View Source
const (
	UuidLen    = 16
	UuidStrLen = UuidLen * 2
)

Variables

This section is empty.

Functions

func Join added in v0.1.14

func Join(src ...string) string

Like `path.Join` but with safeguards. Used internally by `gr.NullUrl.WithPath`, exported because it may be useful separately. Differences from `path.Join`:

  • More efficient if there's only 1 segment.

  • Panics if any segment is "".

  • Panics if any segment begins with ".." or "/..".

Combining segments of a URL path is usually done when building a URL for a request. Accidentally calling the wrong endpoint can have consequences much more annoying than a panic during request building.

func NullTimeLess added in v0.1.19

func NullTimeLess(val ...NullTime) bool

True if the timestamps are ordered like this: A < B < C < .... Also see `gt.NullTimeLessOrEqual` which uses `<=`.

func NullTimeLessOrEqual added in v0.1.19

func NullTimeLessOrEqual(val ...NullTime) bool

True if the timestamps are ordered like this: A <= B <= C <= .... Also see `gt.NullTimeLess` which uses `<`.

func NullTimeOrder added in v0.1.19

func NullTimeOrder(src []NullTime, fun func(NullTime, NullTime) bool) bool

True if the timestamps are ordered in such a way that the given function returns true for each subsequent pair. If the function is nil, returns false. Otherwise, if length is 0 or 1, returns true.

func NullTimeSince

func NullTimeSince(val NullTime) time.Duration

`gt.NullTime` version of `time.Since`.

Types

type AppenderTo added in v0.1.21

type AppenderTo interface{ AppendTo([]byte) []byte }

Implemented by all types in this package, as well as some stdlib types. Appends the default text representation of the receiver to the provided buffer.

type Decodable

Implemented by all types in this package. Various methods for mutating the underlying value by decoding or zeroing. All methods must be implemented on pointer types, rather than value types.

type Encodable

Implemented by all types in this package. Various methods for converting the value to another representation. All methods must be implemented on value types, rather than pointer types.

type Getter

type Getter interface{ Get() any }

Implemented by all types in this package. Returns the underlying value as a "primitive" / "well-known" type, such as `int64`, `string`, `time.Time` depending on the type. All types in this package use `.Get` to implement `sql.Valuer`.

type Interval

type Interval struct {
	Years   int `json:"years"   db:"years"`
	Months  int `json:"months"  db:"months"`
	Days    int `json:"days"    db:"days"`
	Hours   int `json:"hours"   db:"hours"`
	Minutes int `json:"minutes" db:"minutes"`
	Seconds int `json:"seconds" db:"seconds"`
}

Represents an ISO 8601 time interval that has only duration (no timestamps, no range). Supports all six components of ISO 8601 interval: years, months, days, hours, minutes, seconds.

Features:

  • Reversible encoding/decoding in text.
  • Reversible encoding/decoding in JSON.
  • Reversible encoding/decoding in SQL.

Text encoding and decoding uses the standard ISO 8601 format:

P0Y0M0DT0H0M0S

When interacting with a database, to make intervals parsable, configure your DB to always output them in the standard ISO 8601 format.

Limitations:

  • Supports only the standard machine-readable format.
  • Doesn't support decimal fractions.

For a nullable variant, see `gt.NullInterval`.

func DateInterval

func DateInterval(years, months, days int) Interval

Simplified interval constructor without a time constituent.

func DurationInterval

func DurationInterval(src time.Duration) (val Interval)

Uses `.SetDuration` and returns the resulting interval.

func IntervalFrom

func IntervalFrom(years, months, days, hours, mins, secs int) Interval

Simplified interval constructor.

func ParseInterval

func ParseInterval(src string) (val Interval)

Shortcut: parses successfully or panics. Should be used only in root scope. When error handling is relevant, use `.Parse`.

func TimeInterval

func TimeInterval(hours, mins, secs int) Interval

Simplified interval constructor without a date constituent.

func (Interval) Add added in v0.1.6

func (self Interval) Add(val Interval) Interval

Adds every field of one interval to every field of another interval, returning the sum. Does NOT convert different time units, such as seconds to minutes or vice versa.

func (Interval) AddDays added in v0.1.6

func (self Interval) AddDays(val int) Interval

Returns a version of this interval with `.Days += val`.

func (Interval) AddHours added in v0.1.6

func (self Interval) AddHours(val int) Interval

Returns a version of this interval with `.Hours += val`.

func (Interval) AddMinutes added in v0.1.6

func (self Interval) AddMinutes(val int) Interval

Returns a version of this interval with `.Minutes += val`.

func (Interval) AddMonths added in v0.1.6

func (self Interval) AddMonths(val int) Interval

Returns a version of this interval with `.Months += val`.

func (Interval) AddSeconds added in v0.1.6

func (self Interval) AddSeconds(val int) Interval

Returns a version of this interval with `.Seconds += val`.

func (Interval) AddYears added in v0.1.6

func (self Interval) AddYears(val int) Interval

Returns a version of this interval with `.Years += val`.

func (Interval) AppendTo added in v0.1.21

func (self Interval) AppendTo(buf []byte) []byte

Implement `gt.AppenderTo`, using the same representation as `.String`.

func (Interval) Date added in v0.1.10

func (self Interval) Date() (years int, months int, days int)

Returns the date portion of the interval, disregarding the time portion. The result can be passed to `time.Time.AddDate` and `gt.NullTime.AddDate`.

func (Interval) Duration

func (self Interval) Duration() time.Duration

Returns the duration of ONLY the time portion of this interval. Panics if the interval has a date constituent. To make it clear that you're explicitly disregarding the date part, call `.OnlyTime` first. Warning: there are no overflow checks. Usage example:

someInterval.OnlyTime().Duration()

func (Interval) Get

func (self Interval) Get() any

Implement `gt.Getter`, using `.String` to return a string representation.

func (Interval) HasDate

func (self Interval) HasDate() bool

True if the interval has years, months, or days.

func (Interval) HasTime

func (self Interval) HasTime() bool

True if the interval has hours, minutes, or seconds.

func (Interval) IsNull

func (self Interval) IsNull() bool

Implement `gt.Nullable`. Always `false`.

func (Interval) IsZero

func (self Interval) IsZero() bool

Implement `gt.Zeroable`. Equivalent to `reflect.ValueOf(self).IsZero()`.

func (Interval) MarshalJSON

func (self Interval) MarshalJSON() ([]byte, error)

Implement `json.Marshaler`, using the same representation as `.String`.

func (Interval) MarshalText

func (self Interval) MarshalText() ([]byte, error)

Implement `encoding.TextMarhaler`, using the same representation as `.String`.

func (Interval) Neg added in v0.1.6

func (self Interval) Neg() Interval

Returns a version of this interval with every field inverted: positive fields become negative, and negative fields become positive.

func (Interval) OnlyDate added in v0.1.10

func (self Interval) OnlyDate() Interval

Returns only the date portion of this interval, with other fields set to 0.

func (Interval) OnlyTime added in v0.1.10

func (self Interval) OnlyTime() Interval

Returns only the time portion of this interval, with other fields set to 0.

func (*Interval) Parse

func (self *Interval) Parse(src string) error

Implement `gt.Parser`, parsing a valid machine-readable ISO 8601 representation.

func (*Interval) Scan

func (self *Interval) Scan(src any) error

Implement `sql.Scanner`, converting an arbitrary input to `gt.Interval` and modifying the receiver. Acceptable inputs:

  • `string` -> use `.Parse`
  • `[]byte` -> use `.UnmarshalText`
  • `time.Duration` -> use `.SetDuration`
  • `gt.Interval` -> assign
  • `gt.NullInterval` -> assign
  • `gt.Getter` -> scan underlying value

func (*Interval) Set

func (self *Interval) Set(src any)

Implement `gt.Setter`, using `.Scan`. Panics on error.

func (*Interval) SetDuration

func (self *Interval) SetDuration(val time.Duration)

Sets the interval to an approximate value of the given duration, expressed in hours, minutes, seconds, truncating any fractions that don't fit.

func (Interval) String

func (self Interval) String() string

Implement `fmt.Stringer`, returning a text representation in the standard machine-readable ISO 8601 format.

func (Interval) Sub added in v0.1.6

func (self Interval) Sub(val Interval) Interval

Subtracts every field of one interval from every corresponding field of another interval, returning the difference. Does NOT convert different time units, such as seconds to minutes or vice versa.

func (*Interval) UnmarshalJSON

func (self *Interval) UnmarshalJSON(src []byte) error

Implement `json.Unmarshaler`, using the same algorithm as `.Parse`.

func (*Interval) UnmarshalText

func (self *Interval) UnmarshalText(src []byte) error

Implement `encoding.TextUnmarshaler`, using the same algorithm as `.Parse`.

func (Interval) Value

func (self Interval) Value() (driver.Value, error)

Implement `driver.Valuer`, using `.Get`.

func (Interval) WithDays added in v0.1.6

func (self Interval) WithDays(val int) Interval

Returns a version of this interval with `.Days = val`.

func (Interval) WithHours added in v0.1.6

func (self Interval) WithHours(val int) Interval

Returns a version of this interval with `.Hours = val`.

func (Interval) WithMinutes added in v0.1.6

func (self Interval) WithMinutes(val int) Interval

Returns a version of this interval with `.Minutes = val`.

func (Interval) WithMonths added in v0.1.6

func (self Interval) WithMonths(val int) Interval

Returns a version of this interval with `.Months = val`.

func (Interval) WithSeconds added in v0.1.6

func (self Interval) WithSeconds(val int) Interval

Returns a version of this interval with `.Seconds = val`.

func (Interval) WithYears added in v0.1.6

func (self Interval) WithYears(val int) Interval

Returns a version of this interval with `.Years = val`.

func (*Interval) Zero

func (self *Interval) Zero()

Implement `gt.Zeroer`, zeroing the receiver.

type NullDate

type NullDate struct {
	Year  int        `json:"year"  db:"year"`
	Month time.Month `json:"month" db:"month"`
	Day   int        `json:"day"   db:"day"`
}

Civil date without time. Corresponds to SQL type `date` and HTML input with `type="date"`. Zero value is considered empty in text, and null in JSON and SQL. Features:

  • Reversible encoding/decoding in text. Zero value is "".
  • Reversible encoding/decoding in JSON. Zero value is `null`.
  • Reversible encoding/decoding in SQL. Zero value is `null`.
  • Text encoding uses the ISO 8601 extended calendar date format: "0001-02-03".
  • Text decoding supports date-only strings and full RFC3339 timestamps.
  • Convertible to and from `gt.NullTime`.

Caution: `gt.NullDate{}` or `gt.NullDate{0, 0, 0}` is considered empty/null, but when converted to `time.Time` or `gt.NullTime`, it's NOT equivalent to the zero time. The equivalent of zero time is `gt.NullDate{1, 1, 1}`.

func NullDateFrom

func NullDateFrom(year int, month time.Month, day int) NullDate

Shortcut for making a date from a time:

inst := time.Now()
date := gt.NullDateFrom(inst.Date())

Reversible:

date == gt.NullDateFrom(date.Date())

Note that `gt.NullDateFrom(0, 0, 0)` returns a zero value which is considered empty/null, but NOT equivalent to `time.Time{}`. The equivalent of zero time is `gt.NullDateFrom(1, 1, 1)`.

func NullDateNow added in v0.1.11

func NullDateNow() NullDate

Shortcut for `gt.NullTimeNow().NullDate()`.

func ParseNullDate

func ParseNullDate(src string) (val NullDate)

Shortcut: parses successfully or panics. Should be used only in root scope. When error handling is relevant, use `.Parse`.

func (NullDate) AddDate added in v0.1.10

func (self NullDate) AddDate(years int, months int, days int) NullDate

Similar to `time.Time.AddDate`. Returns a modified version of the current value, with the year, month, day deltas added to the corresponding fields. The deltas may be negative. Note that `time.Time` and all time-related types in this package have a convenient `.Date` method that returns this tuple. The calculations are performed for the UTC timezone.

As a special case, because the zero value is considered null, calling this on a zero date ALWAYS returns the same zero date. This matches general SQL semantics of operations involving nulls. Note that the equivalent of zero TIME is not `gt.NullDateFrom(0, 0, 0)`, but rather `gt.NullDateFrom(1, 1, 1)`.

func (NullDate) AppendTo added in v0.1.21

func (self NullDate) AppendTo(buf []byte) []byte

Implement `gt.AppenderTo`, using the same representation as `.String`.

func (NullDate) Date

func (self NullDate) Date() (year int, month time.Month, day int)

Same as `time.Time.Date`. Returns a tuple of the underlying year, month, day.

func (NullDate) Get

func (self NullDate) Get() any

Implement `gt.Getter`. If zero, returns `nil`, otherwise uses `.TimeUTC` to return a timestamp suitable for SQL encoding.

func (NullDate) GoString

func (self NullDate) GoString() string

Implement `fmt.GoStringer`, returning valid Go code that constructs this value.

func (NullDate) IsNull

func (self NullDate) IsNull() bool

Implement `gt.Nullable`. True if zero.

func (NullDate) IsZero

func (self NullDate) IsZero() bool

Implement `gt.Zeroable`. Equivalent to `reflect.ValueOf(self).IsZero()`.

func (NullDate) MarshalJSON

func (self NullDate) MarshalJSON() ([]byte, error)

Implement `json.Marshaler`. If zero, returns bytes representing `null`. Otherwise returns bytes representing a JSON string with the same text as in `.String`.

func (NullDate) MarshalText

func (self NullDate) MarshalText() ([]byte, error)

Implement `encoding.TextMarhaler`. If zero, returns nil. Otherwise returns the same representation as `.String`.

func (NullDate) NullTimeIn

func (self NullDate) NullTimeIn(loc *time.Location) NullTime

Converts to `gt.NullTime` with `T00:00:00` in the provided timezone.

func (NullDate) NullTimeUTC

func (self NullDate) NullTimeUTC() NullTime

Converts to `gt.NullTime` with `T00:00:00` in UTC.

func (*NullDate) Parse

func (self *NullDate) Parse(src string) error

Implement `gt.Parser`. If the input is empty, zeroes the receiver. Otherwise requires an ISO 8601 date representation, one of:

  • Extended calendar date: "2006-01-02"
  • RFC3339 (default Go timestamp format): "2006-01-02T15:04:05Z07:00"

func (*NullDate) Scan

func (self *NullDate) Scan(src any) error

Implement `sql.Scanner`, converting an arbitrary input to `gt.NullDate` and modifying the receiver. Acceptable inputs:

  • `nil` -> use `.Zero`
  • `string` -> use `.Parse`
  • `[]byte` -> use `.UnmarshalText`
  • `time.Time` -> use `.SetTime`
  • `*time.Time` -> use `.Zero` or `.SetTime`
  • `gt.NullTime` -> use `.SetTime`
  • `gt.NullDate` -> assign
  • `gt.Getter` -> scan underlying value

func (*NullDate) Set

func (self *NullDate) Set(src any)

Implement `gt.Setter`, using `.Scan`. Panics on error.

func (*NullDate) SetTime

func (self *NullDate) SetTime(src time.Time)

If the input is zero, zeroes the receiver. Otherwise uses `time.Time.Date` and assigns the resulting year, month, day to the receiver, ignoring smaller constituents such as hour.

func (NullDate) String

func (self NullDate) String() string

Implement `fmt.Stringer`. If zero, returns an empty string. Otherwise returns a text representation in the standard machine-readable ISO 8601 format.

func (NullDate) TimeIn

func (self NullDate) TimeIn(loc *time.Location) time.Time

Converts to `time.Time` with `T00:00:00` in the provided timezone.

func (NullDate) TimeUTC

func (self NullDate) TimeUTC() time.Time

Converts to `time.Time` with `T00:00:00` in UTC.

func (*NullDate) UnmarshalJSON

func (self *NullDate) UnmarshalJSON(src []byte) error

Implement `json.Unmarshaler`. If the input is empty or represents JSON `null`, zeroes the receiver. Otherwise parses a JSON string, using the same algorithm as `.Parse`.

func (*NullDate) UnmarshalText

func (self *NullDate) UnmarshalText(src []byte) error

Implement `encoding.TextUnmarshaler`, using the same algorithm as `.Parse`.

func (NullDate) Value

func (self NullDate) Value() (driver.Value, error)

Implement `driver.Valuer`, using `.Get`.

func (*NullDate) Zero

func (self *NullDate) Zero()

Implement `gt.Zeroer`, zeroing the receiver.

type NullFloat

type NullFloat float64

Variant of `float64` where zero value is considered empty in text, and null in JSON and SQL.

Unlike `float64`, encoding/decoding is not always reversible:

JSON 0 → Go 0 → JSON null
SQL  0 → Go 0 → SQL  null

Also unlike `float64`, this type doesn't use the scientific notation when encoding to a string.

Differences from `"database/sql".NullFloat64`:

  • Much easier to use.
  • Supports text.
  • Supports JSON.
  • Fewer states: zero and null are the same.

Caution: like any floating point number, this should not be used for financial columns. Store money as integers or use a specialized decimal type.

func ParseNullFloat

func ParseNullFloat(src string) (val NullFloat)

Shortcut: parses successfully or panics. Should be used only in root scope. When error handling is relevant, use `.Parse`.

func (NullFloat) AppendTo added in v0.1.21

func (self NullFloat) AppendTo(buf []byte) []byte

Implement `gt.AppenderTo`, using the same representation as `.String`.

func (NullFloat) Float64 added in v0.1.17

func (self NullFloat) Float64() float64

Free cast to the underlying `float64`. Sometimes handy when this type is embedded in a struct.

func (NullFloat) Get

func (self NullFloat) Get() any

Implement `gt.Getter`. If zero, returns `nil`, otherwise returns `float64`.

func (*NullFloat) GetPtr

func (self *NullFloat) GetPtr() any

Implement `gt.PtrGetter`, returning `*float64`.

func (NullFloat) IsNull

func (self NullFloat) IsNull() bool

Implement `gt.Nullable`. True if zero.

func (NullFloat) IsZero

func (self NullFloat) IsZero() bool

Implement `gt.Zeroable`. Equivalent to `reflect.ValueOf(self).IsZero()`.

func (NullFloat) MarshalJSON

func (self NullFloat) MarshalJSON() ([]byte, error)

Implement `json.Marshaler`. If zero, returns bytes representing `null`. Otherwise uses the default `json.Marshal` behavior for `float64`.

func (NullFloat) MarshalText

func (self NullFloat) MarshalText() ([]byte, error)

Implement `encoding.TextMarhaler`. If zero, returns nil. Otherwise returns the same representation as `.String`.

func (*NullFloat) Parse

func (self *NullFloat) Parse(src string) error

Implement `gt.Parser`. If the input is empty, zeroes the receiver. Otherwise parses the input using `strconv.ParseFloat`.

func (*NullFloat) Scan

func (self *NullFloat) Scan(src any) error

Implement `sql.Scanner`, converting an arbitrary input to `gt.NullFloat` and modifying the receiver. Acceptable inputs:

  • `nil` -> use `.Zero`
  • `string` -> use `.Parse`
  • `[]byte` -> use `.UnmarshalText`
  • `intN` -> convert and assign
  • `*intN` -> use `.Zero` or convert and assign
  • `floatN` -> convert and assign
  • `*floatN` -> use `.Zero` or convert and assign
  • `NullFloat` -> assign
  • `gt.Getter` -> scan underlying value

func (*NullFloat) Set

func (self *NullFloat) Set(src any)

Implement `gt.Setter`, using `.Scan`. Panics on error.

func (NullFloat) String

func (self NullFloat) String() string

Implement `fmt.Stringer`. If zero, returns an empty string. Otherwise formats using `strconv.FormatFloat`.

func (*NullFloat) UnmarshalJSON

func (self *NullFloat) UnmarshalJSON(src []byte) error

Implement `json.Unmarshaler`. If the input is empty or represents JSON `null`, zeroes the receiver. Otherwise uses the default `json.Unmarshal` behavior for `*float64`.

func (*NullFloat) UnmarshalText

func (self *NullFloat) UnmarshalText(src []byte) error

Implement `encoding.TextUnmarshaler`, using the same algorithm as `.Parse`.

func (NullFloat) Value

func (self NullFloat) Value() (driver.Value, error)

Implement `driver.Valuer`, using `.Get`.

func (*NullFloat) Zero

func (self *NullFloat) Zero()

Implement `gt.Zeroer`, zeroing the receiver.

type NullInt

type NullInt int64

Variant of `int64` where zero value is considered empty in text, and null in JSON and SQL. Use this for fields where 0 is not allowed, such as primary and foreign keys, or unique bigserials.

Unlike `int64`, encoding/decoding is not always reversible:

JSON 0 → Go 0 → JSON null
SQL  0 → Go 0 → SQL  null

Differences from `"database/sql".NullInt64`:

  • Much easier to use.
  • Supports text.
  • Supports JSON.
  • Fewer states: null and zero are one.

In your data model, numeric fields should be either:

  • Non-nullable; zero value = 0; use `int64`.
  • Nullable; zero value = `null`; 0 is not allowed; use `gt.NullInt`.

Avoid `*intN` or `sql.NullIntN`.

func ParseNullInt

func ParseNullInt(src string) (val NullInt)

Shortcut: parses successfully or panics. Should be used only in root scope. When error handling is relevant, use `.Parse`.

func (NullInt) AppendTo added in v0.1.21

func (self NullInt) AppendTo(buf []byte) []byte

Implement `gt.AppenderTo`, using the same representation as `.String`.

func (NullInt) Get

func (self NullInt) Get() any

Implement `gt.Getter`. If zero, returns `nil`, otherwise returns `int64`.

func (*NullInt) GetPtr

func (self *NullInt) GetPtr() any

Implement `gt.PtrGetter`, returning `*int64`.

func (NullInt) Int64 added in v0.1.16

func (self NullInt) Int64() int64

Free cast to the underlying `int64`. Sometimes handy when this type is embedded in a struct.

func (NullInt) IsNull

func (self NullInt) IsNull() bool

Implement `gt.Nullable`. True if zero.

func (NullInt) IsZero

func (self NullInt) IsZero() bool

Implement `gt.Zeroable`. Equivalent to `reflect.ValueOf(self).IsZero()`.

func (NullInt) MarshalJSON

func (self NullInt) MarshalJSON() ([]byte, error)

Implement `json.Marshaler`. If zero, returns bytes representing `null`. Otherwise uses the default `json.Marshal` behavior for `int64`.

func (NullInt) MarshalText

func (self NullInt) MarshalText() ([]byte, error)

Implement `encoding.TextMarhaler`. If zero, returns nil. Otherwise returns the same representation as `.String`.

func (*NullInt) Parse

func (self *NullInt) Parse(src string) error

Implement `gt.Parser`. If the input is empty, zeroes the receiver. Otherwise parses the input using `strconv.ParseInt`.

func (*NullInt) Scan

func (self *NullInt) Scan(src any) error

Implement `sql.Scanner`, converting an arbitrary input to `gt.NullInt` and modifying the receiver. Acceptable inputs:

  • `nil` -> use `.Zero`
  • `string` -> use `.Parse`
  • `[]byte` -> use `.UnmarshalText`
  • `intN` -> convert and assign
  • `*intN` -> use `.Zero` or convert and assign
  • `NullInt` -> assign
  • `gt.Getter` -> scan underlying value

TODO also support uints.

func (*NullInt) Set

func (self *NullInt) Set(src any)

Implement `gt.Setter`, using `.Scan`. Panics on error.

func (NullInt) String

func (self NullInt) String() string

Implement `fmt.Stringer`. If zero, returns an empty string. Otherwise formats using `strconv.FormatInt`.

func (*NullInt) UnmarshalJSON

func (self *NullInt) UnmarshalJSON(src []byte) error

Implement `json.Unmarshaler`. If the input is empty or represents JSON `null`, zeroes the receiver. Otherwise uses the default `json.Unmarshal` behavior for `*int64`.

func (*NullInt) UnmarshalText

func (self *NullInt) UnmarshalText(src []byte) error

Implement `encoding.TextUnmarshaler`, using the same algorithm as `.Parse`.

func (NullInt) Value

func (self NullInt) Value() (driver.Value, error)

Implement `driver.Valuer`, using `.Get`.

func (*NullInt) Zero

func (self *NullInt) Zero()

Implement `gt.Zeroer`, zeroing the receiver.

type NullInterval

type NullInterval Interval

Variant of `gt.Interval` where zero value is considered empty in text, and null in JSON and SQL.

func DateNullInterval

func DateNullInterval(years int, months int, days int) NullInterval

Simplified interval constructor without a time constituent.

func DurationNullInterval

func DurationNullInterval(src time.Duration) (val NullInterval)

Uses `.SetDuration` and returns the resulting interval.

func NullIntervalFrom

func NullIntervalFrom(years int, months int, days, hours, mins, secs int) NullInterval

Simplified interval constructor.

func ParseNullInterval

func ParseNullInterval(src string) (val NullInterval)

Shortcut: parses successfully or panics. Should be used only in root scope. When error handling is relevant, use `.Parse`.

func TimeNullInterval

func TimeNullInterval(hours, mins, secs int) NullInterval

Simplified interval constructor without a date constituent.

func (NullInterval) Add added in v0.1.6

func (self NullInterval) Add(val NullInterval) NullInterval

Adds every field of one interval to every field of another interval, returning the sum. Does NOT convert different time units, such as seconds to minutes or vice versa.

func (NullInterval) AddDays added in v0.1.6

func (self NullInterval) AddDays(val int) NullInterval

Returns a version of this interval with `.Days += val`.

func (NullInterval) AddHours added in v0.1.6

func (self NullInterval) AddHours(val int) NullInterval

Returns a version of this interval with `.Hours += val`.

func (NullInterval) AddMinutes added in v0.1.6

func (self NullInterval) AddMinutes(val int) NullInterval

Returns a version of this interval with `.Minutes += val`.

func (NullInterval) AddMonths added in v0.1.6

func (self NullInterval) AddMonths(val int) NullInterval

Returns a version of this interval with `.Months += val`.

func (NullInterval) AddSeconds added in v0.1.6

func (self NullInterval) AddSeconds(val int) NullInterval

Returns a version of this interval with `.Seconds += val`.

func (NullInterval) AddYears added in v0.1.6

func (self NullInterval) AddYears(val int) NullInterval

Returns a version of this interval with `.Years += val`.

func (NullInterval) AppendTo added in v0.1.21

func (self NullInterval) AppendTo(buf []byte) []byte

Implement `gt.AppenderTo`, using the same representation as `.String`.

func (NullInterval) Date added in v0.1.10

func (self NullInterval) Date() (years int, months int, days int)

Same as `gt.Interval.Date`.

func (NullInterval) Duration added in v0.1.10

func (self NullInterval) Duration() time.Duration

Same as `gt.Interval.Duration`.

func (NullInterval) Get

func (self NullInterval) Get() any

Implement `gt.Getter`. If zero, returns `nil`, otherwise uses `.String` to return a string representation.

func (NullInterval) HasDate

func (self NullInterval) HasDate() bool

Same as `gt.Interval.HasDate`.

func (NullInterval) HasTime

func (self NullInterval) HasTime() bool

Same as `gt.Interval.HasTime`.

func (NullInterval) IsNull

func (self NullInterval) IsNull() bool

Implement `gt.Nullable`. True if zero.

func (NullInterval) IsZero

func (self NullInterval) IsZero() bool

Implement `gt.Zeroable`. Equivalent to `reflect.ValueOf(self).IsZero()`.

func (NullInterval) MarshalJSON

func (self NullInterval) MarshalJSON() ([]byte, error)

Implement `json.Marshaler`. If zero, returns bytes representing `null`. Otherwise returns bytes representing a JSON string with the same text as in `.String`.

func (NullInterval) MarshalText

func (self NullInterval) MarshalText() ([]byte, error)

Implement `encoding.TextMarhaler`. If zero, returns nil. Otherwise returns the same representation as `.String`.

func (NullInterval) Neg added in v0.1.6

func (self NullInterval) Neg() NullInterval

Returns a version of this interval with every field inverted: positive fields become negative, and negative fields become positive.

func (NullInterval) OnlyDate added in v0.1.10

func (self NullInterval) OnlyDate() NullInterval

Same as `gt.Interval.OnlyDate`.

func (NullInterval) OnlyTime added in v0.1.10

func (self NullInterval) OnlyTime() NullInterval

Same as `gt.Interval.OnlyTime`.

func (*NullInterval) Parse

func (self *NullInterval) Parse(src string) error

Implement `gt.Parser`. If the input is empty, zeroes the receiver. Otherwise requires a valid machine-readable ISO 8601 representation.

func (*NullInterval) Scan

func (self *NullInterval) Scan(src any) error

Implement `sql.Scanner`, converting an arbitrary input to `gt.NullInterval` and modifying the receiver. Acceptable inputs:

  • `nil` -> use `.Zero`
  • `string` -> use `.Parse`
  • `[]byte` -> use `.UnmarshalText`
  • `time.Duration` -> use `.SetDuration`
  • `*time.Duration` -> use `.Zero` or `.SetDuration`
  • `gt.Interval` -> assign
  • `*gt.Interval` -> use `.Zero` or assign
  • `gt.NullInterval` -> assign
  • `gt.Getter` -> scan underlying value

func (*NullInterval) Set

func (self *NullInterval) Set(src any)

Implement `gt.Setter`, using `.Scan`. Panics on error.

func (*NullInterval) SetDuration

func (self *NullInterval) SetDuration(val time.Duration)

Same as `(*gt.Interval).SetDuration`.

func (NullInterval) String

func (self NullInterval) String() string

Implement `fmt.Stringer`. If zero, returns an empty string. Otherwise returns a text representation in the standard machine-readable ISO 8601 format.

func (NullInterval) Sub added in v0.1.6

func (self NullInterval) Sub(val NullInterval) NullInterval

Subtracts every field of one interval from every corresponding field of another interval, returning the difference. Does NOT convert different time units, such as seconds to minutes or vice versa.

func (*NullInterval) UnmarshalJSON

func (self *NullInterval) UnmarshalJSON(src []byte) error

Implement `json.Unmarshaler`. If the input is empty or represents JSON `null`, zeroes the receiver. Otherwise parses a JSON string, using the same algorithm as `.Parse`.

func (*NullInterval) UnmarshalText

func (self *NullInterval) UnmarshalText(src []byte) error

Implement `encoding.TextUnmarshaler`, using the same algorithm as `.Parse`.

func (NullInterval) Value

func (self NullInterval) Value() (driver.Value, error)

Implement `driver.Valuer`, using `.Get`.

func (NullInterval) WithDays added in v0.1.6

func (self NullInterval) WithDays(val int) NullInterval

Returns a version of this interval with `.Days = val`.

func (NullInterval) WithHours added in v0.1.6

func (self NullInterval) WithHours(val int) NullInterval

Returns a version of this interval with `.Hours = val`.

func (NullInterval) WithMinutes added in v0.1.6

func (self NullInterval) WithMinutes(val int) NullInterval

Returns a version of this interval with `.Minutes = val`.

func (NullInterval) WithMonths added in v0.1.6

func (self NullInterval) WithMonths(val int) NullInterval

Returns a version of this interval with `.Months = val`.

func (NullInterval) WithSeconds added in v0.1.6

func (self NullInterval) WithSeconds(val int) NullInterval

Returns a version of this interval with `.Seconds = val`.

func (NullInterval) WithYears added in v0.1.6

func (self NullInterval) WithYears(val int) NullInterval

Returns a version of this interval with `.Years = val`.

func (*NullInterval) Zero

func (self *NullInterval) Zero()

Implement `gt.Zeroer`, zeroing the receiver.

type NullString

type NullString string

Variant of `string` where zero value is considered empty in text, and null in JSON and SQL. Use this for fields where an empty string is not allowed, such as enums or text foreign keys.

Unlike `string`, encoding/decoding is not always reversible:

JSON "" → Go "" → JSON null
SQL  '' → Go "" → SQL  null

Differences from `"database/sql".NullString`:

  • Much easier to use.
  • Supports text.
  • Supports JSON.
  • Fewer states: null and empty string are one.

In your data model, text fields should be either:

  • Non-nullable, zero value = empty string -> use `string`.
  • Nullable, zero value = `null`, empty string is not allowed -> use `gt.NullString`.

Avoid `*string` or `sql.NullString`.

func (NullString) AppendTo added in v0.1.21

func (self NullString) AppendTo(buf []byte) []byte

Implement `gt.AppenderTo`, appending the string as-is.

func (NullString) Get

func (self NullString) Get() any

Implement `gt.Getter`. If zero, returns `nil`, otherwise returns `string`.

func (*NullString) GetPtr

func (self *NullString) GetPtr() any

Implement `gt.PtrGetter`, returning `*string`.

func (NullString) IsNull

func (self NullString) IsNull() bool

Implement `gt.Nullable`. True if zero.

func (NullString) IsZero

func (self NullString) IsZero() bool

Implement `gt.Zeroable`. Equivalent to `reflect.ValueOf(self).IsZero()`.

func (NullString) Len added in v0.1.12

func (self NullString) Len() int

Same as `len(self)`. Sometimes handy when embedding `gt.NullString` in single-field structs.

func (NullString) MarshalJSON

func (self NullString) MarshalJSON() ([]byte, error)

Implement `json.Marshaler`. If zero, returns bytes representing `null`. Otherwise uses the default `json.Marshal` behavior for `string`.

func (NullString) MarshalText

func (self NullString) MarshalText() ([]byte, error)

Implement `encoding.TextMarhaler`. If zero, returns nil. Otherwise returns the string as-is.

func (*NullString) Parse

func (self *NullString) Parse(src string) error

Implement `gt.Parser`, assigning the string as-is.

func (*NullString) Scan

func (self *NullString) Scan(src any) error

Implement `sql.Scanner`, converting an arbitrary input to `gt.NullString` and modifying the receiver. Acceptable inputs:

  • `nil` -> use `.Zero`
  • `string` -> use `.Parse`
  • `[]byte` -> use `.UnmarshalText`
  • `NullString` -> assign
  • `gt.Getter` -> scan underlying value

func (*NullString) Set

func (self *NullString) Set(src any)

Implement `gt.Setter`, using `.Scan`. Panics on error.

func (NullString) String

func (self NullString) String() string

Implement `fmt.Stringer`, returning the string as-is.

func (*NullString) UnmarshalJSON

func (self *NullString) UnmarshalJSON(src []byte) error

Implement `json.Unmarshaler`. If the input is empty or represents JSON `null`, zeroes the receiver. Otherwise uses the default `json.Unmarshal` behavior for `*string`.

func (*NullString) UnmarshalText

func (self *NullString) UnmarshalText(src []byte) error

Implement `encoding.TextUnmarshaler`, assigning the string as-is.

func (NullString) Value

func (self NullString) Value() (driver.Value, error)

Implement `driver.Valuer`, using `.Get`.

func (*NullString) Zero

func (self *NullString) Zero()

Implement `gt.Zeroer`, zeroing the receiver.

type NullTime

type NullTime time.Time

Variant of `time.Time` where zero value is considered empty in text, and null in JSON and SQL. Prevents you from accidentally inserting nonsense times like 0001-01-01 or 1970-01-01 into date/time columns, without the hassle of pointers such as `*time.Time` or unusable types such as `sql.NullTime`.

Differences from `time.Time`:

  • Zero value is "" in text.
  • Zero value is `null` in JSON.
  • Zero value is `null` in SQL.
  • Default text encoding is RFC3339.
  • Text encoding/decoding is automatically reversible.

Differences from `"database/sql".NullTime`:

  • Much easier to use.
  • Supports text; zero value is "".
  • Supports JSON; zero value is `null`.
  • Fewer states: null and zero are one.

In your data model, `time.Time` is often the wrong choice, because the zero value of `time.Time` is considered "non-empty". It leads to accidentally inserting junk data. `*time.Time` is a better choice, but it introduces nil pointer hazards without eliminating the invalid state `&time.Time{}`. `sql.NullTime` is unusable due to lack of support for text and JSON encoding. `gt.NullTime` avoids all of those issues.

For civil dates without time, use `gt.NullDate`.

func ClockNullTime added in v0.1.17

func ClockNullTime(hour, min, sec int) NullTime

Creates a UTC timestamp with the given time of day for the first day of the Gregorian calendar.

func NullDateIn

func NullDateIn(year int, month time.Month, day int, loc *time.Location) NullTime

Shortcut for `gt.NullTimeIn` with `T00:00:00`.

func NullDateUTC

func NullDateUTC(year int, month time.Month, day int) NullTime

Shortcut for `gt.NullDateIn` in UTC.

Note: due to peculiarities of civil time, `gt.NullDateUTC(1, 1, 1)` returns a zero value, while `gt.NullDateUTC(0, 0, 0)` returns a "negative" time.

func NullTimeIn

func NullTimeIn(year int, month time.Month, day, hour, min, sec, nsec int, loc *time.Location) NullTime

`gt.NullTime` version of `time.Date`.

func NullTimeNow

func NullTimeNow() NullTime

`gt.NullTime` version of `time.Now`.

func NullTimeUTC

func NullTimeUTC(year int, month time.Month, day, hour, min, sec, nsec int) NullTime

Shortcut for `gt.NullTimeIn` in UTC.

Note: due to peculiarities of civil time, `gt.NullTimeUTC(1, 1, 1, 0, 0, 0, 0)` returns a zero value, while `gt.NullTimeUTC(0, 0, 0, 0, 0, 0, 0)` returns a "negative" time.

func ParseNullTime

func ParseNullTime(src string) (val NullTime)

Shortcut: parses successfully or panics. Should be used only in root scope. When error handling is relevant, use `.Parse`.

func (NullTime) Add

func (self NullTime) Add(val time.Duration) NullTime

`gt.NullTime` version of `time.Time.Add`.

func (NullTime) AddDate

func (self NullTime) AddDate(y, m, d int) NullTime

`gt.NullTime` version of `time.Time.AddDate`.

func (NullTime) AddInterval added in v0.1.10

func (self NullTime) AddInterval(val Interval) NullTime

Adds the interval to the time, returning the modified time. If the interval is a zero value, the resulting time should be identical to the source.

func (NullTime) AddNullInterval added in v0.1.10

func (self NullTime) AddNullInterval(val NullInterval) NullTime

Same as `gt.NullTime.AddInterval` but for `gt.NullInterval`.

func (NullTime) After

func (self NullTime) After(val NullTime) bool

Same as `time.Time.After`.

func (NullTime) AppendFormat

func (self NullTime) AppendFormat(a []byte, b string) []byte

`gt.NullTime` version of `time.Time.AppendFormat`.

func (NullTime) AppendTo added in v0.1.21

func (self NullTime) AppendTo(buf []byte) []byte

Implement `gt.AppenderTo`, using the same representation as `.String`.

func (NullTime) Before

func (self NullTime) Before(val NullTime) bool

Same as `time.Time.Before`.

func (NullTime) Clock

func (self NullTime) Clock() (int, int, int)

`gt.NullTime` version of `time.Time.Clock`.

func (NullTime) Date

func (self NullTime) Date() (int, time.Month, int)

`gt.NullTime` version of `time.Time.Date`.

func (NullTime) Day

func (self NullTime) Day() int

`gt.NullTime` version of `time.Time.Day`.

func (NullTime) Equal

func (self NullTime) Equal(val NullTime) bool

`gt.NullTime` version of `time.Time.Equal`.

func (NullTime) Format

func (self NullTime) Format(layout string) string

`gt.NullTime` version of `time.Time.Format`.

func (NullTime) Get

func (self NullTime) Get() any

Implement `gt.Getter`. If zero, returns `nil`, otherwise returns `time.Time`.

func (*NullTime) GetPtr

func (self *NullTime) GetPtr() any

Implement `gt.PtrGetter`, returning `*time.Time`.

func (NullTime) GoString

func (self NullTime) GoString() string

Implement `fmt.GoStringer`, returning Go code that constructs this value. For UTC, the resulting code is valid. For non-UTC, the resulting code is invalid, because `*time.Location` doesn't implement `fmt.GoStringer`.

func (NullTime) Hour

func (self NullTime) Hour() int

`gt.NullTime` version of `time.Time.Hour`.

func (NullTime) ISOWeek

func (self NullTime) ISOWeek() (int, int)

`gt.NullTime` version of `time.Time.ISOWeek`.

func (NullTime) In

func (self NullTime) In(loc *time.Location) NullTime

`gt.NullTime` version of `time.Time.In`.

func (NullTime) IsDST

func (self NullTime) IsDST() bool

`gt.NullTime` version of `time.Time.IsDST`.

func (NullTime) IsNull

func (self NullTime) IsNull() bool

Implement `gt.Nullable`. True if zero.

func (NullTime) IsZero

func (self NullTime) IsZero() bool

Implement `gt.Zeroable`. Same as `self.Time().IsZero()`. Unlike most implementations of `gt.Zeroable` in this package, this is NOT equivalent to `reflect.ValueOf(self).IsZero()`, but rather a superset of it.

func (NullTime) Less added in v0.1.19

func (self NullTime) Less(val NullTime) bool

Alias for `time.Time.Before`. Also see `gt.NullTime.Before` which is variadic.

func (NullTime) LessOrEqual added in v0.1.19

func (self NullTime) LessOrEqual(val NullTime) bool

Equivalent to `self.Equal(val) || self.Less(val)`.

func (NullTime) Local

func (self NullTime) Local() NullTime

`gt.NullTime` version of `time.Time.Local`.

func (NullTime) Location

func (self NullTime) Location() *time.Location

`gt.NullTime` version of `time.Time.Location`.

func (NullTime) MarshalJSON

func (self NullTime) MarshalJSON() ([]byte, error)

Implement `json.Marshaler`. If zero, returns bytes representing `null`. Otherwise uses the default `json.Marshal` behavior for `time.Time`.

func (NullTime) MarshalText

func (self NullTime) MarshalText() ([]byte, error)

Implement `encoding.TextMarhaler`. If zero, returns nil. Otherwise returns the same representation as `.String`.

func (NullTime) MaybeTime

func (self NullTime) MaybeTime() *time.Time

If zero, returns nil. Otherwise returns a non-nil `*time.Time`.

func (NullTime) Minute

func (self NullTime) Minute() int

`gt.NullTime` version of `time.Time.Minute`.

func (NullTime) Month

func (self NullTime) Month() time.Month

`gt.NullTime` version of `time.Time.Month`.

func (NullTime) Nanosecond

func (self NullTime) Nanosecond() int

`gt.NullTime` version of `time.Time.Nanosecond`.

func (NullTime) NullDate added in v0.1.11

func (self NullTime) NullDate() NullDate

Shortcut for `gt.NullDateFrom(self.Date())`.

func (*NullTime) Parse

func (self *NullTime) Parse(src string) error

Implement `gt.Parser`. If the input is empty, zeroes the receiver. Otherwise requires either an RFC3339 timestamp (default time parsing format in Go), or a numeric timestamp in milliseconds.

func (NullTime) Round

func (self NullTime) Round(val time.Duration) NullTime

`gt.NullTime` version of `time.Time.Round`.

func (*NullTime) Scan

func (self *NullTime) Scan(src any) error

Implement `sql.Scanner`, converting an arbitrary input to `gt.NullTime` and modifying the receiver. Acceptable inputs:

  • `nil` -> use `.Zero`
  • `string` -> use `.Parse`
  • `[]byte` -> use `.UnmarshalText`
  • `time.Time` -> assign
  • `*time.Time` -> use `.Zero` or assign
  • `gt.NullTime` -> assign
  • `gt.NullDate` -> assume UTC, convert, assign
  • `gt.Getter` -> scan underlying value

func (NullTime) Second

func (self NullTime) Second() int

`gt.NullTime` version of `time.Time.Second`.

func (*NullTime) Set

func (self *NullTime) Set(src any)

Implement `gt.Setter`, using `.Scan`. Panics on error.

func (NullTime) String

func (self NullTime) String() string

Implement `fmt.Stringer`. If zero, returns an empty string. Otherwise returns a text representation in the RFC3339 format.

func (NullTime) Sub

func (self NullTime) Sub(val NullTime) time.Duration

`gt.NullTime` version of `time.Time.Sub`.

func (NullTime) SubInterval added in v0.1.23

func (self NullTime) SubInterval(val Interval) NullTime

Subtracts the given interval, returning the modified time. Inverse of `NullTime.AddInterval`.

func (NullTime) SubNullInterval added in v0.1.23

func (self NullTime) SubNullInterval(val NullInterval) NullTime

Same as `gt.NullTime.SubInterval` but for `gt.NullInterval`.

func (NullTime) Time

func (self NullTime) Time() time.Time

Free cast to `time.Time`.

func (*NullTime) TimePtr

func (self *NullTime) TimePtr() *time.Time

Free cast to `*time.Time`.

func (NullTime) Truncate

func (self NullTime) Truncate(val time.Duration) NullTime

`gt.NullTime` version of `time.Time.Truncate`.

func (NullTime) UTC

func (self NullTime) UTC() NullTime

`gt.NullTime` version of `time.Time.UTC`.

func (NullTime) Unix

func (self NullTime) Unix() int64

`gt.NullTime` version of `time.Time.Unix`.

func (NullTime) UnixMicro

func (self NullTime) UnixMicro() int64

`gt.NullTime` version of `time.Time.UnixMicro`.

func (NullTime) UnixMilli

func (self NullTime) UnixMilli() int64

`gt.NullTime` version of `time.Time.UnixMilli`.

func (NullTime) UnixNano

func (self NullTime) UnixNano() int64

`gt.NullTime` version of `time.Time.UnixNano`.

func (*NullTime) UnmarshalJSON

func (self *NullTime) UnmarshalJSON(src []byte) error

Implement `json.Unmarshaler`. If the input is empty or represents JSON `null`, zeroes the receiver. Otherwise uses the default `json.Unmarshal` behavior for `*time.Time`.

func (*NullTime) UnmarshalText

func (self *NullTime) UnmarshalText(src []byte) error

Implement `encoding.TextUnmarshaler`, using the same algorithm as `.Parse`.

func (NullTime) Value

func (self NullTime) Value() (driver.Value, error)

Implement `driver.Valuer`, using `.Get`.

func (NullTime) Weekday

func (self NullTime) Weekday() time.Weekday

`gt.NullTime` version of `time.Time.Weekday`.

func (NullTime) Year

func (self NullTime) Year() int

`gt.NullTime` version of `time.Time.Year`.

func (NullTime) YearDay

func (self NullTime) YearDay() int

`gt.NullTime` version of `time.Time.YearDay`.

func (*NullTime) Zero

func (self *NullTime) Zero()

Implement `gt.Zeroer`, zeroing the receiver.

func (NullTime) Zone

func (self NullTime) Zone() (string, int)

`gt.NullTime` version of `time.Time.Zone`.

type NullUint

type NullUint uint64

Variant of `uint64` where zero value is considered empty in text, and null in JSON and SQL. Use this for fields where 0 is not allowed, such as primary and foreign keys, or unique bigserials.

Unlike `uint64`, encoding/decoding is not always reversible:

JSON 0 → Go 0 → JSON null
SQL  0 → Go 0 → SQL  null

In your data model, positive numeric fields should be either:

  • Non-nullable; zero value = 0; use `uint64`.
  • Nullable; zero value = `null`; 0 is not allowed; use `gt.NullUint`.

Avoid `*uintN`.

func ParseNullUint

func ParseNullUint(src string) (val NullUint)

Shortcut: parses successfully or panics. Should be used only in root scope. When error handling is relevant, use `.Parse`.

func (NullUint) AppendTo added in v0.1.21

func (self NullUint) AppendTo(buf []byte) []byte

Implement `gt.AppenderTo`, using the same representation as `.String`.

func (NullUint) Get

func (self NullUint) Get() any

Implement `gt.Getter`. If zero, returns `nil`, otherwise returns `uint64`.

func (*NullUint) GetPtr

func (self *NullUint) GetPtr() any

Implement `gt.PtrGetter`, returning `*uint64`.

func (NullUint) IsNull

func (self NullUint) IsNull() bool

Implement `gt.Nullable`. True if zero.

func (NullUint) IsZero

func (self NullUint) IsZero() bool

Implement `gt.Zeroable`. Equivalent to `reflect.ValueOf(self).IsZero()`.

func (NullUint) MarshalJSON

func (self NullUint) MarshalJSON() ([]byte, error)

Implement `json.Marshaler`. If zero, returns bytes representing `null`. Otherwise uses the default `json.Marshal` behavior for `uint64`.

func (NullUint) MarshalText

func (self NullUint) MarshalText() ([]byte, error)

Implement `encoding.TextMarhaler`. If zero, returns nil. Otherwise returns the same representation as `.String`.

func (*NullUint) Parse

func (self *NullUint) Parse(src string) error

Implement `gt.Parser`. If the input is empty, zeroes the receiver. Otherwise parses the input using `strconv.ParseUint`.

func (*NullUint) Scan

func (self *NullUint) Scan(src any) error

Implement `sql.Scanner`, converting an arbitrary input to `gt.NullUint` and modifying the receiver. Acceptable inputs:

  • `nil` -> use `.Zero`
  • `string` -> use `.Parse`
  • `[]byte` -> use `.UnmarshalText`
  • `uintN` -> convert and assign
  • `*uintN` -> use `.Zero` or convert and assign
  • `NullUint` -> assign
  • `gt.Getter` -> scan underlying value

TODO also support signed ints.

func (*NullUint) Set

func (self *NullUint) Set(src any)

Implement `gt.Setter`, using `.Scan`. Panics on error.

func (NullUint) String

func (self NullUint) String() string

Implement `fmt.Stringer`. If zero, returns an empty string. Otherwise formats using `strconv.FormatUint`.

func (NullUint) Uint64 added in v0.1.16

func (self NullUint) Uint64() uint64

Free cast to the underlying `uint64`. Sometimes handy when this type is embedded in a struct.

func (*NullUint) UnmarshalJSON

func (self *NullUint) UnmarshalJSON(src []byte) error

Implement `json.Unmarshaler`. If the input is empty or represents JSON `null`, zeroes the receiver. Otherwise uses the default `json.Unmarshal` behavior for `*uint64`.

func (*NullUint) UnmarshalText

func (self *NullUint) UnmarshalText(src []byte) error

Implement `encoding.TextUnmarshaler`, using the same algorithm as `.Parse`.

func (NullUint) Value

func (self NullUint) Value() (driver.Value, error)

Implement `driver.Valuer`, using `.Get`.

func (*NullUint) Zero

func (self *NullUint) Zero()

Implement `gt.Zeroer`, zeroing the receiver.

type NullUrl added in v0.1.3

type NullUrl url.URL

Variant of `*url.URL` with a less-atrocious API. Differences from `*url.URL`:

  • Used by value, not by pointer.
  • Full support for text, JSON, SQL encoding/decoding.
  • Zero value is considered empty in text, and null in JSON and SQL.
  • Easier to use.
  • Fewer invalid states.

func ParseNullUrl added in v0.1.3

func ParseNullUrl(src string) (val NullUrl)

Shortcut: parses successfully or panics. Should be used only in root scope. When error handling is relevant, use `.Parse`.

func ToNullUrl added in v0.1.3

func ToNullUrl(src *url.URL) (val NullUrl)

Safe cast. Like `gt.NullUrl(*src)` but doesn't panic on nil pointer.

func (NullUrl) AddPath added in v0.1.20

func (self NullUrl) AddPath(src ...string) NullUrl

Returns a modified variant where `.Path` is replaced by combining the existing path with the segments via `gt.Join`. See the docs on `gt.Join`. Also see `.WithPath` that replaces the path instead of appending.

func (NullUrl) AppendTo added in v0.1.21

func (self NullUrl) AppendTo(buf []byte) []byte

Implement `gt.AppenderTo`, using the same representation as `.String`.

func (NullUrl) EscapedFragment added in v0.1.3

func (self NullUrl) EscapedFragment() string

`gt.NullUrl` version of `(*url.URL).EscapedFragment`.

func (NullUrl) EscapedPath added in v0.1.3

func (self NullUrl) EscapedPath() string

`gt.NullUrl` version of `(*url.URL).EscapedPath`.

func (NullUrl) Get added in v0.1.3

func (self NullUrl) Get() any

Implement `gt.Getter`. If zero, returns `nil`, otherwise uses `.String` to return a string representation.

func (*NullUrl) GetPtr added in v0.1.3

func (self *NullUrl) GetPtr() any

Implement `gt.PtrGetter`, returning `*url.URL`.

func (NullUrl) GoString added in v0.1.3

func (self NullUrl) GoString() string

Implement `fmt.GoStringer`, returning valid Go code that constructs this value.

func (NullUrl) Hostname added in v0.1.3

func (self NullUrl) Hostname() string

`gt.NullUrl` version of `(*url.URL).Hostname`.

func (NullUrl) IsAbs added in v0.1.3

func (self NullUrl) IsAbs() bool

`gt.NullUrl` version of `(*url.URL).IsAbs`.

func (NullUrl) IsNull added in v0.1.3

func (self NullUrl) IsNull() bool

Implement `gt.Nullable`. True if zero.

func (NullUrl) IsZero added in v0.1.3

func (self NullUrl) IsZero() bool

Implement `gt.Zeroable`. Equivalent to `reflect.ValueOf(self).IsZero()`.

func (NullUrl) MarshalJSON added in v0.1.3

func (self NullUrl) MarshalJSON() ([]byte, error)

Implement `json.Marshaler`. If zero, returns bytes representing `null`. Otherwise returns bytes representing a JSON string with the same text as in `.String`.

func (NullUrl) MarshalText added in v0.1.3

func (self NullUrl) MarshalText() ([]byte, error)

Implement `encoding.TextMarhaler`. If zero, returns nil. Otherwise returns the same representation as `.String`.

func (NullUrl) Maybe added in v0.1.14

func (self NullUrl) Maybe() *url.URL

If zero, returns nil. Otherwise returns a non-nil `*url.URL`.

func (*NullUrl) Parse added in v0.1.3

func (self *NullUrl) Parse(src string) error

Implement `gt.Parser`. If the input is empty, zeroes the receiver. Otherwise parses the input using `url.Parse`.

func (NullUrl) ParseIn added in v0.1.3

func (self NullUrl) ParseIn(ref string) (NullUrl, error)

`gt.NullUrl` version of `(*url.URL).Parse`.

func (NullUrl) Port added in v0.1.3

func (self NullUrl) Port() string

`gt.NullUrl` version of `(*url.URL).Port`.

func (NullUrl) Query added in v0.1.3

func (self NullUrl) Query() url.Values

`gt.NullUrl` version of `(*url.URL).Query`.

func (NullUrl) Redacted added in v0.1.3

func (self NullUrl) Redacted() string

`gt.NullUrl` version of `(*url.URL).Redacted`.

func (NullUrl) RequestURI added in v0.1.3

func (self NullUrl) RequestURI() string

`gt.NullUrl` version of `(*url.URL).RequestURI`.

func (NullUrl) ResolveReference added in v0.1.3

func (self NullUrl) ResolveReference(ref NullUrl) NullUrl

`gt.NullUrl` version of `(*url.URL).ResolveReference`.

func (*NullUrl) Scan added in v0.1.3

func (self *NullUrl) Scan(src any) error

Implement `sql.Scanner`, converting an arbitrary input to `gt.NullUrl` and modifying the receiver. Acceptable inputs:

  • `nil` -> use `.Zero`
  • `string` -> use `.Parse`
  • `[]byte` -> use `.UnmarshalText`
  • `url.URL` -> convert and assign
  • `*url.URL` -> use `.Zero` or convert and assign
  • `NullUrl` -> assign
  • `gt.Getter` -> scan underlying value

func (*NullUrl) Set added in v0.1.3

func (self *NullUrl) Set(src any)

Implement `gt.Setter`, using `.Scan`. Panics on error.

func (NullUrl) String added in v0.1.3

func (self NullUrl) String() string

Implement `fmt.Stringer`. If zero, returns an empty string. Otherwise formats using `(*url.URL).String`.

func (*NullUrl) UnmarshalJSON added in v0.1.3

func (self *NullUrl) UnmarshalJSON(src []byte) error

Implement `json.Unmarshaler`. If the input is empty or represents JSON `null`, zeroes the receiver. Otherwise parses a JSON string, using the same algorithm as `.Parse`.

func (*NullUrl) UnmarshalText added in v0.1.3

func (self *NullUrl) UnmarshalText(src []byte) error

Implement `encoding.TextUnmarshaler`, using the same algorithm as `.Parse`.

func (NullUrl) Url added in v0.1.14

func (self NullUrl) Url() *url.URL

Converts to `*url.URL`. The returned pointer refers to new memory.

func (*NullUrl) UrlPtr added in v0.1.3

func (self *NullUrl) UrlPtr() *url.URL

Free cast to `*url.URL`.

func (NullUrl) Value added in v0.1.3

func (self NullUrl) Value() (driver.Value, error)

Implement `driver.Valuer`, using `.Get`.

func (NullUrl) WithFragment added in v0.1.3

func (self NullUrl) WithFragment(val string) NullUrl

Returns a modified variant with replaced `.Fragment`.

func (NullUrl) WithPath added in v0.1.3

func (self NullUrl) WithPath(src ...string) NullUrl

Returns a modified variant where `.Path` is replaced by combining the segments via `gt.Join`. See the docs on `gt.Join`. Also see `.AddPath` that appends to the path instead of replacing it.

func (NullUrl) WithQuery added in v0.1.3

func (self NullUrl) WithQuery(val url.Values) NullUrl

Returns a modified variant with replaced `.RawQuery` encoded from input.

func (NullUrl) WithRawQuery added in v0.1.3

func (self NullUrl) WithRawQuery(val string) NullUrl

Returns a modified variant with replaced `.RawQuery`.

func (*NullUrl) Zero added in v0.1.3

func (self *NullUrl) Zero()

Implement `gt.Zeroer`, zeroing the receiver.

type NullUuid

type NullUuid Uuid

Variant of `gt.Uuid` where zero value is considered empty in text, and null in JSON and SQL. Features:

  • Reversible encoding/decoding in text. Zero value is "".
  • Reversible encoding/decoding in JSON. Zero value is `null`.
  • Reversible encoding/decoding in SQL. Zero value is `null`.
  • Text encoding uses simplified format without dashes.
  • Text decoding supports formats with and without dashes, case-insensitive.

Differences from `"github.com/google/uuid".UUID`:

  • Text encoding uses simplified format without dashes.
  • Text decoding supports only simplified and canonical format.
  • Supports only version 4 (random except for a few bits).
  • Zero value is considered empty in text, and null in JSON and SQL.

Differences from `"github.com/google/uuid".NullUUID`:

  • Fewer states: there is NO "00000000000000000000000000000000".
  • Easier to use: `NullUuid` is a typedef of `Uuid`, not a wrapper.

For database columns, `NullUuid` is recommended over `Uuid`, even when columns are non-nullable. It prevents you from accidentally using zero-initialized "00000000000000000000000000000000" in SQL or JSON, without the hassle of pointers or additional fields.

func ParseNullUuid

func ParseNullUuid(src string) (val NullUuid)

Shortcut: parses successfully or panics. Should be used only in root scope. When error handling is relevant, use `.Parse`.

func RandomNullUuid

func RandomNullUuid() NullUuid

Creates a random UUID using `gt.ReadNullUuid` and "crypto/rand". Panics if random bytes can't be read.

func ReadNullUuid

func ReadNullUuid(src io.Reader) (NullUuid, error)

Creates a UUID (version 4 variant 1) from bytes from the provided reader.

func (NullUuid) AppendTo added in v0.1.21

func (self NullUuid) AppendTo(buf []byte) []byte

Implement `gt.AppenderTo`, using the same representation as `.String`.

func (NullUuid) Get

func (self NullUuid) Get() any

Implement `gt.Getter`. If zero, returns `nil`, otherwise returns `[16]byte` understood by many DB drivers.

func (NullUuid) GoString added in v0.1.3

func (self NullUuid) GoString() string

Implement `fmt.GoStringer`, returning valid Go code that constructs this value. The rendered code is biased for readability over performance: it parses a string instead of using a literal constructor.

func (NullUuid) IsNull

func (self NullUuid) IsNull() bool

Implement `gt.Nullable`. True if zero.

func (NullUuid) IsZero

func (self NullUuid) IsZero() bool

Implement `gt.Zeroable`. Equivalent to `reflect.ValueOf(self).IsZero()`.

func (NullUuid) Less

func (self NullUuid) Less(other NullUuid) bool

Equivalent to `a.String() < b.String()`. Useful for sorting.

func (NullUuid) MarshalJSON

func (self NullUuid) MarshalJSON() ([]byte, error)

Implement `json.Marshaler`. If zero, returns bytes representing `null`. Otherwise returns bytes representing a JSON string with the same text as in `.String`.

func (NullUuid) MarshalText

func (self NullUuid) MarshalText() ([]byte, error)

Implement `encoding.TextMarhaler`. If zero, returns nil. Otherwise returns the same representation as `.String`.

func (*NullUuid) Parse

func (self *NullUuid) Parse(src string) error

Implement `gt.Parser`. If the input is empty, zeroes the receiver. Otherwise requires a valid UUID representation. Supports both the short format without dashes, and the canonical format with dashes. Parsing is case-insensitive.

func (*NullUuid) Scan

func (self *NullUuid) Scan(src any) error

Implement `sql.Scanner`, converting an arbitrary input to `gt.NullUuid` and modifying the receiver. Acceptable inputs:

  • `nil` -> use `.Zero`
  • `string` -> use `.Parse`
  • `[16]byte` -> assign
  • `*[16]byte` -> use `.Zero` or assign
  • `gt.Uuid` -> assign
  • `gt.NullUuid` -> assign
  • `gt.Getter` -> scan underlying value

func (*NullUuid) Set

func (self *NullUuid) Set(src any)

Implement `gt.Setter`, using `.Scan`. Panics on error.

func (NullUuid) String

func (self NullUuid) String() string

Implement `fmt.Stringer`. If zero, returns an empty string. Otherwise returns a simplified text representation: lowercase without dashes.

func (*NullUuid) UnmarshalJSON

func (self *NullUuid) UnmarshalJSON(src []byte) error

Implement `json.Unmarshaler`. If the input is empty or represents JSON `null`, zeroes the receiver. Otherwise parses a JSON string, using the same algorithm as `.Parse`.

func (*NullUuid) UnmarshalText

func (self *NullUuid) UnmarshalText(src []byte) error

Implement `encoding.TextUnmarshaler`, using the same algorithm as `.Parse`.

func (NullUuid) Value

func (self NullUuid) Value() (driver.Value, error)

Implement `driver.Valuer`, using `.Get`.

func (*NullUuid) Zero

func (self *NullUuid) Zero()

Implement `gt.Zeroer`, zeroing the receiver.

type Nullable

type Nullable interface{ IsNull() bool }

Implemented by all types in this package. For all "null" types, this is equivalent to `gt.Zeroable`. For all non-"null" types, this always returns `false`.

TODO consider removing from `Encodable` and from non-nullable types.

type Parser

type Parser interface{ Parse(string) error }

Missing counterpart to `encoding.TextUnmarshaler`. Parses a string, rather than a byte slice.

type PtrGetter

type PtrGetter interface{ GetPtr() any }

Mutable counterpart to `gt.Getter`. Where `.Get` returns an underlying primitive value as a copy, `.GetPtr` returns an underlying primitive value as a pointer. Decoding into the underlying value by using `json.Unmarshal`, SQL decoding, or any other decoding mechanism must mutate the target, and the resulting state must be valid for that type.

Unlike other interfaces, not every type in this package implements this. This is implemented only by types whose underlying value is built-in (strings and numbers) or also supports decoding (`time.Time`).

type Raw added in v0.1.13

type Raw []byte

Similar to `json.RawMessage` but supports text, JSON, SQL. In all contexts, stores and returns self as-is, with no encoding or decoding.

func (Raw) AppendTo added in v0.1.21

func (self Raw) AppendTo(buf []byte) []byte

Implement `gt.AppenderTo`, appending self to the buffer as-is.

func (Raw) Get added in v0.1.13

func (self Raw) Get() any

Implement `gt.Getter`. If empty, returns `nil`, otherwise returns self as `[]byte`.

func (Raw) GoString added in v0.1.13

func (self Raw) GoString() string

Implement `fmt.GoStringer`, returning valid Go code that constructs this value. Assumes that the contents are UTF-8 text that can be represented with a Go string.

func (Raw) Grow added in v0.1.14

func (self Raw) Grow(size int) Raw

Missing feature of the language / standard library. Grows the slice to ensure at least this much additional capacity (not total capacity), returning a modified version of the slice. The returned slice always has the same length as the original, but its capacity and backing array may have changed. This doesn't ensure EXACTLY the given additional capacity. It follows the usual hidden Go rules for slice growth, and may allocate significantly more than asked. Similar to `(*bytes.Buffer).Grow` but without wrapping, unwrapping, or spurious escapes to the heap.

func (Raw) IsNull added in v0.1.13

func (self Raw) IsNull() bool

Implement `gt.Nullable`. True if empty.

func (Raw) IsZero added in v0.1.13

func (self Raw) IsZero() bool

Implement `gt.Zeroable`. Equivalent to `len(self)` == 0. NOT equivalent to `self == nil` or `reflect.ValueOf(self).IsZero()`.

func (Raw) Len added in v0.1.13

func (self Raw) Len() int

Same as `len(self)`. Handy in edge case scenarios involving embedding.

func (Raw) MarshalJSON added in v0.1.13

func (self Raw) MarshalJSON() ([]byte, error)

Implement `json.Marshaler`. If empty, returns bytes representing `null`. Otherwise returns self as-is, assuming that the source representation was originally valid JSON.

func (Raw) MarshalText added in v0.1.13

func (self Raw) MarshalText() ([]byte, error)

Implement `encoding.TextMarhaler`, returning self as-is.

func (*Raw) Parse added in v0.1.13

func (self *Raw) Parse(src string) error

Implement `gt.Parser`. If the input is empty, empties the receiver while keeping any capacity. Otherwise stores the input as-is, copying it for safety. If the receiver had enough capacity, its backing array may be mutated by this.

func (*Raw) Scan added in v0.1.13

func (self *Raw) Scan(src any) error

Implement `sql.Scanner`, converting an arbitrary input to `gt.Raw` and modifying the receiver. Acceptable inputs:

  • `nil` -> use `.Zero`
  • `string` -> use `.Parse`
  • `[]byte` -> use `.UnmarshalText`
  • convertible to `string` -> use `.Parse`
  • convertible to `[]byte` -> use `.UnmarshalText`
  • `gt.Raw` -> assign, replacing the receiver
  • `gt.Getter` -> scan underlying value

func (*Raw) Set added in v0.1.13

func (self *Raw) Set(src any)

Implement `gt.Setter`, using `.Scan`. Panics on error.

func (Raw) String added in v0.1.13

func (self Raw) String() string

Implement `fmt.Stringer`. Returns self as-is, performing an unsafe cast.

func (*Raw) UnmarshalJSON added in v0.1.13

func (self *Raw) UnmarshalJSON(src []byte) error

Implement `json.Unmarshaler`. If the input is empty or represents JSON `null`, empties the receiver while keeping any capacity. Otherwise stores the input as-is, copying it for safety. If the receiver had enough capacity, its backing array may be mutated by this.

func (*Raw) UnmarshalText added in v0.1.13

func (self *Raw) UnmarshalText(src []byte) error

Implement `encoding.TextUnmarshaler`. If the input is empty, empties the receiver while keeping any capacity. Otherwise stores the input as-is, copying it for safety. If the receiver had enough capacity, its backing array may be mutated by this.

func (Raw) Value added in v0.1.13

func (self Raw) Value() (driver.Value, error)

Implement `driver.Valuer`, using `.Get`.

func (*Raw) Zero added in v0.1.13

func (self *Raw) Zero()

Implement `gt.Zeroer`, emptying the receiver. If the receiver was non-nil, its length is reduced to 0 while keeping any capacity, and it remains non-nil.

type Scanner added in v0.1.13

type Scanner interface{ Scan(any) error }

Copy of `"database/sql".Scanner` to avoid a big import.

type Setter

type Setter interface{ Set(any) }

Implemented by all types in this package. Same as `.Scan`, but panics on error.

type Ter added in v0.1.8

type Ter byte

Ternary type / nullable boolean type. Similar to `*bool`, with various advantages. Has three states with the following representations:

TerNull  | 0 | ""      in text | null  in JSON | null  in SQL
TerFalse | 1 | "false" in text | false in JSON | false in SQL
TerTrue  | 2 | "true"  in text | true  in JSON | true  in SQL

Differences from `bool`:

  • 3 states rather than 2.
  • Nullable in JSON and SQL.
  • Zero value is empty/null rather than false.

Differences from `*bool`:

  • More efficient: 1 byte, no heap indirection, no added GC pressure.
  • Safer: no nil pointer panics.
  • Zero value is considered empty in text.
  • Text encoding/decoding is reversible.

Differences from `sql.NullBool`:

  • More efficient: 1 byte rather than 2.
  • Much easier to use.
  • Supports text.
  • Supports JSON.
const (
	TerNull  Ter = 0
	TerFalse Ter = 1
	TerTrue  Ter = 2
)

Valid representations of `gt.Ter`. Other values are considered invalid and will cause panics.

func BoolPtrTer added in v0.1.8

func BoolPtrTer(val *bool) Ter

Converts boolean pointer to ternary:

  • nil = gt.TerNull
  • &false = gt.TerFalse
  • &true = gt.TerTrue

For inverse conversion, use `gt.Ter.BoolPtr`.

func BoolTer added in v0.1.8

func BoolTer(val bool) Ter

Converts boolean to ternary:

  • false = gt.TerFalse
  • true = gt.TerTrue

For inverse conversion, use `gt.Ter.LaxBool` or `gt.Ter.TryBool`.

func ParseTer added in v0.1.8

func ParseTer(src string) (val Ter)

Shortcut: parses successfully or panics. Provided only for consistency with other types. Prefer constants such as `gt.TerNull`.

func (Ter) AppendTo added in v0.1.21

func (self Ter) AppendTo(buf []byte) []byte

Implement `gt.AppenderTo`, using the same representation as `.String`.

func (Ter) BoolPtr added in v0.1.8

func (self Ter) BoolPtr() *bool

Inverse of `gt.BoolPtrTer`. Converts to a boolean pointer:

  • gt.TerNull = nil
  • gt.TerFalse = &false
  • gt.TerTrue = &true

func (Ter) EqBool added in v0.1.8

func (self Ter) EqBool(val bool) bool

Exact boolean equality. If the receiver is not true or false, this returns false regardless of the input.

func (Ter) Get added in v0.1.8

func (self Ter) Get() any

Implement `gt.Getter`. If zero, returns `nil`, otherwise returns `bool`.

func (Ter) GoString added in v0.1.9

func (self Ter) GoString() string

Implement `fmt.GoStringer`, returning valid Go code representing this value.

func (Ter) IsFalse added in v0.1.8

func (self Ter) IsFalse() bool

Same as `== gt.TerFalse`.

func (Ter) IsNull added in v0.1.8

func (self Ter) IsNull() bool

Implement `gt.Nullable`. True if zero.

func (Ter) IsTrue added in v0.1.8

func (self Ter) IsTrue() bool

Same as `== gt.TerTrue`.

func (Ter) IsZero added in v0.1.8

func (self Ter) IsZero() bool

Implement `gt.Zeroable`. Equivalent to `reflect.ValueOf(self).IsZero()`.

func (Ter) LaxBool added in v0.1.8

func (self Ter) LaxBool() bool

Semi-inverse of `gt.BoolTer`. Permissive conversion, where anything untrue is considered false. Equivalent to `.IsTrue()`.

func (Ter) MarshalJSON added in v0.1.8

func (self Ter) MarshalJSON() ([]byte, error)

Implement `json.Marshaler`, using the following representations:

  • gt.TerNull = []byte("null")
  • gt.TerFalse = []byte("false")
  • gt.TerTrue = []byte("true")

The returned slices must not be mutated.

func (Ter) MarshalText added in v0.1.8

func (self Ter) MarshalText() ([]byte, error)

Implement `encoding.TextMarhaler`. If zero, returns nil. Otherwise returns the same representation as `.String`.

func (*Ter) Parse added in v0.1.8

func (self *Ter) Parse(src string) (err error)

Implement `gt.Parser`. If the input is empty, zeroes the receiver. Otherwise expects the input to be "false" or "true".

func (*Ter) Scan added in v0.1.8

func (self *Ter) Scan(src any) error

Implement `sql.Scanner`, converting an arbitrary input to `gt.Ter` and modifying the receiver. Acceptable inputs:

  • `nil` -> use `.Zero`
  • `string` -> use `.Parse`
  • `[]byte` -> use `.UnmarshalText`
  • `bool` -> use `.SetBool`
  • `*bool` -> use `.SetBoolPtr`
  • `Ter` -> assign
  • `gt.Getter` -> scan underlying value

func (*Ter) Set added in v0.1.8

func (self *Ter) Set(src any)

Implement `gt.Setter`, using `.Scan`. Panics on error.

func (*Ter) SetBool added in v0.1.8

func (self *Ter) SetBool(val bool)

Sets the receiver to the result of `gt.BoolTer`.

func (*Ter) SetBoolPtr added in v0.1.8

func (self *Ter) SetBoolPtr(val *bool)

Sets the receiver to the result of `gt.BoolPtrTer`.

func (Ter) String added in v0.1.8

func (self Ter) String() string

Implement `fmt.Stringer`, using the following representations:

  • gt.TerNull = ""
  • gt.TerFalse = "false"
  • gt.TerTrue = "true"

func (Ter) TryBool added in v0.1.8

func (self Ter) TryBool() bool

Exact inverse of `gt.BoolTer`. If true or false, converts to a boolean, otherwise panics.

func (*Ter) UnmarshalJSON added in v0.1.8

func (self *Ter) UnmarshalJSON(src []byte) error

Implement `json.Unmarshaler`, using the following representations:

  • []byte(nil) = gt.TerNull
  • []byte("") = gt.TerNull
  • []byte("null") = gt.TerNull
  • []byte("false") = gt.TerFalse
  • []byte("true") = gt.TerTrue

func (*Ter) UnmarshalText added in v0.1.8

func (self *Ter) UnmarshalText(src []byte) error

Implement `encoding.TextUnmarshaler`, using the same algorithm as `.Parse`.

func (Ter) Value added in v0.1.8

func (self Ter) Value() (driver.Value, error)

Implement `driver.Valuer`, using `.Get`.

func (*Ter) Zero added in v0.1.8

func (self *Ter) Zero()

Implement `gt.Zeroer`, zeroing the receiver.

type Uuid

type Uuid [UuidLen]byte

Simple UUID implementation. Features:

  • Reversible encoding/decoding in text.
  • Reversible encoding/decoding in JSON.
  • Reversible encoding/decoding in SQL.
  • Text encoding uses simplified format without dashes.
  • Text decoding supports formats with and without dashes, case-insensitive.

Differences from "github.com/google/uuid".UUID:

  • Text encoding uses simplified format without dashes.
  • Text decoding supports only simplified and canonical format.
  • Supports only version 4 (random except for a few bits).

When dealing with databases, it's highly recommended to use `NullUuid` instead.

func ParseUuid

func ParseUuid(src string) (val Uuid)

Shortcut: parses successfully or panics. Should be used only in root scope. When error handling is relevant, use `.Parse`.

func RandomUuid

func RandomUuid() Uuid

Creates a random UUID using `gt.ReadUuid` and "crypto/rand". Panics if random bytes can't be read.

func ReadUuid

func ReadUuid(src io.Reader) (val Uuid, err error)

Creates a UUID (version 4 variant 1) from bytes from the provided reader.

func (Uuid) AppendTo added in v0.1.21

func (self Uuid) AppendTo(buf []byte) []byte

Implement `gt.AppenderTo`, using the same representation as `.String`.

func (Uuid) Get

func (self Uuid) Get() any

Implement `gt.Getter`, returning `[16]byte` understood by many DB drivers.

func (Uuid) GoString added in v0.1.3

func (self Uuid) GoString() string

Implement `fmt.GoStringer`, returning valid Go code that constructs this value. The rendered code is biased for readability over performance: it parses a string instead of using a literal constructor.

func (Uuid) IsNull

func (self Uuid) IsNull() bool

Implement `gt.Nullable`. Always `false`.

func (Uuid) IsZero

func (self Uuid) IsZero() bool

Implement `gt.Zeroable`. Equivalent to `reflect.ValueOf(self).IsZero()`.

func (Uuid) Less

func (self Uuid) Less(other Uuid) bool

Equivalent to `a.String() < b.String()`. Useful for sorting.

func (Uuid) MarshalJSON

func (self Uuid) MarshalJSON() ([]byte, error)

Implement `json.Marshaler`, using the same representation as `.String`.

func (Uuid) MarshalText

func (self Uuid) MarshalText() ([]byte, error)

Implement `encoding.TextMarhaler`, using the same representation as `.String`.

func (*Uuid) Parse

func (self *Uuid) Parse(src string) (err error)

Implement `gt.Parser`, parsing a valid UUID representation. Supports the short format without dashes and the canonical format with dashes. Parsing is case-insensitive.

func (*Uuid) Scan

func (self *Uuid) Scan(src any) error

Implement `sql.Scanner`, converting an arbitrary input to `gt.Uuid` and modifying the receiver. Acceptable inputs:

  • `string` -> use `.Parse`
  • `[]byte` -> use `.UnmarshalText`
  • `[16]byte` -> assign
  • `gt.Uuid` -> assign
  • `gt.NullUuid` -> assign
  • `gt.Getter` -> scan underlying value

func (*Uuid) Set

func (self *Uuid) Set(src any)

Implement `gt.Setter`, using `.Scan`. Panics on error.

func (Uuid) String

func (self Uuid) String() string

Implement `fmt.Stringer`, returning a simplified text representation: lowercase without dashes.

func (*Uuid) UnmarshalJSON

func (self *Uuid) UnmarshalJSON(src []byte) error

Implement `json.Unmarshaler`, using the same algorithm as `.Parse`.

func (*Uuid) UnmarshalText

func (self *Uuid) UnmarshalText(src []byte) error

Implement `encoding.TextUnmarshaler`, using the same algorithm as `.Parse`.

func (Uuid) Value

func (self Uuid) Value() (driver.Value, error)

Implement `driver.Valuer`, using `.Get`.

func (*Uuid) Zero

func (self *Uuid) Zero()

Implement `gt.Zeroer`, zeroing the receiver.

type Zeroable

type Zeroable interface{ IsZero() bool }

Implemented by all types in this package, as well as some stdlib types. Equivalent to `reflect.ValueOf(val).IsZero()`, but also works on pointer receivers.

type Zeroer

type Zeroer interface{ Zero() }

Zeroes the receiver. Implemented by all types in this package, as well as some stdlib types.

Jump to

Keyboard shortcuts

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