strutil

package
v1.0.0-beta.2 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2026 License: MIT Imports: 19 Imported by: 4 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

strutil

String helpers used across go-types: trimming that also removes zero-width characters and invalid UTF-8, rune-predicate filtering and splitting, transliteration and file-name sanitization, snake case, line endings, domain extraction, HTML entities, a string set, a per-key mutex and random strings. Use it when the standard strings package leaves invisible runes in user input or you need one of the small helpers the other packages of this module are built on.

import "github.com/domonda/go-types/strutil"

The subpackage stringfrom formats pointers and other values as strings with a default for nil.

Trim and truncate

TrimSpace removes more than strings.TrimSpace: any Unicode whitespace, every non-printable rune (control, format, surrogate, private use and unassigned runes, including the zero-width characters \u200b, \u200c, \u200d, \u2060 and the BOM \ufeff), every byte that is not valid UTF-8, and the replacement character \ufffd.

Function Description
TrimSpace[S ~string](s S) S Remove leading and trailing trimmable runes (see above). ASCII-only input takes a fast path.
TrimSpaceBytes(s []byte) []byte Same for []byte, returns a subslice of s.
CutTrimSpace[S ~string](s, sep S) (before, after S, found bool) strings.Cut with both halves trimmed. If sep is missing it returns s untrimmed, "", false.
Truncate[S ~string](s S, maxLen int) S First maxLen runes of s, never splitting a rune. maxLen <= 0 gives "".
TruncateTrimSpace[S ~string](s S, maxLen int) S Truncate, then TrimSpace.
TruncateWithEllipsis[S ~string](s S, maxLenInclEllipsis int) S Truncate and append … so the result has at most maxLenInclEllipsis runes. <= 0 gives "".
IsSpace(r rune) bool unicode.IsSpace(r) or \u200b. Narrower than the TrimSpace predicate: \ufeff and \u200c are not spaces.

Rune predicates and filters

Identifier Description
IsRuneFunc func(rune) bool, the predicate type used by all functions below.
IsRune(runes ...rune) IsRuneFunc True for any of runes. Without arguments always false.
IsRuneInverse(isRune IsRuneFunc) IsRuneFunc Negates isRune.
IsRuneAll(isRune ...IsRuneFunc) IsRuneFunc True if all functions are true. Without arguments always true.
IsRuneAny(isRune ...IsRuneFunc) IsRuneFunc True if any function is true. Without arguments always false.
IsWordSeparator(r rune) bool Unicode space, punctuation, mark or symbol. '-', '_', '€' and combining marks are separators, 'ä' is not.
IsNorLetterOrDigit(r rune) bool Neither a letter nor a digit.
RemoveRunes(str []byte, removeRunes ...IsRuneFunc) []byte New slice without the runes where any function is true.
KeepRunes(str []byte, keepRunes ...IsRuneFunc) []byte New slice with only the runes where any function is true.
RemoveRunesString(str string, removeRunes ...IsRuneFunc) string String variant of RemoveRunes. Returns str itself if no rune was removed and str is valid UTF-8.
KeepRunesString(str string, keepRunes ...IsRuneFunc) string String variant of KeepRunes.
MapRuneIsAfterWordSeparator(str string) []bool One entry per byte of str: true if the rune at that byte follows an IsWordSeparator rune. All bytes of a multi-byte rune share the value, the first rune counts as following a separator.

The four filter functions pass every invalid UTF-8 byte to the predicates as utf8.RuneError and write it as \ufffd if it is kept, so the byte and string variants return the same result.

Splitting

Function Description
SplitAndTrimIndex(str []byte, isSplitRune, isTrimRune IsRuneFunc) [][]int Split str at runes where isSplitRune is true, trim isTrimRune runes from both ends of each word, and return the [start, end) byte offsets of the words that are not empty after trimming.

vat.IDFinder and money.AmountFinder use SplitAndTrimIndex to cut text into candidate words. The bank and date finders scan the text with their own logic.

Strings and pointers

