Documentation
¶
Overview ¶
Package strutil provides string helpers used across the go-types module.
The main groups are:
- TrimSpace, TrimSpaceBytes, CutTrimSpace and the Truncate functions: trimming that also removes zero-width characters, the BOM, other non-printable runes and invalid UTF-8.
- IsRuneFunc predicates with RemoveRunes, KeepRunes and SplitAndTrimIndex, which vat.IDFinder and money.AmountFinder use to split text into candidate words.
- TransliterateSpecialCharacters, SanitizeFileName, MakeValidFileName and NormalizeExt for ASCII-friendly names and file names.
- ToSnakeCase, SanitizeLineEndings, EqualJSON and small string and pointer helpers.
- ParseDomainName for domains in URLs, www hosts and email addresses with a fixed list of top level domains.
- HTMLEscapeSpecialRunes, which replaces '&' and special runes like 'ä' or '€' with named HTML entities. It does not escape <, >, " or the apostrophe, so it is not a replacement for html.EscapeString.
- StringSet, a map based string set with the methods of the Go collections proposal, and StrMutex, a per-key mutex.
- RandomString for URL-safe random strings from crypto/rand.
The subpackage github.com/domonda/go-types/strutil/stringfrom formats pointers and other values as strings with a default for nil.
Index ¶
- func CompareStringsShorterFirst[T ~string](a, b T) int
- func ConvertSlice[T, S ~string](s []S) []T
- func CutTrimSpace[S ~string](s, sep S) (before, after S, found bool)
- func DerefPtr(ptr *string) string
- func EmptyStringToNil(str string) any
- func EqualJSON(a, b any) bool
- func EqualPtrOrString(a, b *string) bool
- func HTMLEscapeSpecialRunes(str string) string
- func IndexInStrings(str string, slice []string) int
- func IsNorLetterOrDigit(r rune) bool
- func IsSpace(r rune) bool
- func IsWordSeparator(r rune) bool
- func Join[T ~string](elems []T, sep string) string
- func KeepRunes(str []byte, keepRunes ...IsRuneFunc) []byte
- func KeepRunesString(str string, keepRunes ...IsRuneFunc) string
- func MakeValidFileName(name string) string
- func MapRuneIsAfterWordSeparator(str string) []bool
- func NormalizeExt(ext string) string
- func ParseDomainName(word string) string
- func ParseDomainNameIndex(word string) (domain string, indices []int)
- func RandomString(length int) string
- func RandomStringBytes(length int) []byte
- func RemoveRunes(str []byte, removeRunes ...IsRuneFunc) []byte
- func RemoveRunesString(str string, removeRunes ...IsRuneFunc) string
- func SanitizeFileName(name string) string
- func SanitizeLineEndings(text string) string
- func SanitizeLineEndingsBytes(text []byte) []byte
- func SplitAndTrimIndex(str []byte, isSplitRune, isTrimRune IsRuneFunc) (indices [][]int)
- func StringContainsAny(str string, subStrings []string) bool
- func StringToPtrEmptyToNil(str string) *string
- func SubStringIn(subString string, strs []string) bool
- func ToSnakeCase(s string) string
- func TransliterateSpecialCharacters(str string) string
- func TransliterateSpecialCharactersMaxLen(str string, maxLen int) string
- func TrimSpace[S ~string](s S) S
- func TrimSpaceBytes(s []byte) []byte
- func Truncate[S ~string](s S, maxLen int) S
- func TruncateTrimSpace[S ~string](s S, maxLen int) S
- func TruncateWithEllipsis[S ~string](s S, maxLenInclEllipsis int) S
- type IsRuneFunc
- type StrMutex
- type StringSet
- func (set StringSet) All() iter.Seq[string]
- func (set StringSet) Clear()
- func (set StringSet) Clone() StringSet
- func (set StringSet) Contains(str string) bool
- func (set StringSet) ContainsAll(seq iter.Seq[string]) bool
- func (set StringSet) ContainsAny(strs ...string) bool
- func (set StringSet) Delete(str string) bool
- func (set StringSet) DeleteAll(seq iter.Seq[string]) bool
- func (set StringSet) DeleteFunc(del func(string) bool) bool
- func (set StringSet) Difference(other StringSet) StringSet
- func (set StringSet) DifferenceWith(other StringSet)
- func (set StringSet) Equal(other StringSet) bool
- func (set StringSet) Insert(str string) bool
- func (set StringSet) InsertAll(seq iter.Seq[string]) bool
- func (set StringSet) Intersection(other StringSet) StringSet
- func (set StringSet) IntersectionWith(other StringSet)
- func (set StringSet) Intersects(other StringSet) bool
- func (set StringSet) IsEmpty() bool
- func (set StringSet) Len() int
- func (set StringSet) Sorted() (s []string)
- func (set StringSet) String() string
- func (set StringSet) StringContainsAnyOfSet(str string) bool
- func (set StringSet) SymmetricDifference(other StringSet) StringSet
- func (set StringSet) SymmetricDifferenceWith(other StringSet)
- func (set StringSet) Union(other StringSet) StringSet
- func (set StringSet) UnionWith(other StringSet)
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CompareStringsShorterFirst ¶
CompareStringsShorterFirst compares two strings by length first and then by lexicographical order.
func ConvertSlice ¶
func ConvertSlice[T, S ~string](s []S) []T
ConvertSlice converts a slice of one string type to another string type. It does this by reinterpreting the slice's underlying memory using unsafe.Pointer, so the result shares its elements with s instead of being a copy.
func CutTrimSpace ¶
CutTrimSpace slices s around the first instance of sep, returning the text before and after sep with all leading and trailing trimmable runes removed (see TrimSpace for the predicate). The found result reports whether sep appears in s. If sep does not appear in s, CutTrimSpace returns s untrimmed, "", false.
func EmptyStringToNil ¶
EmptyStringToNil returns str or nil if it is empty.
func EqualJSON ¶
EqualJSON returns true if a and b are equal on a value basis, or if their marshalled JSON representation is equal. Values of uncomparable types like slices and maps are only compared by their JSON representation.
func EqualPtrOrString ¶
EqualPtrOrString returns if a and b are equal pointers or if the pointed to strings are equal
func HTMLEscapeSpecialRunes ¶
HTMLEscapeSpecialRunes returns str with special Unicode characters replaced by their HTML entity equivalents (e.g., 'ä' becomes 'ä'). The only escaped ASCII character is '&'. The characters <, >, " and the apostrophe are not escaped, so the result is not safe to embed untrusted text in HTML; use html.EscapeString or html/template for that.
func IndexInStrings ¶
IndexInStrings returns the index of where str can be found in slice, or -1 if it was not found.
func IsNorLetterOrDigit ¶
IsNorLetterOrDigit returns true if r is neither a letter nor a digit.
func IsSpace ¶
IsSpace reports whether r is a space character as defined by Unicode or zero width space '\u200b'.
func IsWordSeparator ¶
IsWordSeparator returns true if r is a word separator character (space, punctuation, mark, or symbol).
func Join ¶
Join concatenates the elements of its first argument to create a single string. The separator string sep is placed between elements in the resulting string.
func KeepRunes ¶
func KeepRunes(str []byte, keepRunes ...IsRuneFunc) []byte
KeepRunes returns a copy of str with only those runes kept where any call to a keepRunes function returns true. Like ranging over a string, every invalid UTF-8 byte is passed to the functions as utf8.RuneError and written as U+FFFD if kept.
func KeepRunesString ¶
func KeepRunesString(str string, keepRunes ...IsRuneFunc) string
KeepRunesString returns a copy of str with only those runes kept where any call to a keepRunes function returns true. Like KeepRunes, every invalid UTF-8 byte is passed to the functions as utf8.RuneError and written as U+FFFD if kept.
func MakeValidFileName ¶
MakeValidFileName trims name with TrimSpace and replaces the characters \ / : * " < > | and newline, carriage return and tab with '_'. These characters are removed instead at the start and end of the name, and an empty result is returned as "_". See also SanitizeFileName that does more than just replacing characters.
func MapRuneIsAfterWordSeparator ¶
MapRuneIsAfterWordSeparator returns a boolean slice indicating for each byte position in str whether that position comes after a word separator character (see IsWordSeparator). All bytes of a multi-byte rune get the same value, and the first rune counts as coming after a separator.
func NormalizeExt ¶
NormalizeExt normalizes a file extension by converting it to lowercase and applying common extension mappings (e.g., .tif -> .tiff, .jpg -> .jpeg).
func ParseDomainName ¶
ParseDomainName extracts and returns a domain name from word. It recognizes domains in HTTP URLs, www prefixed domains, and email addresses. Returns an empty string if no domain is found.
func ParseDomainNameIndex ¶
ParseDomainNameIndex extracts a domain name from word and returns both the lowercase domain and the byte indices [start, end) where the domain was found in word. It recognizes domains in HTTP URLs, www prefixed domains, and email addresses. Returns empty string and nil indices if no domain is found.
func RandomString ¶
RandomString returns an URL compatible random string with the requested length.
func RandomStringBytes ¶
RandomStringBytes returns an URL compatible random string with the requested length as []byte slice, saving a string copy compared to RandomString. It panics if length is negative.
func RemoveRunes ¶
func RemoveRunes(str []byte, removeRunes ...IsRuneFunc) []byte
RemoveRunes returns a copy of str with all runes removed where any call to a removeRunes function returns true. Like ranging over a string, every invalid UTF-8 byte is passed to the functions as utf8.RuneError and written as U+FFFD if kept.
func RemoveRunesString ¶
func RemoveRunesString(str string, removeRunes ...IsRuneFunc) string
RemoveRunesString returns a copy of str with all runes removed where any call to a removeRunes function returns true. Like RemoveRunes, every invalid UTF-8 byte is passed to the functions as utf8.RuneError and written as U+FFFD if kept. If no rune was removed and str is valid UTF-8, the string is not copied.
func SanitizeFileName ¶
SanitizeFileName creates a nice sane filename. It does more than just replacing invalid characters:
- trims name with TrimSpace,
- URL-unescapes name if it contains '%' or '+', so "a+b" becomes "a b",
- normalizes the extension with NormalizeExt,
- transliterates the special characters of TransliterateSpecialCharacters,
- keeps ASCII letters, digits, '-' and '_',
- replaces whitespace with '_' and every other rune with '-', not at the start and only once per run of replaced runes.
Never returns an empty string.
func SanitizeLineEndings ¶
SanitizeLineEndings normalizes all line endings in text to '\n' in a single pass and returns the result.
The following byte sequences are collapsed to a single '\n':
- "\r\n" (Windows / DOS)
- "\n\r" (rare, e.g. Acorn / RISC OS, or as the trailing half of "\r\n\r")
- "\r" (classic Mac OS)
A bare '\n' (Unix) is preserved as-is. If text contains no '\r', it is returned unchanged without allocating.
The exact pairings match three successive non-overlapping replacements of "\r\n", then "\n\r", then "\r" — so for example "\r\n\r" collapses to a single "\n", while "\r\n\r\n" yields "\n\n".
func SanitizeLineEndingsBytes ¶
SanitizeLineEndingsBytes normalizes all line endings in text to '\n' in a single pass and returns the result.
The following byte sequences are collapsed to a single '\n':
- "\r\n" (Windows / DOS)
- "\n\r" (rare, e.g. Acorn / RISC OS, or as the trailing half of "\r\n\r")
- "\r" (classic Mac OS)
A bare '\n' (Unix) is preserved as-is. If text contains no '\r', the original slice is returned unchanged without allocating; otherwise a freshly allocated slice is returned and text is not modified.
The exact pairings match three successive non-overlapping replacements of "\r\n", then "\n\r", then "\r" — so for example "\r\n\r" collapses to a single "\n", while "\r\n\r\n" yields "\n\n".
func SplitAndTrimIndex ¶
func SplitAndTrimIndex(str []byte, isSplitRune, isTrimRune IsRuneFunc) (indices [][]int)
SplitAndTrimIndex first splits str into words not containing isSplitRune, then trims the words with isTrimRune. It returns the [start, end) byte index pairs of the trimmed words, words consisting only of trim runes are dropped. Like ranging over a string, every invalid UTF-8 byte is passed to the functions as utf8.RuneError.
func StringContainsAny ¶
StringContainsAny returns if str contains any of subStrings. An empty string in subStrings always matches.
func StringToPtrEmptyToNil ¶
StringToPtrEmptyToNil returns the address of a string or nil if the string is empty.
func SubStringIn ¶
SubStringIn returns if subString is equal or a substring of any of strs.
func ToSnakeCase ¶
ToSnakeCase converts s to snake case by lower casing everything and inserting '_' before every upper case character that follows a character that is neither upper case nor replaced by '_'. A run of upper case characters is not split into words, so "MyHTTPRequest" becomes "my_httprequest". Whitespace, symbol, and punctuation characters will be replaced by '_'.
func TransliterateSpecialCharacters ¶
TransliterateSpecialCharacters returns the string sanitized as valid UTF-8 with common European special characters transliterated to single or multiple ANSI characters. Invalid UTF-8 bytes and U+FFFD runes are dropped. Runes without a transliteration, like 'ź' or '€', are kept, so the result is not guaranteed to be ASCII.
func TransliterateSpecialCharactersMaxLen ¶
TransliterateSpecialCharactersMaxLen returns the string sanitized as valid UTF-8 with common European special characters transliterated to single or multiple ANSI characters, like TransliterateSpecialCharacters.
The maxLen argument limits the number of runes returned. A transliteration that starts below the limit is written completely, so the result can be one rune longer: "Ä" with maxLen 1 returns "Ae". A negative value means no limit, zero returns an empty string.
func TrimSpace ¶
func TrimSpace[S ~string](s S) S
TrimSpace returns a slice of the string s with all leading and trailing trimmable runes removed: any Unicode whitespace, any non-printable rune (including zero-width characters and the BOM), and any byte that does not decode as valid UTF-8. A valid U+FFFD replacement character is trimmed too, because it can't be told apart from invalid UTF-8.
func TrimSpaceBytes ¶
TrimSpaceBytes returns a slice of the bytes string s with all leading and trailing trimmable runes removed: any Unicode whitespace, any non-printable rune (including zero-width characters and the BOM), and any byte that does not decode as valid UTF-8. A valid U+FFFD replacement character is trimmed too, because it can't be told apart from invalid UTF-8.
func Truncate ¶
Truncate returns a truncated version of s with at most maxLen runes. If s has more than maxLen runes, it returns the first maxLen runes. The truncation is UTF-8 aware and will not split multi-byte characters.
func TruncateTrimSpace ¶
TruncateTrimSpace truncates s to maxLen runes and trims leading and trailing trimmable runes (see TrimSpace for the predicate).
func TruncateWithEllipsis ¶
TruncateWithEllipsis truncates s to maxLenInclEllipsis runes, appending an ellipsis (…) if truncated. The returned string will have at most maxLenInclEllipsis runes including the ellipsis. If maxLenInclEllipsis is 0 or negative, returns an empty string.
Types ¶
type IsRuneFunc ¶
IsRuneFunc is a function pointer for specifying if a rune matches a criteria.
func IsRune ¶
func IsRune(runes ...rune) IsRuneFunc
IsRune returns an IsRuneFunc that returns true if the tested rune matches any of the provided runes.
func IsRuneAll ¶
func IsRuneAll(isRune ...IsRuneFunc) IsRuneFunc
IsRuneAll returns an IsRuneFunc that returns true only if all provided isRune functions return true for the tested rune.
func IsRuneAny ¶
func IsRuneAny(isRune ...IsRuneFunc) IsRuneFunc
IsRuneAny returns an IsRuneFunc that returns true if any of the provided isRune functions return true for the tested rune.
func IsRuneInverse ¶
func IsRuneInverse(isRune IsRuneFunc) IsRuneFunc
IsRuneInverse returns an IsRuneFunc that inverts the result of the provided isRune function.
type StrMutex ¶
type StrMutex struct {
// contains filtered or unexported fields
}
StrMutex manages a unique mutex for every locked string key. The mutex for a key exists as long as there are any locks waiting to be unlocked. This is equivalent to declaring a mutex variable for every key, except that the key and the number of mutexes are dynamic. Like a sync.Mutex it is not reentrant, locking a key again from the goroutine holding it deadlocks.
type StringSet ¶
type StringSet map[string]struct{}
StringSet is a set of unique strings implemented as a map. It has no JSON or SQL methods, so encoding/json encodes it like any map as an object, for example {"a":{}}.
func NewStringSet ¶
NewStringSet creates and returns a new StringSet containing the provided strings.
func NewStringSetMergeSlices ¶
NewStringSetMergeSlices creates and returns a new StringSet containing all unique strings from the provided slices.
func (StringSet) All ¶
All returns an iterator over the strings of the set in undefined order. It is valid to call this method on a nil StringSet.
func (StringSet) Clear ¶
func (set StringSet) Clear()
Clear removes all strings from the set. It is valid to call this method on a nil StringSet.
func (StringSet) Contains ¶
Contains returns true if str is in the set. It is valid to call this method on a nil StringSet.
func (StringSet) ContainsAll ¶
ContainsAll reports whether the set contains all strings yielded by seq. It returns true for an empty sequence and is valid to call on a nil StringSet.
func (StringSet) ContainsAny ¶
ContainsAny returns true if any of the provided strings are in the set.
func (StringSet) Delete ¶
Delete removes str from the set and reports whether the set was changed. It is valid to call this method on a nil StringSet.
func (StringSet) DeleteAll ¶
DeleteAll removes all strings yielded by seq from the set and reports whether the set was changed. It is valid to call this method on a nil StringSet.
func (StringSet) DeleteFunc ¶
DeleteFunc removes every string for which del returns true and reports whether the set was changed. It is valid to call this method on a nil StringSet.
func (StringSet) Difference ¶
Difference returns a new StringSet with the strings of set that are not in other.
This replaces the former Diff method, which returned the symmetric difference and is now StringSet.SymmetricDifference.
func (StringSet) DifferenceWith ¶
DifferenceWith removes every string of other from set. It is valid to call this method on a nil StringSet.
func (StringSet) Insert ¶
Insert adds str to the set and reports whether the set was changed. It panics if the set is nil and str is not already an element.
func (StringSet) InsertAll ¶
InsertAll adds all strings yielded by seq to the set and reports whether the set was changed. It panics if the set is nil and seq yields a string that is not already an element.
func (StringSet) Intersection ¶
Intersection returns a new StringSet with the strings that are in both set and other.
func (StringSet) IntersectionWith ¶
IntersectionWith removes every string from set that is not also in other. It is valid to call this method on a nil StringSet.
func (StringSet) Intersects ¶
Intersects reports whether set and other have at least one string in common.
func (StringSet) Len ¶
Len returns the number of strings in the set. It is valid to call this method on a nil StringSet.
func (StringSet) Sorted ¶
Sorted returns all strings in the set as a sorted slice. It returns nil for an empty or nil set.
func (StringSet) StringContainsAnyOfSet ¶
StringContainsAnyOfSet returns true if the passed string contains any of the strings of the StringSet.
func (StringSet) SymmetricDifference ¶
SymmetricDifference returns a new StringSet containing strings that are in either set but not in both.
func (StringSet) SymmetricDifferenceWith ¶
SymmetricDifferenceWith replaces the strings of set with the strings that are in exactly one of set and other. It panics if set is nil and other has a string that is not already an element of set.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package stringfrom provides utilities for converting various Go types to strings with safe handling of nil pointers and customizable default values.
|
Package stringfrom provides utilities for converting various Go types to strings with safe handling of nil pointers and customizable default values. |