types

package
v0.0.0-...-24ca9bf Latest Latest
Warning

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

Go to latest
Published: Jun 7, 2022 License: MIT Imports: 15 Imported by: 0

Documentation

Index

Examples

Constants

View Source
const (
	ESC       = "\x1b"
	NL        = "\n"
	TAB       = "\t"
	SPACE     = " "
	AnsiReset = "\x1b[0m"
)
View Source
const (
	UPPER    = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	LOWER    = "abcdefghijklmnopqrstuvwxyz"
	DIGITS   = "0123456789"
	ALPHA    = LOWER + UPPER
	ALPHANUM = ALPHA + DIGITS
)
View Source
const ReplacementChar rune = '\uFFFD'

ReplacementChar is the recognized unicode replacement character for malformed unicode or errors in encoding.

It is also found in unicode.ReplacementChar

Variables

View Source
var (
	LimitResult            bool
	DefaultTestResultLimit = 15
)
View Source
var Greek = charMap{

	"Alpha":   {'A', 'Α', 'α'},
	"Beta":    {'B', 'Β', 'β'},
	"Gamma":   {'G', 'Γ', 'γ'},
	"Delta":   {'D', 'Δ', 'δ'},
	"Epsilon": {'E', 'Ε', 'ε'},
	"Zeta":    {'Z', 'Ζ', 'ζ'},
	"Eta":     {'H', 'Η', 'η'},
	"Theta":   {'T', 'Θ', 'θ'},
	"Iota":    {'I', 'Ι', 'ι'},
	"Kappa":   {'K', 'Κ', 'κ'},
	"Lambda":  {'L', 'Λ', 'λ'},
	"Mu":      {'M', 'Μ', 'μ'},
	"Nu":      {'N', 'Ν', 'ν'},
	"Xi":      {'X', 'Ξ', 'ξ'},
	"Omicron": {'O', 'Ο', 'ο'},
	"Pi":      {'P', 'Π', 'π'},
	"Rho":     {'R', 'Ρ', 'ρ'},
	"Sigma":   {'S', 'Σ', 'σ'},
	"Tau":     {'t', 'Τ', 'τ'},
	"Upsilon": {'U', 'Υ', 'υ'},
	"Phi":     {'p', 'Φ', 'φ'},
	"Chi":     {'C', 'Χ', 'χ'},
	"Psi":     {'s', 'Ψ', 'ψ'},
	"Omega":   {'W', 'Ω', 'ω'},
}
View Source
var IsTerminal bool = isTerminal()

IsTerminal returns true if os.Stdout is a terminal. This is used to determine output options such as ANSI color sequences used in terminal output.

Reference: uses isatty package (MIT License): https://github.com/mattn/go-isatty

View Source
var (
	Log = errorlogger.Log
)
View Source
var NilStruct = &structs.Struct{}

Functions

func Addr

func Addr(v reflect.Value) reflect.Value

Addr returns a pointer value representing the address of v. If v is not addressable, v is returned unchanged.

Addr is typically used to obtain a pointer to a struct field or slice element in order to call a method that requires a pointer receiver.

func AssertComparable

func AssertComparable(t *testing.T, got, want Any) (retval bool)

func AssertEqual

func AssertEqual(got, want Any) bool

func BRun

func BRun(b *testing.B, name string, function Any, args ...Any)

BRun runs function with arguments args and returns a slice of results to a global dummy variable.

If a panic occurs, BRun will mark it as failed and continue running other benchmarks / tests.

func BTest

func BTest(b *testing.B, text string, got, want Any) bool

func Contains

func Contains(needle Any, haystack []Any) bool

Contains returns true if the underlying iterable sequence (haystack) contains the search term (needle) in at least one position.

func Convert

func Convert(v reflect.Value, typ reflect.Type) reflect.Value

Convert returns the value v converted to type t. If the usual Go conversion rules do not allow conversion of the value v to type t, or if converting v to type t would panic, v is returned.

func Count

func Count(needle Any, haystack []Any) int

Count returns the number of times the search term (needle) occurs in the underlying iterable sequence (haystack).

func Elem

func Elem(v reflect.Value) reflect.Value

Elem returns the value that the interface contains or that the pointer points to. If the kind of a is not Interface or Ptr, the v is returned. It returns the zero Value if the underlying is nil.

func Frequency