Function Description
DerefPtr(ptr *string) string *ptr, or "" for nil.
StringToPtrEmptyToNil(str string) *string nil for "", else a pointer to a copy of str.
EmptyStringToNil(str string) any Untyped nil for "", else str. Useful as SQL argument when "" should be stored as NULL.
EqualPtrOrString(a, b *string) bool Same pointer, or both non-nil and pointing to equal strings. nil and a pointer to "" are not equal.
IndexInStrings(str string, slice []string) int Index of the first element equal to str, or -1.
Join[T ~string](elems []T, sep string) string strings.Join for any string type.
CompareStringsShorterFirst[T ~string](a, b T) int Compare by byte length first, then lexicographically. Usable with slices.SortFunc.
ConvertSlice[T, S ~string](s []S) []T Reinterpret []S as []T through unsafe.Pointer. No copy: the result shares its elements with s.
StringContainsAny(str string, subStrings []string) bool str contains any of subStrings. An empty element always matches.
SubStringIn(subString string, strs []string) bool Any of strs contains subString.
EqualJSON(a, b any) bool a == b for comparable values, otherwise equal json.Marshal output. 1 and 1.0 are equal, 1 and "1" are not. False if marshalling fails, true for two nils.

Case and line endings

Function Description
ToSnakeCase(s string) string Lower-case s, insert _ before an upper-case rune that follows a rune that is neither upper case nor replaced, and replace space, punctuation and symbol runes with _. A run of capitals stays one word: "MyHTTPRequest" gives "my_httprequest", "getURL" gives "get_url".
SanitizeLineEndings(text string) string Collapse "\r\n", "\n\r" and "\r" to "\n" in one pass, so "\r\n\r" becomes one "\n" and "\r\n\r\n" two. Returns text unchanged if it has no '\r'.
SanitizeLineEndingsBytes(text []byte) []byte Same for []byte. Returns text itself if it has no '\r', otherwise a new slice.

Transliteration and file names

Function Description
TransliterateSpecialCharacters(str string) string Replace 71 special Latin letters and ligatures with ASCII, like "ö" to "oe", "Æ" to "AE", "ß" to "ss". Drops invalid UTF-8 and \ufffd. Other runes pass through, so "Łódź" gives "Lodź".
TransliterateSpecialCharactersMaxLen(str string, maxLen int) string Same, stopping at maxLen output runes. A transliteration that starts below the limit is written completely, so ("Ä", 1) gives "Ae". Negative maxLen means no limit, 0 gives "".
SanitizeFileName(name string) string ASCII file name from arbitrary input, see below. Never returns "".
MakeValidFileName(name string) string Only trims and replaces \ / : * " < > |, newline, carriage return and tab with _; at the start and end of the name they are removed. Keeps spaces and non-ASCII runes. Returns "_" for an empty result. Not a sanitizer: ".." and NUL bytes pass unchanged, use SanitizeFileName for untrusted names.
NormalizeExt(ext string) string Lower-case the extension and map .jpg to .jpeg, .tif to .tiff, "." to "". Other runes are replaced like in SanitizeFileName.

SanitizeFileName applies these steps:

  1. Trim with TrimSpace.
  2. URL-unescape with url.QueryUnescape if the name contains % or +, so + becomes a space.
  3. Split off the extension (path.Ext) and normalize it with NormalizeExt.
  4. Transliterate with the TransliterateSpecialCharacters table, keep ASCII letters, digits, - and _.
  5. Replace whitespace with _ and every other rune with -, but not at the start and only once per run of replaced runes.
Input SanitizeFileName
"Mein Foto (1).JPG" "Mein_Foto_1-.jpeg"
" Über/Größe:*.tif " "Ueber-Groesse-.tiff"
"a+b.pdf" "a_b.pdf"
"100%25.txt" "100-.txt"
"x.Tar.GZ" "x-Tar.gz"
"..." "_"

Domain names

Function Description
ParseDomainName(word string) string Lower-cased domain of an http:// or https:// URL, a www. host, or an email address. "" if word is none of these.
ParseDomainNameIndex(word string) (domain string, indices []int) Same, plus the [start, end) byte offsets of the domain in word itself, not in its lower-cased copy. nil offsets if nothing matched.

The patterns are anchored, so word must be exactly one URL, host or address. Only these top-level domains are recognized: com net org edu gov mil de at eu ch es nl uk cz dk fi.

