into

package module
v0.0.0-...-8f66d1d Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2023 License: BSD-2-Clause Imports: 5 Imported by: 0

README

into GoDoc

into provides convenience functions for coercing dynamic values to concrete values.

Inlcudes:

  • into.String, into.Int, into.Uint, into.Float for coercing any to their respective types
  • into.CanString, into.CanInt, into.CanUint, into.CanFloat for testing coercibility
  • into.Try and into.Maybe for catching panics and coercing them to error
Motivation

This library is an experiment that might be useful if you have to deal with map[string]any, writing data mapper libraries, etc. It's not intended to replace strconv; if you know your concrete types ahead of time just use the standard library.

The panicking nature of the API is an idea borrowed from everyone's favorite, the standard library reflect package.

Example

a := into.Int(42) // 42
b := into.Int("42", into.WithConvertString) // 42
c := into.Int(nil, into.WithFallback(1337)) // 1337

var ptr *int        // nil
d := into.Int(ptr)  // 0

ok := into.CanInt("blah") // false
err := into.Try(func() {
    a = into.Int("blah")
}) // into.ErrInvalid{Value: "blah", Type: "int"}
n, err := into.Maybe(into.Int, "blah") // 0, into.ErrInvalid{Value: "blah", Type: "int"}

Performance

This library tries to avoid as much overhead as possible, and in many cases achieves zero allocation.

Benchmarks on a M2 Mac Mini:

BenchmarkFloat-12                	601534540	        1.997 ns/op	      0 B/op	      0 allocs/op
BenchmarkFloatWithOptions-12     	444859920	        2.692 ns/op	      0 B/op	      0 allocs/op
BenchmarkFloatFallback-12        	441497448	        2.699 ns/op	      0 B/op	      0 allocs/op
BenchmarkInt-12                  	572993503	        2.096 ns/op	      0 B/op	      0 allocs/op
BenchmarkIntWithOptions-12       	442683682	        2.715 ns/op	      0 B/op	      0 allocs/op
BenchmarkIntFallback-12          	440095513	        2.704 ns/op	      0 B/op	      0 allocs/op
BenchmarkString-12               	331075846	        3.579 ns/op	      0 B/op	      0 allocs/op
BenchmarkStringWithOptions-12    	307433682	        3.914 ns/op	      0 B/op	      0 allocs/op
BenchmarkStringFallback-12       	264048576	        4.490 ns/op	      0 B/op	      0 allocs/op
BenchmarkUint-12                 	621541999	        1.928 ns/op	      0 B/op	      0 allocs/op
BenchmarkUintWithOptions-12      	447733209	        2.673 ns/op	      0 B/op	      0 allocs/op
BenchmarkUintFallback-12         	445057358	        2.689 ns/op	      0 B/op	      0 allocs/op

Documentation

Overview

Package into provides convenience functions for creating and dereferencing pointers and converting types.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func CanFloat

func CanFloat(x any, options ...Option) bool

CanFloat returns true if the given value can be coerced to a float. See: Float for supported types.

func CanInt

func CanInt(x any, options ...Option) bool

CanInt returns true if the given value can be coerced to a signed integer. Int will succeed without panicking if CanInt returns true.

See: Int for supported types.

func CanString

func CanString(x any, options ...Option) bool

CanString returns true if the given value can be coerced to a signed integer. String will succeed without panicking if CanString returns true.

See: String for supported types.

func CanUint

func CanUint(x any, options ...Option) bool

CanUint returns true if the given value can be coerced to a signed integer. Uint will succeed without panicking if CanUint returns true.

See: Uint for supported types.

func Float

func Float(x any, options ...Option) float64

Float coerces x into a float, supporting the following types:

  • float64, float32
  • *float64, *float32
  • types with an underlying float value or pointers to such types
  • given WithConvertStrings, any string-like type supported by String
  • nil

Float will panic with ErrInvalid if the value cannot be coerced.

func Int

func Int(x any, options ...Option) int

Int coerces x into a signed integer, supporting the following types:

  • int, int64, int32 (and rune), int16, int8
  • *int, *int64, *int32 (and *rune), *int16, *int8
  • types with an underlying signed integer value or pointers to such types
  • given WithConvertStrings, any string-like type supported by String
  • nil

Int will panic with ErrInvalid if the value cannot be coerced.

func Maybe

func Maybe[T any](try func(any, ...Option) T, value any, options ...Option) (result T, err error)

Maybe tries to run the given function (such as Int or String), returning an error instead of panicking.

Example
package main

import (
	"fmt"

	"github.com/guregu/into"
)

func main() {
	_, err := into.Maybe(into.Int, "cat")
	fmt.Println(err)
}
Output:

into: value cat of type string is not a int

func Ptr

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

Ptr returns a pointer to v.

Example
package main

import (
	"fmt"

	"github.com/guregu/into"
)

func main() {
	np := into.Ptr(42)
	fmt.Println(*np)
}
Output:

42

func String

func String(x any, options ...Option) string

String coerces x into a string, supporting the following types:

String will panic with ErrInvalid if the value cannot be coerced or TextMarshaler fails.

func Try

func Try(fn func()) (err error)

Try executes fn, recovering and returning an error if it panics. If the panic value satisfies the error interface, it will be returned as-is; otherwise, it will be wrapped in Panic.

func Uint

func Uint(x any, options ...Option) uint

Uint coerces x into an unsigned integer, supporting the following types:

  • uint, uint64, uint32, uint16, uint8
  • *uint, *uint64, *uint32, *uint16, *uint8
  • types with an underlying unsigned integer value or pointers to such types
  • given WithConvertStrings, any string-like type supported by String
  • nil

Uint will panic with ErrInvalid if the value cannot be coerced.

func Value

func Value[T any](p *T) T

Value indirects (dereferences) p if non-nil, otherwise returns the zero value.

Example
package main

import (
	"fmt"

	"github.com/guregu/into"
)

func main() {
	var np *int
	value := into.Value(np)
	fmt.Println(value)
}
Output:

0

func ValueOr

func ValueOr[T any](p *T, fallback T) T

ValueOr indirects (dereferences) p if non-nil, otherwise returns the fallback value.

Types

type ErrInvalid

type ErrInvalid struct {
	Value any
	Type  string

	// Cause is non-nil if a fallible conversion returns an error (such as string conversion or TextMarshaler).
	Cause error
}

ErrInvalid is an error returned when into could not convert a given value.

func (ErrInvalid) Error

func (err ErrInvalid) Error() string

func (ErrInvalid) Unwrap

func (err ErrInvalid) Unwrap() error

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option is a configuration parameter. Use the With... functions to specify options.

func WithConvertStrings

func WithConvertStrings() Option

WithConvertStrings enables conversion of strings during type coercion.

func WithFallback

func WithFallback(fallback any) Option

WithFallback specifies a fallback value when coercing nil input. By default, the zero value is returned.

func WithoutMarshalerCheck

func WithoutMarshalerCheck() Option

WithoutMarshalerCheck is an option that skips a check in CanString and similar that runs encoding.TextMarshaler's marshal or strconv conversions to ensure they don't return errors.

func WithoutReflection

func WithoutReflection() Option

WithoutReflection will skip using reflection to coerce values. Using this disables support for nonstandard types (e.g. custom subtypes of int or string).

type Panic

type Panic struct {
	// Value is the value passed to panic.
	Value any
}

Panic is an error encapsulating a panicked value.

func (Panic) Error

func (p Panic) Error() string

Error satisfies the error interface using fmt's %v verb to represent the panic value.

Jump to

Keyboard shortcuts

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