func Frequency(s string) byteMap

LetterFrequency maps the frequency of letters in a text sample

func GetFileListByName

func GetFileListByName(path, needle string) (files []string, err error)

func GetFileListByPrefix

func GetFileListByPrefix(path, prefix string) (files []string, err error)

func GetFileListBySuffix

func GetFileListBySuffix(path, suffix string) (files []string, err error)

func GetFileListWithDirectories

func GetFileListWithDirectories(path string) (files []string, err error)

func GetGoFileList

func GetGoFileList() (files []string, err error)

func GuardReflectType

func GuardReflectType(v reflect.Value) reflect.Type

func HasAlternate

func HasAlternate(v Any) bool

HasAlternate returns true if the underlying value has alternate methods in addition to the Go standard library operations.

func Indirect

func Indirect(v reflect.Value) reflect.Value

Indirect returns the value that v points to. If v is a nil pointer, Indirect returns a zero Value. If v is not a pointer, Indirect returns v.

func Intn

func Intn(start, end int) int

func IsComparable

func IsComparable(a Any) bool

IsComparable returns true if the underlying value is of a type that is capable of comparisions, e.g. equal, not equal

Bools, strings and most numeric values are comparable.

Next, types that have a Len() method are considered comparable by this function based on their length and item type alone. This is different from the standard library approach.

func IsDeepComparable

func IsDeepComparable(v Any) bool

IsDeepComparable returns true if the underlying value is of a type that is capable of DeepEqual, the Go standard library approach to rigorous comparisons.

func IsIterable

func IsIterable(v Any) bool

IsIterable returns true if the underlying value is made up of smaller units that can be read out one by one.

Maps, strings, and slices naturally come to mind, but this package also adds functionality to iterate over most numeric values and structs.

func IsOrdered

func IsOrdered(v Any) bool

IsOrdered returns true if the underlying value is ordered. This means that it is capable of order based comparisons, e.g. less than, greater than

Strings and most numeric values are ordered.

func KindOf

func KindOf(a Any) reflect.Kind

Kind returns a's Kind. If a is the zero Value (IsValid returns false), Kind returns Invalid.

func NewByteMap

func NewByteMap(s string) *byteMap

func NewKindInfo

func NewKindInfo(a Any) kindInfo

func NewStruct

func NewStruct(v Any) *structs.Struct

func PrepValues

func PrepValues(got, want Any) (AnyValue, AnyValue)

func RandomGreek

func RandomGreek(length, minGreekPct, maxGreekPct int) string

func RandomGreekString

func RandomGreekString(n int) string

func RandomString

func RandomString(n int) string

func ShowFrequency

func ShowFrequency(s string) string

func TAssertEqual

func TAssertEqual(t *testing.T, name string, got, want Any)

func TAssertType

func TAssertType(t *testing.T, name string, got, want reflect.Kind)

func TError

func TError(t *testing.T, name string, got, want Any)

func TName

func TName(testname, funcname, argname Any) string

func TRun

func TRun(t *testing.T, name string, got, want Any)

func TTypeError

func TTypeError(t *testing.T, name string, got, want Any)

func TTypeRun

func TTypeRun(t *testing.T, name string, got, want Any)

func TerminalExample

func TerminalExample()

TerminalExample prints the results of isatty.IsTerminal() and isatty.IsCygwinTerminal() to os.Stdout

Example

Example prints the results of isatty.IsTerminal() and isatty.IsCygwinTerminal() to os.Stdout

package main

import (
	"github.com/skeptycal/gosimple/types"
)

func main() {
	types.TerminalExample()
}
Output:

func ToString

func ToString(a Any) string

ToString converts the given argument to the standard string representation. If a implements fmt.Stringer, it is used, otherwise the slower fmt.Sprintf is used as a backup.

func ToValues

func ToValues(list []Any) []reflect.Value

func TypeOf

func TypeOf(a Any) reflect.Type

Type returns a's type.

func ValueOf

func ValueOf(i interface{}) reflect.Value

ValueOf returns a new Value initialized to the concrete value stored in the interface i. ValueOf(nil) returns the zero Value.

func WithLock

func WithLock(lk Locker, fn func())

WithLock runs fn while holding lk.

Types

type Any

type Any = interface{}

Any represents a object that may contain any valid type.

func Interface

func Interface(v reflect.Value) Any