Input ParseDomainName Why
"HTTPS://Sub.Example.COM/Path" "sub.example.com" URL hosts may contain more dots
"www.example.org/y" "www.example.org"
"user@example.de" "example.de"
"example.com" "" no scheme, www. or @
"https://example.com:8080/" "" ports are not matched
"www.sub.example.com" "" no more dots after www.
"user@mail.example.com" "" no more dots after @
"https://example.io" "" TLD not in the list
"see https://example.com" "" not a single word

HTML entities

Function Description
HTMLEscapeSpecialRunes(str string) string Replace & and 238 other runes (accented letters, Greek letters, typographic quotes and dashes, math symbols, arrows, currency signs, \u00a0) with named entities, like ä to &auml; and € to &euro;.

The result is not safe for untrusted input: <, >, " and ' are not escaped. html.UnescapeString restores the input, except that \u2006 (six-per-em space) is written as &nbsp; and comes back as \u00a0.

StringSet

StringSet is map[string]struct{}. Its methods mirror types.Set[T] and the abstract set interface of the Go collections proposal (go.dev/issue/80590) and delegate to mapset.

Identifier Description
NewStringSet(strings ...string) StringSet New set with the passed strings.
NewStringSetMergeSlices(slices ...[]string) StringSet New set with the strings of all slices.
Len() int Number of strings.
IsEmpty() bool True for an empty or nil set.
Contains(str string) bool str is in the set.
ContainsAny(strs ...string) bool Any of strs is in the set. False without arguments.
ContainsAll(seq iter.Seq[string]) bool Every string of seq is in the set. True for an empty seq.
StringContainsAnyOfSet(str string) bool str contains any element as a substring. An element "" always matches.
All() iter.Seq[string] Iterate in undefined order.
Sorted() []string Sorted slice, nil for an empty or nil set.
String() string Sorted and quoted, like ["a", "b"]. [] for an empty or nil set.
Equal(other StringSet) bool Same strings. A nil set equals an empty one.
Intersects(other StringSet) bool At least one string in common.
Clone() StringSet Copy of the map, nil for nil.
Insert(str string) bool Add str, report whether the set changed.
InsertAll(seq iter.Seq[string]) bool Add all strings of seq, report whether the set changed.
Delete(str string) bool Remove str, report whether the set changed.
DeleteAll(seq iter.Seq[string]) bool Remove all strings of seq, report whether the set changed.
DeleteFunc(del func(string) bool) bool Remove the strings where del is true, report whether the set changed.
Clear() Remove all strings.
Union(other StringSet) StringSet New set with the strings of both.
Intersection(other StringSet) StringSet New set with the strings in both.
Difference(other StringSet) StringSet New set with the strings of set that are not in other.
SymmetricDifference(other StringSet) StringSet New set with the strings in exactly one of the two. This was called Diff before.
UnionWith(other StringSet) In-place Union.
IntersectionWith(other StringSet) In-place Intersection.
DifferenceWith(other StringSet) In-place Difference.
SymmetricDifferenceWith(other StringSet) In-place SymmetricDifference.

Implements: fmt.Stringer. A nil StringSet is a valid empty set for every method except Insert, InsertAll, UnionWith and SymmetricDifferenceWith, which panic like an assignment to a nil map when they have to add a string. The methods returning a new set never return nil.

StrMutex

StrMutex holds one mutex per string key. A key's mutex is created by the first Lock and deleted when no goroutine holds or waits for it, so memory grows with the number of keys in use at the same time, not with all keys ever locked.

Identifier Description
NewStrMutex() *StrMutex New mutex. The zero value is usable too.
Lock(key string) Block until key is free, then lock it.
Unlock(key string) Unlock key. Panics with Unlock called for non locked key: "k" if key is not locked.

types.KeyMutex[T] implements the same algorithm for any comparable key and also has IsLocked. uu.IDMutex does the same for uu.ID keys and adds optional lock callbacks. New code can use types.KeyMutex[string].

Random strings

Function Description
RandomString(length int) string length characters from the URL-safe base64 alphabet (A-Z a-z 0-9 - _), 6 random bits each, read from crypto/rand. Panics if length is negative.
RandomStringBytes(length int) []byte Same as []byte, saving the string copy.

Serialization

StringSet has no JSON, text or SQL methods, so encoding/json treats it as a plain map:

Go value json.Marshal String()
StringSet(nil) null []
StringSet{} {} []
NewStringSet("b", "a") {"a":{},"b":{}} ["a", "b"]

