strutils

package module
v0.0.0-...-2e3aed4 Latest Latest
Warning

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

Go to latest
Published: Mar 16, 2025 License: MIT Imports: 8 Imported by: 2

README

strutils

Additional string parsing and manipulation functions for Go.

Comparisons, prefixes, trimming, quoting, wildcards, random, segmentation, tags, values, wrapping, conversion, printing.

Uses unsafe package.

Status

Ever evolving.

License

MIT.

See included LICENSE file.

Documentation

Overview

Package strings adds additional string utility functions.

Index

Constants

This section is empty.

Variables

View Source
var (
	Wovels        = "aeiou"
	Consonants    = "bcdfghjklmnpqrstvxyz"
	SpecialChars  = " !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~"
	Numerals      = "0123456789"
	AlphaUpper    = "ABCDEFGHIJKLMNOPQRSTUVXYZ"
	AlphaLower    = "abcdefghijklmnopqrstuvxyz"
	Alpha         = AlphaUpper + AlphaLower
	AlphaNumerals = Numerals + Alpha
)
View Source
var (
	WovelsBytes        = []byte(Wovels)
	ConsonantsBytes    = []byte(Consonants)
	SpecialCharsBytes  = []byte(SpecialChars)
	NumeralsBytes      = []byte(Numerals)
	AlphaUpperBytes    = []byte(AlphaUpper)
	AlphaLowerBytes    = []byte(AlphaLower)
	AlphaBytes         = []byte(Alpha)
	AlphaNumeralsBytes = []byte(AlphaNumerals)
)
View Source
var ErrTagNotFound = errors.New("tag not found")

ErrTagNotFound is returned when tag named [Tag.TagKey] was not found in a tag string literal.

Functions

func CamelCase

func CamelCase(s string) string

Camelcase the given string.

func Compare

func Compare(a, b string) int

Compare returns 1 if a > b, -1 if a < b or 0 if a == b.

func CompareFold

func CompareFold(a, b string) int

CompareFold returns 1 if a > b, -1 if a < b or 0 if a == b. Comparison is not case-sensitive.

func FetchLeft

func FetchLeft(s, sep string) string

Return s prefix up to sep starting from the left. If sep not found returns an empty string.

func FetchLeftFold

func FetchLeftFold(s, sep string) string

Return s prefix up to sep starting from the left. Separator search is case-insesitive, result casing is not modified. If sep not found returns an empty string.

func FetchRight

func FetchRight(s, sep string) string

Return s suffix up to sep starting from the right. If sep not found returns an empty string.

func FetchRightFold

func FetchRightFold(s, sep string) string

Return s suffix up to sep starting from the right. Separator search is case-insesitive, result casing is not modified. If sep not found returns an empty string.

func HasPrefixFold

func HasPrefixFold(s, prefix string) bool

HasPrefixFold tests whether the string s begins with prefix. Case-insensitive.

func HasSuffixFold

func HasSuffixFold(s, suffix string) bool

HasSuffixFold tests whether the string s ends with suffix Case-insensitive.

func IndexFold

func IndexFold(s, substr string) int

IndexFold returns the index of the first instance of substr in s, or -1 if substr is not present in s. Search is case-insensitive.

func Indexes

func Indexes(s, sep string) (r []int)

Indexes returns a slice of all indexes of "sep" starting byte positions in "s", or an empty slice if none are present in "s".

func IndexesFold

func IndexesFold(s, sep string) []int

Indexes returns a slice of all indexes of "sep" starting byte positions in "s", or an empty slice if none are present in "s". Case-insensitive.

func IsAlphanumeric

func IsAlphanumeric(c byte) bool

IsAlphanumeric returns true if c is a digit, lower or upper alpha.

func IsDigit

func IsDigit(c byte) bool

IsDigit returns true if c is a digit.

func IsLetter

func IsLetter(c byte) bool

IsLetter returns true if c is lowercase or uppercase alpha.

func IsLower

func IsLower(c byte) bool

IsLower returns true if c is a lowercase alpha.

func IsUpper

func IsUpper(c byte) bool

IsUpper returns true if c is an uppercase alpha.

func KebabCase

func KebabCase(s string) string

Kebabcase the given string.

func LookupTag

func LookupTag(rawStructTag, key string) (value string, ok bool)

LookupTag returns the value associated with key in the tag string. If the key is present in the tag the value (which may be empty) is returned. Otherwise the returned value will be the empty string. The ok return value reports whether the value was explicitly set in the tag string. If the tag does not have the conventional format, the value returned by LookupTag is unspecified.

LookupTag is a copy of (reflect.Lookup) to skip the reflect include.

func MatchesWildcard

func MatchesWildcard(text, pattern string) bool

Matches "text" against "pattern". Case insensitive. Returns truth. * matches any number of characters. ? matches one character.

func PascalCase

func PascalCase(s string) string

Pascalcase the given string.

func QuoteDouble

func QuoteDouble(s string) string

QuoteDouble wraps s with double quotes.