Interface returns v's current value as an interface{}. It is equivalent to:

var i interface{} = (v's underlying value)

It panics if the Value was obtained by accessing unexported struct fields.

type AnyValue

type AnyValue interface {

	// ValueOf returns a new Value initialized to the
	// concrete value stored in the interface i.
	// ValueOf(nil) returns the zero Value.
	ValueOf() reflect.Value

	// TypeOf returns the object's type.
	TypeOf() reflect.Type

	// Kind returns v's Kind. If v is the zero Value
	// (IsValid returns false), Kind returns Invalid.
	Kind() reflect.Kind

	// Interface returns the original underlying interface.
	Interface() Any

	// Indirect returns the value pointed to by a pointer.
	// If the AnyValue is not a pointer, indirect returns the
	// AnyValue unchanged.
	Indirect() AnyValue

	// Elem returns the value that the interface contains
	// or that the pointer points to. If the kind of the
	// AnyValue is not Interface or Ptr, the original
	// AnyValue is returned.
	Elem() reflect.Value

	String() string

	KindInfo
}

AnyValue is a wrapper around the Any interface, or interface{}, which may contain any value. The extra features of this wrapper allow value, type, and kind information, as well as whether the type is comparable, ordered, and/or iterable.

func GetAnyValues

func GetAnyValues(args ...Any) []AnyValue

func NewAnyValue

func NewAnyValue(a Any) AnyValue

NewAnyValue returns a new AnyValue interface, e.g. v := NewAnyValue(uint(42))

AnyValue is a wrapper around the Any interface, or interface{}, which may contain any value. The original interface{} value is returned by v.Interface()

The extra features of this wrapper allow value, type, and kind information, as well as whether the type is comparable, ordered, and/or iterable.

type Arg

type Arg interface{}

type Assert

type Assert interface {
	Tester
	Result() bool
}

Assert implements the Tester interface. It is used for boolean only challenges. In addition to working seamlessly with the standard library testing package, it can return the bool result for use in alternate data collection or CI software.

type Closer

type Closer interface {
	Close() error
}

Closer is the interface that wraps the basic Close method.

The behavior of Close after the first call is undefined. Specific implementations may document their own behavior.

type Cosa

type Cosa struct{}

Cosa is a generic 'thing.' It is an empty stuct used for 'preallocating' zero resource objects.

type Custom

type Custom interface {
	Tester
	Hook(name string, got, want Any, wantErr bool)
}

Custom implements Tester and can be used to hook into existing software by passing in the various test arguments with Hook(). Calling Hook() also calls Run() automaticaly.

type Enabler

type Enabler interface {
	Enable()
	Disable()
}

An Enabler represents an object that can be enabled or disabled.

type Errer

type Errer interface {
	Err() error
}

Errer processes and returns an error

type Formatter

type Formatter interface {
	Format(f State, verb rune)
}

Formatter is implemented by any value that has a Format method. The implementation controls how State and rune are interpreted, and may call Sprint(f) or Fprint(f) etc. to generate its output.

Ref: Standard Library fmt package

type Fprinter

type Fprinter interface {
	Fprint(w Writer, a ...interface{}) (n int, err error)
	Fprintln(w Writer, a ...interface{}) (n int, err error)
	Fprintf(w Writer, format string, a ...interface{}) (n int, err error)
}

Fprinter implements common printing functions similar to the standard library fmt package.

Example methods:

func (p *padding) Fprint(w Writer, args ...interface{}) (n int, err error) {
	// TODO Print unformatted args to Writer
	return n, err
}
func (p *padding) Fprintln(w Writer, args ...interface{}) (n int, err error) {
	// TODO Print unformatted args to Writer with line break (NL)
	return n, err
}
func (p *padding) Fprintf(w Writer, format string, args ...interface{}) (n int, err error) {
	// TODO Print formatted args to Writer
	return n, err
}

type Function

type Function interface {
	Name() string
	Func() Any
	Args() []Arg
}

type FunctionCaller

type FunctionCaller interface {
	// Run runs a function and compares the results
	Tester
}

type GetSetter

type GetSetter[K comparable, V any] interface {
	Get(key K) (V, error)
	Set(key K, value V) error
}

A GetSetter represents an object that can be accessed using Get and Set methods to access an underlying map.

Example methods:

 func (p *padding) Get(key Any) (Any, error) {
		// TODO get the value that matches the key
 	return nil, nil
 }
 func (p *padding) Set(key, value Any) error {
		// TODO set the value that matches the key
 	return nil
 }

type GoCode

type GoCode interface {
	Functions() []Function
}

type Kind

type Kind = reflect.Kind

A Kind represents the specific kind of type that a Type represents. The zero Kind is not a valid kind.

Reference: standard library reflect package

type Kind uint
const (
	Invalid Kind = iota
	Bool
	Int
	Int8
	Int16
	Int32
	Int64
	Uint
	Uint8
	Uint16
	Uint32
	Uint64
	Uintptr
	Float32
	Float64
	Complex64
	Complex128
	Array
	Chan
	Func
	Interface
	Map
	Ptr
	Slice
	String
	Struct
	UnsafePointer
)

type KindInfo

type KindInfo interface {
	IsComparable() bool
	IsOrdered() bool
	IsIterable() bool
	IsDeepComparable() bool
	HasAlternate() bool
}

type ListSorter

type ListSorter[E comparable, S ~[]E] interface {
	Sorter
	Sorted() S
	Reverse() S
}

type Lister

type Lister[E comparable, S ~[]E] interface {
	List() S
	Sorted() S
	Reverse() S
}

type Locker

type Locker interface {
	Lock()
	Unlock()
}

A Locker represents an object that can be locked and unlocked.

type Locker interface {
	Lock()
	Unlock()
}

Ref: Standard Library sync package

type MapSlicer

type MapSlicer[E comparable, S ~[]E] interface {
	Keys(sorted bool) S
	Values(sorted bool) S
	SortedKeys() S
	ReverseKeys() S
	ListSorter[E, S]
}

MapSlicer returns the slice of keys and values that are asoociated with the underlying map.

Example methods:

func (d *dict) Keys() []Any {
	// TODO return a list of keys
	keys := make([]Any, len(d.m))
 	for k := range d.m {
 		keys = append(keys, k)
 	}
 	return keys
 }
 func (d *dict) Values() []Any {
	// TODO return a list of values
 	values := make([]Any, len(d.m))
 	for _, v := range d.m {
 		values = append(values, v)
 	}
 	return values
 }

type Node

type Node interface{}

func BuildNodes

func BuildNodes() Node

BuildNodes returns the parent node of a tree structure.

type Printer

type Printer interface {
	Print(args ...interface{}) (n int, err error)
	Println(args ...interface{}) (n int, err error)
	Printf(format string, args ...interface{}) (n int, err error)
}

Printer implements common printing functions similar to the standard library fmt package.

Example methods:

func (p *padding) Print(args ...interface{}) (n int, err error) {
	// TODO Print unformatted args
	return n, err
}
func (p *padding) Println(args ...interface{}) (n int, err error) {
	// TODO Print unformatted args with line break (NL)
	return n, err
}
func (p *padding) Printf(format string, args ...interface{}) (n int, err error) {
	// TODO Print formatted args
	return n, err
}

type Protector

type Protector interface {
	Protect()
	Unprotect()
}

Protector is used when an object needs to be protected or unprotected (inspired by the "write-protect" tabs of floppy disks)

type Random

type Random interface {
	Tester
	Regenerate()
}

Random implements Tester and creates a random test that can be used to generate many varied tests automatically. After each use, Regenerate() can be called to generate a new test.

type Sorter

type Sorter interface {
	// Len is the number of elements in the collection.
	Len() int

	// Less reports whether the element with index i
	// must sort before the element with index j.
	//
	// If both Less(i, j) and Less(j, i) are false,
	// then the elements at index i and j are considered equal.
	// Sort may place equal elements in any order in the final result,
	// while Stable preserves the original input order of equal elements.
	//
	// Less must describe a transitive ordering:
	//  - if both Less(i, j) and Less(j, k) are true, then Less(i, k) must be true as well.
	//  - if both Less(i, j) and Less(j, k) are false, then Less(i, k) must be false as well.
	//
	// Note that floating-point comparison (the < operator on float32 or float64 values)
	// is not a transitive ordering when not-a-number (NaN) values are involved.
	// See Float64Slice.Less for a correct implementation for floating-point values.
	Less(i, j int) bool

	// Swap swaps the elements with indexes i and j.
	Swap(i, j int)
}

An implementation of sort.Interface can be sorted by the routines in this package. The methods refer to elements of the underlying collection by integer index.

Ref: Standard Library sort package

type Sprinter

type Sprinter interface {
	Sprint(args ...interface{}) string
	Sprintln(args ...interface{}) string
	Sprintf(format string, args ...interface{}) string
}

Sprinter implements common printing functions similar to the standard library fmt package.

Example methods:

func (p *padding) Sprint(args ...interface{}) string {
	// TODO Print unformatted args to string
	return ""
}
func (p *padding) Sprintln(args ...interface{}) string {
	// TODO Print unformatted args to string with line break (NL)
	return ""
}
func (p *padding) Sprintf(format string, args ...interface{}) string {
	// TODO Print formatted args to string
	return ""
}

type State

type State interface {
	// Write is the function to call to emit formatted output to be printed.
	Write(b []byte) (n int, err error)
	// Width returns the value of the width option and whether it has been set.
	Width() (wid int, ok bool)
	// Precision returns the value of the precision option and whether it has been set.
	Precision() (prec int, ok bool)
	// Flag reports whether the flag c, a character, has been set.
	Flag(c int) bool
}

State represents the printer state passed to custom formatters. It provides access to the io.Writer interface plus information about the flags and options for the operand's format specifier.

Ref: Standard Library fmt package

type StringWriter

type StringWriter interface {
	WriteString(s string) (n int, err error)
}

StringWriter is the interface that wraps the WriteString method.

WriteString writes the contents of the string s to w, which accepts a slice of bytes. If w implements StringWriter, its WriteString method is invoked directly. Otherwise, w.Write is called exactly once.

Ref: Standard Library io package

type Stringer

type Stringer interface {
	String() string
}

Stringer is implemented by any value that has a String method, which defines the “native” format for that value. The String method is used to print values passed as an operand to any format that accepts a string or to an unformatted printer such as Print.

Ref: Standard Library fmt package

type TestRunner

type TestRunner interface {
	// Run runs all tests in the set.
	Tester
}

func NewTestSet

func NewTestSet(t *testing.T, name string, list []test) TestRunner

type Tester

type Tester interface {
	// Run runs an individual test.
	Run()
}

Tester implements an individual test. It may be implemented by traditional tests, asserts, random inputs, or custom code.

func NewTest

func NewTest(t *testing.T, name string, got, want Any, wantErr bool, assert testFunc) Tester

type Type

type Type = reflect.Type

Type is the representation of a Go type.

Not all methods apply to all kinds of types. Restrictions, if any, are noted in the documentation for each method. Use the Kind method to find out the kind of type before calling kind-specific methods. Calling a method inappropriate to the kind of type causes a run-time panic.

Type values are comparable, such as with the == operator, so they can be used as map keys. Two Type values are equal if they represent identical types.

Synopsis of methods:

type Type interface {
	Align() int
	FieldAlign() int
	Method(int) Method
	MethodByName(string) (Method, bool)
	NumMethod() int
	Name() string
	PkgPath() string
	Size() uintptr
	String() string
	Kind() Kind
	Implements(u Type) bool
	AssignableTo(u Type) bool
	ConvertibleTo(u Type) bool
	Comparable() bool
	Bits() int
	ChanDir() ChanDir
	IsVariadic() bool
	Elem() Type
	Field(i int) StructField
	FieldByIndex(index []int) StructField
	FieldByName(name string) (StructField, bool)
	FieldByNameFunc(match func(string) bool) (StructField, bool)
	In(i int) Type
	Key() Type
	Len() int
	NumField() int
	NumIn() int
	NumOut() int
	Out(i int) Type

 	common() *rtype
	uncommon() *uncommonType
}

type Writer

type Writer interface {
	Write(p []byte) (n int, err error)
}

Writer is the interface that wraps the basic Write method.

Write writes len(p) bytes from p to the underlying data stream. It returns the number of bytes written from p (0 <= n <= len(p)) and any error encountered that caused the write to stop early. Write must return a non-nil error if it returns n < len(p). Write must not modify the slice data, even temporarily.

Implementations must not retain p.

Ref: Standard Library io package

Directories

Path Synopsis
cmd
Package constraints defines a set of useful constraints to be used with type parameters.
Package constraints defines a set of useful constraints to be used with type parameters.

Jump to

Keyboard shortcuts

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