json.Unmarshal only accepts the object form and adds its keys to an existing map. A JSON array is an error. There is no sql.Scanner or driver.Valuer. Use types.Set[string] if you need a JSON array with null for nil.

Gotchas

  • IsSpace and TrimSpace disagree: IsSpace('\ufeff') is false, but TrimSpace removes the BOM. TrimSpace also removes a valid \ufffd, and TransliterateSpecialCharacters drops every \ufffd, not only leading and trailing ones.
  • CutTrimSpace(" a ", ":") returns " a ", "", false. The input is only trimmed when sep is found.
  • Truncate and TruncateWithEllipsis count runes, not bytes: Truncate("Größe", 3) is "Grö", which is 4 bytes.
  • ToSnakeCase does not split acronyms ("HTMLHandler" gives "htmlhandler") and keeps repeated separators ("hello world" gives "hello__world").
  • TransliterateSpecialCharactersMaxLen can return one rune more than maxLen, and neither transliteration function guarantees ASCII output.
  • SanitizeFileName URL-unescapes its input, so a literal + becomes _ and %25 becomes % and then -. It also renames .JPG to .jpeg.
  • HTMLEscapeSpecialRunes is not an XSS filter. Do not chain it with html.EscapeString either: running html.EscapeString on its output escapes the & of every entity again, so ä ends up as &amp;auml;.
  • ParseDomainName("example.com") is "": a bare domain without scheme, www. or @ is not recognized.
  • MapRuneIsAfterWordSeparator returns one value per byte, so index it with byte offsets, not rune counts.
  • StringContainsAny(s, []string{""}) and NewStringSet("").StringContainsAnyOfSet(s) are always true.
  • var s strutil.StringSet; s.Insert("a") panics. Create sets with NewStringSet or make.
  • ConvertSlice does not copy: the result and the input share their elements.
  • StrMutex is not reentrant. Locking a key again from the goroutine that holds it deadlocks.

Examples

Trimming and truncation:

package main

import (
	"fmt"

	"github.com/domonda/go-types/strutil"
)

func main() {
	fmt.Printf("%q\n", strutil.TrimSpace("\u200b\ufeff Hello \u00a0"))

	before, after, found := strutil.CutTrimSpace(" key : value ", ":")
	fmt.Printf("%q %q %v\n", before, after, found)
	before, after, found = strutil.CutTrimSpace(" no separator ", ":")
	fmt.Printf("%q %q %v\n", before, after, found)

	fmt.Println(strutil.Truncate("Größe", 3))
	fmt.Println(strutil.TruncateWithEllipsis("Hello World", 8))
	// Output:
	// "Hello"
	// "key" "value" true
	// " no separator " "" false
	// Grö
	// Hello W…
}

Names, file names and HTML entities:

package main

import (
	"fmt"

	"github.com/domonda/go-types/strutil"
)

func main() {
	fmt.Println(strutil.ToSnakeCase("MyHTTPRequest"))
	fmt.Println(strutil.ToSnakeCase("getURL"))
	fmt.Println(strutil.TransliterateSpecialCharacters("Größe Łódź"))
	fmt.Println(strutil.TransliterateSpecialCharactersMaxLen("Äpfel", 1))
	fmt.Println(strutil.SanitizeFileName("  Über/Größe:*.tif "))
	fmt.Println(strutil.SanitizeFileName("a+b.pdf"))
	fmt.Println(strutil.MakeValidFileName("Über Größe/2024.txt"))
	fmt.Println(strutil.HTMLEscapeSpecialRunes(`<b>Größe & "Maß"</b>`))
	// Output:
	// my_httprequest
	// get_url
	// Groesse Lodź
	// Ae
	// Ueber-Groesse-.tiff
	// a_b.pdf
	// Über Größe_2024.txt
	// <b>Gr&ouml;&szlig;e &amp; "Ma&szlig;"</b>
}

Splitting, domains, sets and the zero StrMutex:

package main

import (
	"encoding/json"
	"fmt"
	"unicode"

	"github.com/domonda/go-types/strutil"
)