func QuoteSingle

func QuoteSingle(s string) string

QuoteSingle wraps s with single quotes.

func Random

func Random(set []byte) string

Random returns a string containing a single character from set.

func RandomByte

func RandomByte(set []byte) []byte

Random returns a string containing a single character from set.

func RandomLower

func RandomLower() string

Returns a string containing a random lowercase letter.

func RandomLowers

func RandomLowers(length int) string

Returns a string of random lowercase letters of length.

func RandomNum

func RandomNum() string

Returns a string containing a random number.

func RandomNums

func RandomNums(length int) string

Returns a string of random numbers of length.

func RandomSpecial

func RandomSpecial() string

Returns a string containing a random password special character.

func RandomSpecials

func RandomSpecials(length int) string

Returns a string of random special characters of length.

func RandomString

func RandomString(lo, up, nums bool, length int) string

Returns a random string of "length". If "lo" includes lowercase letters. If "up" includes uppercase letters. If "num" includes numbers.

func RandomUpper

func RandomUpper() string

Returns a string containing a random uppercase letter.

func RandomUppers

func RandomUppers(length int) string

Returns a string of random uppercase letters of length.

func Randoms

func Randoms(set []byte, length int) string

Randoms returns a string of length consisting of random characters from s.

func Segment

func Segment(s, sep string, start int) (segment string, next int)

Segment returns the word up to the next separator and index of s just after the separator. Scan of s starts at start index.

If sep was not found returns s starting at start and -1. If the end of s was reached resulting next will be -1. Returns an empty string and -1 if start is out of range or sep is empty.

func SegmentFold

func SegmentFold(s, sep string, start int) (segment string, next int)

SegmentFold is the case-insensitive version of Segment.

func SnakeCase

func SnakeCase(s string) string

Snakecase the given string.

func ToLower

func ToLower(c byte) byte

ToLower returns lowercased c.

func ToUpper

func ToUpper(c byte) byte

ToLower returns uppercased c.

func Unique

func Unique(in ...string) (out []string)

Unique returns unique strings from in.

Returned strings are in order as passed in.

func UnquoteDouble

func UnquoteDouble(s string) (string, bool)

UnquoteDouble removes double quotes around s and returns it and true on success. If either leading or trailing quote is not found result is s, false.

func UnquoteSingle

func UnquoteSingle(s string) (string, bool)

UnquoteSingle removes single quotes around s and returns it and true on success. If either leading or trailing quote is not found result is s, false.

func UnsafeStringBytes

func UnsafeStringBytes(s string) []byte

UnsafeStringBytes returns bytes of a string without allocating a slice.

Result is a weak, non-garbage collected byte slice that is valid for the lifetime of s.

func Unwrap

func Unwrap(s, prefix, suffix string) (string, bool)

Unwrap unpacks the string by removing prefix and suffix. If both prefix and suffix were found result is an unpacked string and true else result is s and false. Both prefix and suffix are optional and can be empty in which case their removal is not performed.

func UnwrapFold

func UnwrapFold(s, prefix, suffix string) (string, bool)

UnwrapFold is the case-insensitive version of Unpack.

func Wrap

func Wrap(s, prefix, suffix string) string

Wrap wraps s within prefix and suffix.

func WrapText

func WrapText(text string, cols int, force bool) (out []string)

WrapText wraps text into multiple lines at first whitespace before or exactly at cols.

If a word is longer than cols and force is true it is split at cols length regardless of white space. If force is false, the word is not split and placed into its own line at first next whitespace.

Allocates runes of text and appends to out without preallocation.

Types

type CaseMapping

type CaseMapping int

CaseMapping specifies one of case mapping supported by this package.

const (
	// InvalidMapping is the invalid/undefined mapping.
	InvalidMapping CaseMapping = iota
	// NoMapping specifies no mapping.
	NoMapping
	// PascalMapping specifies PascalCase mapping.
	PascalMapping
	// SnakeMapping specifies snake_case mapping.
	SnakeMapping
	// CamelMapping specifies camelCase mapping.
	CamelMapping
	// KebabMapping specifies kebab-case mapping.
	KebabMapping
)

func (CaseMapping) Map

func (self CaseMapping) Map(s string) string

Map case maps s depending on self value. If mapping value is unknown input string is returned unmodified.

func (CaseMapping) MarshalText

func (self CaseMapping) MarshalText() (text []byte, err error)

MarshalText implementes encoding.TextMarshaler on CaseMapping.

func (CaseMapping) String

func (self CaseMapping) String() string

String implements stringer on CaseMapping.

func (*CaseMapping) UnmarshalText

func (self *CaseMapping) UnmarshalText(text []byte) error

UnmarshalText implementes encoding.TextUnmarshaler on CaseMapping.

type Converter

type Converter struct {
	// TimeFormat is the time layout sring used to parse time strings.
	TimeFormat string
}

Converter converts strings and string slices into basic go types.

func NewConverter

func NewConverter() Converter

NewConverter returns a new Converter with default values.

func (Converter) StringToAny

func (self Converter) StringToAny(in string, out any) (err error)

StringToAny converts in to out or returns an error.

In must be a GoString compatible with out which must be a pointer to the variable whose value is to be set. Basic, non-structured types and slices of those types are supported.

type Foo

type Foo struct {
	// MinName is the minimum length for various name generation functions.
	MinName int
	// MaxName is the maximum length for various name generation functions.
	MaxName int
	// Domains is a set of domains used for generating fake urls or emails.
	Domains []string
}

Foo returns various random texts.

func NewFoo

func NewFoo() Foo

NewFoo returns a new Foo.

func (Foo) Bool

func (self Foo) Bool() bool

Bool returns a random bool.

func (Foo) EMail

func (self Foo) EMail() string

EMail returns a random email where name and domain name are randomly generated words and the domain will be one of configured domains.

func (Foo) Name

func (self Foo) Name() string

Name returns a random name.

type PairKey

type PairKey = string

PairKey is a recognized key in a set of key=value pairs parsed from a tag value.

Given:

tagKey  := "foo"
pairKey := "key1"
rawTag  := `json:"omitempty" foo:"key1,key2=value1,key2=value2,key3"`

pairKey specifies the "key1" inside a value keyed by tagKey.

type StringValueGetter

type StringValueGetter interface {
	Get() string
}

StringValueGetter is an interface which can return self as string.

type StringValueSetter

type StringValueSetter interface {
	Set(string) error
}

StringValueSetter is an interface which can convert a string to self.

type Tag

type Tag struct {
	// TagKey is the name of the tag whose value is to be parsed into [Values].
	TagKey

	// Separator is the pair separator.
	//
	// Defaults to comma ",".
	Separator string

	// KnownPairKeys is a set of recognised pair keys found inside a value of
	// a tag.
	//
	// If it is an empty slice all keys or key=value pairs will be parsed.
	// If it is not an empty slice, unrecognised keys will be skipped silently
	// or an error will be thrown if [Tag.ErrorOnUnknownKey] is true.
	KnownPairKeys []PairKey

	// ErrorOnUnknownKey, if true will make parse functions throw an error if
	// an unrecognised tag is found and [Tag.Keys] is not an empty slice.
	//
	// Default: false
	ErrorOnUnknownKey bool

	// Raw is the raw tag value that was parsed.
	// Set after [Tag.Parse].
	Raw string

	// Values are the parsed values. Values are nil until [Tag.ParseDocs] or
	// [Tag.ParseStructTag] is called.
	Values
}

Tag parses value of a key inside a tag string literal into Values map.

Given:

tag := `json:"omitempty" MyTag:"key1,key2=value1,key2=value2,key3"`

Results in following Values structure:

	Values{
		"key1": nil,
		"key2": []string{
			"value1",
			"value2",
     }
		"key3": nil,
	}

The following rules, equal to how Go parses tags apply:

Keys may appear without values or in key=value format. Multiple keys or pairs are separated by a comma. Values may not contain commas or double quotes.

Leading and trailing space is trimmed from pair values. Specifying a pair with the same key multiple times adds values to an entry under key in parsed Values.

Specifying a PairKey without a value adds an entry without values in the Values map. Specifying a PairKey with an empty value multiple times is a no-op.

See Tag.Parse for details.

func (*Tag) Parse

func (self *Tag) Parse(tag string) (err error)

Parse parses a tag string literal into Values.

tag may be a backquoted string (for instance extracted from struct field type using reflect) in which case it is unquoted before parsing.

See Tag on details how the tag string is parsed.

type TagKey

type TagKey = string

TagKey names a key inside a tag string literal whose value is to be parsed into Values.

Given:

tagKey := "foo"
rawTag := `json:"omitempty" foo:"key1,key2=value1,key2=value2,key3"`

TagKey specifies the "foo" key inside a tag string literal.

type Values

type Values map[PairKey][]string

Values is a map of parsed key=value pairs from a tag value.

func (Values) Add

func (self Values) Add(key string, values ...string)

Add appends values to value slice under key.

If no values exist under key a new entry is added. If no values were specified target slice is unmodified. Initial value of an empty entry is a nil slice.

func (Values) Clear

func (self Values) Clear()

Clear clears any loaded values.

func (Values) Exists

func (self Values) Exists(key string) (exists bool)

Exists returns true if entry under key exists.

func (Values) ExistsNonEmpty

func (self Values) ExistsNonEmpty(key string) (exists bool)

Exists returns true if entry under key exists and has at least one value which is not empty.

func (Values) First

func (self Values) First(key string) (s string)

First returns the first value keyed under key. If entry not found or no values for entry found returns an empty string. Use Values.Exists to check if an entry exists.

func (Values) Set

func (self Values) Set(key string, out *string) (exists bool)

Set sets value of out to value under specified key and returns true. If key was not found or has no value out is not set and false is returned.

Jump to

Keyboard shortcuts

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