func main() {
	text := []byte("Total: 1.234,56 EUR.")
	var words []string
	for _, pos := range strutil.SplitAndTrimIndex(text, unicode.IsSpace, strutil.IsRune('.', ',', ':')) {
		words = append(words, string(text[pos[0]:pos[1]]))
	}
	fmt.Printf("%q\n", words)

	domain, indices := strutil.ParseDomainNameIndex("Info@Domonda.COM")
	fmt.Println(domain, indices)
	fmt.Printf("%q\n", strutil.ParseDomainName("example.com"))

	set := strutil.NewStringSet("b", "a")
	fmt.Println(set.Insert("c"), set.Insert("c"))
	fmt.Println(set, set.Difference(strutil.NewStringSet("a")))
	j, _ := json.Marshal(set)
	fmt.Println(string(j))

	var locks strutil.StrMutex // usable without NewStrMutex
	locks.Lock("user-42")
	locks.Unlock("user-42")
	// Output:
	// ["Total" "1.234,56" "EUR"]
	// domonda.com [5 16]
	// ""
	// true false
	// ["a", "b", "c"] ["b", "c"]
	// {"a":{},"b":{},"c":{}}
}

Documentation

Overview

Package strutil provides string helpers used across the go-types module.

The main groups are:

The subpackage github.com/domonda/go-types/strutil/stringfrom formats pointers and other values as strings with a default for nil.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CompareStringsShorterFirst

func CompareStringsShorterFirst[T ~string](a, b T) int

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

func CutTrimSpace[S ~string](s, sep S) (before, after S, found bool)

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 DerefPtr

func DerefPtr(ptr *string) string

DerefPtr returns the string ptr points to or an empty string if ptr is nil.

func EmptyStringToNil

func EmptyStringToNil(str string) any

EmptyStringToNil returns str or nil if it is empty.

func EqualJSON

func EqualJSON(a, b any) bool

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

func EqualPtrOrString(a, b *string) bool

EqualPtrOrString returns if a and b are equal pointers or if the pointed to strings are equal

func HTMLEscapeSpecialRunes

func HTMLEscapeSpecialRunes(str string) string

HTMLEscapeSpecialRunes returns str with special Unicode characters replaced by their HTML entity equivalents (e.g., 'ä' becomes '&auml;'). 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

func IndexInStrings(str string, slice []string) int

IndexInStrings returns the index of where str can be found in slice, or -1 if it was not found.

func IsNorLetterOrDigit

func IsNorLetterOrDigit(r rune) bool

IsNorLetterOrDigit returns true if r is neither a letter nor a digit.

func IsSpace

func IsSpace(r rune) bool

IsSpace reports whether r is a space character as defined by Unicode or zero width space '\u200b'.

func IsWordSeparator

func IsWordSeparator(r rune) bool

IsWordSeparator returns true if r is a word separator character (space, punctuation, mark, or symbol).

func Join

func Join[T ~string](elems []T, sep string) string

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

func MakeValidFileName(name string) string

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

func MapRuneIsAfterWordSeparator(str string) []bool

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

func NormalizeExt(ext string) string

NormalizeExt normalizes a file extension by converting it to lowercase and applying common extension mappings (e.g., .tif -> .tiff, .jpg -> .jpeg).

func ParseDomainName

func ParseDomainName(word string) string

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

func ParseDomainNameIndex(word string) (domain string, indices []int)

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

func RandomString(length int) string

RandomString returns an URL compatible random string with the requested length.

func RandomStringBytes

func RandomStringBytes(length int) []byte

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

func SanitizeFileName(name string) string

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

func SanitizeLineEndings(text string) string

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

func SanitizeLineEndingsBytes(text []byte) []byte

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

func StringContainsAny(str string, subStrings []string) bool

StringContainsAny returns if str contains any of subStrings. An empty string in subStrings always matches.

func StringToPtrEmptyToNil

func StringToPtrEmptyToNil(str string) *string

StringToPtrEmptyToNil returns the address of a string or nil if the string is empty.

func SubStringIn

func SubStringIn(subString string, strs []string) bool

SubStringIn returns if subString is equal or a substring of any of strs.

func ToSnakeCase

func ToSnakeCase(s string) string

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

func TransliterateSpecialCharacters(str string) string

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

func TransliterateSpecialCharactersMaxLen(str string, maxLen int) string

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

func TrimSpaceBytes(s []byte) []byte

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

func Truncate[S ~string](s S, maxLen int) S

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

func TruncateTrimSpace[S ~string](s S, maxLen int) S

TruncateTrimSpace truncates s to maxLen runes and trims leading and trailing trimmable runes (see TrimSpace for the predicate).

func TruncateWithEllipsis

func TruncateWithEllipsis[S ~string](s S, maxLenInclEllipsis int) S

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

type IsRuneFunc func(rune) bool

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.

func NewStrMutex

func NewStrMutex() *StrMutex

NewStrMutex returns a new StrMutex

func (*StrMutex) Lock

func (m *StrMutex) Lock(key string)

Lock the mutex for a given key. The zero value of StrMutex is usable, it is initialized by the first Lock call.

func (*StrMutex) Unlock

func (m *StrMutex) Unlock(key string)

Unlock the mutex for a given key. It panics if the key is not locked.

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

func NewStringSet(strings ...string) StringSet

NewStringSet creates and returns a new StringSet containing the provided strings.

func NewStringSetMergeSlices

func NewStringSetMergeSlices(slices ...[]string) StringSet

NewStringSetMergeSlices creates and returns a new StringSet containing all unique strings from the provided slices.

func (StringSet) All

func (set StringSet) All() iter.Seq[string]

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) Clone

func (set StringSet) Clone() StringSet

Clone returns a copy of the set. Returns nil if the set is nil.

func (StringSet) Contains

func (set StringSet) Contains(str string) bool

Contains returns true if str is in the set. It is valid to call this method on a nil StringSet.

func (StringSet) ContainsAll

func (set StringSet) ContainsAll(seq iter.Seq[string]) bool

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

func (set StringSet) ContainsAny(strs ...string) bool

ContainsAny returns true if any of the provided strings are in the set.

func (StringSet) Delete

func (set StringSet) Delete(str string) bool

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

func (set StringSet) DeleteAll(seq iter.Seq[string]) bool

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

func (set StringSet) DeleteFunc(del func(string) bool) bool

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

func (set StringSet) Difference(other StringSet) StringSet

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

func (set StringSet) DifferenceWith(other StringSet)

DifferenceWith removes every string of other from set. It is valid to call this method on a nil StringSet.

func (StringSet) Equal

func (set StringSet) Equal(other StringSet) bool

Equal returns true if set and other contain exactly the same strings.

func (StringSet) Insert

func (set StringSet) Insert(str string) bool

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

func (set StringSet) InsertAll(seq iter.Seq[string]) bool

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

func (set StringSet) Intersection(other StringSet) StringSet

Intersection returns a new StringSet with the strings that are in both set and other.

func (StringSet) IntersectionWith

func (set StringSet) IntersectionWith(other StringSet)

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

func (set StringSet) Intersects(other StringSet) bool

Intersects reports whether set and other have at least one string in common.

func (StringSet) IsEmpty

func (set StringSet) IsEmpty() bool

IsEmpty returns true if the set is empty or nil.

func (StringSet) Len

func (set StringSet) Len() int

Len returns the number of strings in the set. It is valid to call this method on a nil StringSet.

func (StringSet) Sorted

func (set StringSet) Sorted() (s []string)

Sorted returns all strings in the set as a sorted slice. It returns nil for an empty or nil set.

func (StringSet) String

func (set StringSet) String() string

String implements the fmt.Stringer interface.

func (StringSet) StringContainsAnyOfSet

func (set StringSet) StringContainsAnyOfSet(str string) bool

StringContainsAnyOfSet returns true if the passed string contains any of the strings of the StringSet.

func (StringSet) SymmetricDifference

func (set StringSet) SymmetricDifference(other StringSet) StringSet

SymmetricDifference returns a new StringSet containing strings that are in either set but not in both.

func (StringSet) SymmetricDifferenceWith

func (set StringSet) SymmetricDifferenceWith(other StringSet)

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.

func (StringSet) Union

func (set StringSet) Union(other StringSet) StringSet

Union returns a new StringSet with all strings of set and other.

func (StringSet) UnionWith

func (set StringSet) UnionWith(other StringSet)

UnionWith adds all strings of other to set. It panics if set is nil and other has a string that is not already an element of set.

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.

Jump to

Keyboard shortcuts

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