Documentation
¶
Overview ¶
Example (StringPointerBasic) ¶
Estos ejemplos ilustran cómo usar los punteros a strings para evitar asignaciones adicionales
// Creamos una variable string que queremos modificar myText := "héllô wórld" // En lugar de crear una nueva variable con el resultado, // modificamos directamente la variable original usando Apply() Convert(&myText).Tilde().ToLower().Apply() // La variable original ha sido modificada std_fmt.Println(myText)
Output: hello world
Example (StringPointerCamelCase) ¶
// Ejemplo de uso con múltiples transformaciones originalText := "Él Múrcielago Rápido" // Las transformaciones modifican la variable original directamente // usando el método Apply() para actualizar el puntero Convert(&originalText).Tilde().CamelLow().Apply() std_fmt.Println(originalText)
Output: elMurcielagoRapido
Example (StringPointerEfficiency) ¶
// En aplicaciones de alto rendimiento, reducir asignaciones de memoria // puede ser importante para evitar la presión sobre el garbage collector // Método tradicional (crea nuevas asignaciones de memoria) traditionalText := "Texto con ACENTOS" processedText := Convert(traditionalText).Tilde().ToLower().String() std_fmt.Println(processedText) // Método con punteros (modifica directamente la variable original) directText := "Otro TEXTO con ACENTOS" Convert(&directText).Tilde().ToLower().Apply() std_fmt.Println(directText)
Output: texto con acentos otro texto con acentos
Index ¶
- Variables
- func Contains(Conv, search string) bool
- func Count(Conv, search string) int
- func ErrType(cause, sentinel error) error
- func Fprintf(w io.Writer, format string, args ...any) (n int, err error)
- func GetPathBase() string
- func HasPrefix(conv, prefix string) bool
- func HasSuffix(conv, suffix string) bool
- func HasUpperPrefix(s string) bool
- func IDorPrimaryKey(tableName, fieldName string) (isID, isPK bool)
- func Index(s, substr string) int
- func IsWordSeparator(input any) bool
- func IsWordSeparatorChar(r rune) bool
- func IsZero(v any) bool
- func JSONEscape(s string, b *Builder)
- func JoinSlice(elems []string, sep string) string
- func LastIndex(s, substr string) int
- func Matches(content string, terms ...string) bool
- func MatchesAny(content string, terms ...string) bool
- func PathRelativeTo(path, base string) string
- func Printf(format string, args ...any)
- func Println(args ...any)
- func Repeat(s string, count int) string
- func ReplaceAll(s, old, new string) string
- func ReplaceN(s, old, new string, n int) string
- func SetPathBase(base string)
- func SetTranslator(fn func(word string) (string, bool))
- func Split(s string, separator ...string) []string
- func Sprint(v any) string
- func Sprintf(format string, args ...any) string
- func Sscanf(src string, format string, args ...any) (n int, err error)
- func ToLower(s string) string
- func ToUpper(s string) string
- func TrimPrefix(s, prefix string) string
- func TrimSpace(s string) string
- func TrimSuffix(s, suffix string) string
- type BuffDest
- type Builder
- type Conv
- func (c *Conv) AnyToBuff(dest BuffDest, value any)
- func (t *Conv) Apply()
- func (c *Conv) Bool() (bool, error)
- func (c *Conv) Bytes() []byte
- func (t *Conv) CamelLow() *Conv
- func (t *Conv) CamelUp() *Conv
- func (t *Conv) Capitalize() *Conv
- func (c *Conv) Error() string
- func (c *Conv) EscapeAttr() string
- func (c *Conv) EscapeHTML() string
- func (c *Conv) ExtractValue(delimiters ...string) (string, error)
- func (c *Conv) Float32() (float32, error)
- func (c *Conv) Float64() (float64, error)
- func (c *Conv) GetBytes(dest BuffDest) []byte
- func (c *Conv) GetKind() Kind
- func (c *Conv) GetString(dest BuffDest) string
- func (c *Conv) GetStringZeroCopy(dest BuffDest) string
- func (c *Conv) Int(base ...int) (int, error)
- func (c *Conv) Int32(base ...int) (int32, error)
- func (c *Conv) Int64(base ...int) (int64, error)
- func (c *Conv) Join(sep ...string) *Conv
- func (c *Conv) LoadBytes(b []byte)
- func (c *Conv) PathBase() *Conv
- func (c *Conv) PathExt() *Conv
- func (c *Conv) PathShort() *Conv
- func (c *Conv) PutConv()
- func (c *Conv) Quote() *Conv
- func (t *Conv) Repeat(n int) *Conv
- func (c *Conv) Replace(oldAny, newAny any, n ...int) *Conv
- func (c *Conv) Reset() *Conv
- func (c *Conv) ResetBuffer(dest BuffDest)
- func (t *Conv) Round(decimals int, down ...bool) *Conv
- func (t *Conv) SnakeLow(sep ...string) *Conv
- func (t *Conv) SnakeUp(sep ...string) *Conv
- func (c *Conv) Split(separator ...string) []string
- func (c *Conv) String() string
- func (c *Conv) StringErr() (out string, err error)
- func (c *Conv) StringType() (string, MessageType)
- func (c *Conv) TagPairs(key string) []KeyValue
- func (c *Conv) TagValue(key string) (string, bool)
- func (t *Conv) Thousands(anglo ...bool) *Conv
- func (t *Conv) Tilde() *Conv
- func (t *Conv) ToLower() *Conv
- func (t *Conv) ToUpper() *Conv
- func (c *Conv) TrimPrefix(prefix string) *Conv
- func (c *Conv) TrimSpace() *Conv
- func (c *Conv) TrimSuffix(suffix string) *Conv
- func (t *Conv) Truncate(maxWidth any, reservedChars ...any) *Conv
- func (t *Conv) TruncateName(maxCharsPerWord, maxWidth any) *Conv
- func (c *Conv) Uint(base ...int) (uint, error)
- func (c *Conv) Uint32(base ...int) (uint32, error)
- func (c *Conv) Uint64(base ...int) (uint64, error)
- func (c *Conv) WrFloat64(dest BuffDest, val float64)
- func (c *Conv) WrIntBase(dest BuffDest, val int64, base int, signed bool, upper ...bool)
- func (c *Conv) WrString(dest BuffDest, s string)
- func (c *Conv) Write(v any) *Conv
- func (c *Conv) WriteByte(b byte) error
- func (c *Conv) WriteFloat(v float64)
- func (c *Conv) WriteInt(v int64)
- func (c *Conv) WriteString(s string) *Conv
- type KeyValue
- type Kind
- type MessageType
- func (t MessageType) IsAuth() bool
- func (t MessageType) IsBroadcast() bool
- func (t MessageType) IsConnect() bool
- func (t MessageType) IsDebug() bool
- func (t MessageType) IsError() bool
- func (t MessageType) IsEvent() bool
- func (t MessageType) IsInfo() bool
- func (t MessageType) IsNetworkError() bool
- func (t MessageType) IsNormal() bool
- func (t MessageType) IsParse() bool
- func (t MessageType) IsRequest() bool
- func (t MessageType) IsResponse() bool
- func (t MessageType) IsSuccess() bool
- func (t MessageType) IsTimeout() bool
- func (t MessageType) IsWarning() bool
- func (t MessageType) String() string
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // Accented characters (lowercase) — exported for tinywasm/model AL = []rune{'á', 'à', 'ã', 'â', 'ä', 'é', 'è', 'ê', 'ë', 'í', 'ì', 'î', 'ï', 'ó', 'ò', 'õ', 'ô', 'ö', 'ú', 'ù', 'û', 'ü', 'ý'} // Accented characters (uppercase) — exported for tinywasm/model AU = []rune{'Á', 'À', 'Ã', 'Â', 'Ä', 'É', 'È', 'Ê', 'Ë', 'Í', 'Ì', 'Î', 'Ï', 'Ó', 'Ò', 'Õ', 'Ô', 'Ö', 'Ú', 'Ù', 'Û', 'Ü', 'Ý'} )
Index-based character mapping for maximum efficiency
var K = struct { Invalid Kind Bool Kind Int Kind Int8 Kind Int16 Kind Int32 Kind Int64 Kind Uint Kind Uint8 Kind Uint16 Kind Uint32 Kind Uint64 Kind Uintptr Kind Float32 Kind Float64 Kind Complex64 Kind Complex128 Kind Array Kind Chan Kind Func Kind Interface Kind Map Kind Pointer Kind Slice Kind String Kind Struct Kind UnsafePointer Kind }{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, }
Kind exposes the Kind constants as fields for external use, while keeping the underlying type and values private.
var Msg = struct { Normal MessageType Info MessageType Error MessageType Warning MessageType Success MessageType // Network/SSE specific (new) Connect MessageType // Connection error Auth MessageType // Authentication error Parse MessageType // Parse/decode error Timeout MessageType // Timeout error Broadcast MessageType // Broadcast/send error Debug MessageType // / Debug message // Pub/Sub & Request/Response (new) Event MessageType Request MessageType Response MessageType }{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}
Msg exposes the MessageType constants for external use, following fmt naming convention. Msg exposes the MessageType constants for external use, following fmt naming convention.
Functions ¶
func Contains ¶
Contains checks if the string 'search' is present in 'Conv'. Uses Index internally for efficient single-pass detection.
Examples:
Contains("hello world", "world") // returns true
Contains("hello world", "xyz") // returns false
Contains("", "test") // returns false (empty string)
Contains("test", "") // returns false (empty search)
Contains("data\x00more", "\x00") // returns true (null byte)
Contains("Case", "case") // returns false (case sensitive)
func Count ¶
Count checks how many times the string 'search' is present in 'Conv'. Uses Index internally for consistency and maintainability.
Examples:
Count("abracadabra", "abra") // returns 2
Count("hello world", "l") // returns 3
Count("golang", "go") // returns 1
Count("test", "xyz") // returns 0 (not found)
Count("anything", "") // returns 0 (empty search)
Count("a\x00b\x00c", "\x00") // returns 2 (null bytes)
func ErrType ¶ added in v0.24.0
ErrType creates an error that:
- shows: cause.Error() + ": " + sentinel.Error()
- allows: errors.Is(result, sentinel) == true
- allows: errors.Is(result, cause) == true (if cause supports it)
The sentinel acts as the type identity of the error — analogous to the category, class or "type" to which the resulting error belongs.
If cause is nil, it returns sentinel directly (no wrapping).
Example:
return fmt.ErrType(dbErr, ErrSyncFailed)
func Fprintf ¶
Fprintf formats according to a format specifier and writes to w. It returns the number of bytes written and any write error encountered. Example: Fprintf(os.Stdout, "Hello %s\n", "world")
func GetPathBase ¶ added in v0.12.5
func GetPathBase() string
GetPathBase returns the domain root path using syscall/js.
func HasPrefix ¶
HasPrefix reports whether the string 'conv' begins with 'prefix'. Implemented using Index for consistency with other helpers in this package.
Examples:
HasPrefix("hello", "he") // returns true
HasPrefix("hello", "hello") // returns true
HasPrefix("hello", "") // returns false (empty prefix)
HasPrefix("a", "abc") // returns false (prefix longer than string)
func HasSuffix ¶
HasSuffix reports whether the string 'Conv' ends with 'suffix'. Implemented using Index by checking the tail of the string.
Examples:
HasSuffix("testing", "ing") // returns true
HasSuffix("file.txt", ".txt") // returns true
HasSuffix("hello", "") // returns false (empty suffix)
HasSuffix("go", "golang") // returns false
func HasUpperPrefix ¶ added in v0.13.0
HasUpperPrefix reports whether the string s starts with an uppercase letter. Supports ASCII (A-Z) and common accented uppercase (Á, É, Í, Ó, Ú, etc.).
Examples:
HasUpperPrefix("Hello") -> true
HasUpperPrefix("Ángel") -> true
HasUpperPrefix("hello") -> false
func IDorPrimaryKey ¶
IDorPrimaryKey determines if a field is an ID field and/or a primary key field. This function analyzes field names to identify ID fields and primary keys based on naming conventions.
Parameters:
- tableName: The name of the table or entity that the field belongs to
- fieldName: The name of the field to analyze
Returns:
- isID: true if the field is an ID field (starts with "id")
- isPK: true if the field is a primary key (matches specific patterns)
Examples:
- IDorPrimaryKey("user", "id") returns (true, true)
- IDorPrimaryKey("user", "iduser") returns (true, true)
- IDorPrimaryKey("user", "userID") returns (true, true)
- IDorPrimaryKey("user", "USER_id") returns (true, true)
- IDorPrimaryKey("user", "id_user") returns (true, true)
- IDorPrimaryKey("user", "idaddress") returns (true, false)
- IDorPrimaryKey("user", "name") returns (false, false)
func Index ¶
Index finds the first occurrence of substr in s, returns -1 if not found. This is the base primitive that other functions will reuse.
Examples:
Index("hello world", "world") // returns 6
Index("hello world", "lo") // returns 3
Index("hello world", "xyz") // returns -1 (not found)
Index("hello world", "") // returns 0 (empty string)
Index("data\x00more", "\x00") // returns 4 (null byte)
func IsWordSeparator ¶ added in v0.24.1
IsWordSeparator checks if a character is a word separator UNIFIED FUNCTION: Handles byte, rune, and string inputs in a single function OPTIMIZED: Uses IsWordSeparatorChar as single source of truth
func IsWordSeparatorChar ¶ added in v0.24.1
IsWordSeparatorChar is the core separator detection logic CENTRALIZED: Single source of truth for what constitutes a word separator OPTIMIZED: Handles both ASCII and Unicode characters efficiently
func IsZero ¶ added in v0.18.14
IsZero reports whether v is the zero value for its type. Supports: string, bool, int (all sizes), uint (all sizes), float32, float64, []byte, nil. Returns false for unrecognized types.
func JSONEscape ¶ added in v0.18.14
JSONEscape writes s to b with JSON string escaping (without surrounding quotes). Escapes: " → \", \ → \\, newline → \n, carriage return → \r, tab → \t, control chars (< 0x20) → \u00XX.
The caller is responsible for writing the surrounding double quotes. This design allows the caller to compose JSON strings without extra allocations.
func JoinSlice ¶ added in v0.25.2
JoinSlice mirrors strings.Join(elems, sep). Named JoinSlice (not Join) to avoid colliding with Conv.Join.
func LastIndex ¶
LastIndex returns the index of the last instance of substr in s, or -1 if substr is not present in s.
Special cases:
- If substr is empty, LastIndex returns len(s).
- If substr is not found in s, LastIndex returns -1.
- If substr is longer than s, LastIndex returns -1.
Examples:
LastIndex("hello world", "world") // returns 6
LastIndex("hello world hello", "hello") // returns 12 (last occurrence)
LastIndex("image.backup.jpg", ".") // returns 12 (useful for file extensions)
LastIndex("hello", "xyz") // returns -1 (not found)
LastIndex("hello", "") // returns 5 (len("hello"))
LastIndex("", "hello") // returns -1 (not found in empty string)
Common use case - extracting file extensions:
filename := "document.backup.pdf"
pos := LastIndex(filename, ".")
if pos >= 0 {
extension := filename[pos+1:] // "pdf"
}
func Matches ¶ added in v0.23.7
Matches reports whether content contains ALL given terms (AND semantics). content and each term are lowercased before comparison. Returns false if no terms are given or any term is empty.
func MatchesAny ¶ added in v0.23.7
MatchesAny reports whether content contains AT LEAST ONE of the given terms (OR semantics). content and each term are lowercased before comparison. Returns false if no terms are given or any term is empty.
func PathRelativeTo ¶ added in v0.25.4
PathRelativeTo shortens path's occurrences of base into "./"-relative form, using the same algorithm as PathShort but with the base given explicitly — for callers that track their own reference directory instead of relying on SetPathBase/GetPathBase's process-CWD auto-detection (e.g. a daemon whose own working directory does not track the project root it is serving).
Example: PathRelativeTo("/home/user/project/config/db.sql", "/home/user/project") -> "./config/db.sql"
func Println ¶ added in v0.16.0
func Println(args ...any)
Println prints arguments to console.log (like fmt.Println)
func ReplaceAll ¶ added in v0.25.2
ReplaceAll mirrors strings.ReplaceAll.
func ReplaceN ¶ added in v0.25.2
ReplaceN mirrors strings.Replace(s, old, new, n). Named ReplaceN (not Replace) to avoid colliding with Conv.Replace's signature, which accepts values of any type instead of only strings.
func SetPathBase ¶ added in v0.12.5
func SetPathBase(base string)
SetPathBase sets the base path for PathShort operations. Optional: if not called, PathShort auto-detects using GetPathBase (os.Getwd or syscall/js).
func SetTranslator ¶ added in v0.24.1
SetTranslator installs the global translator. It is typically called by the fmt/lang package during its initialization.
func Split ¶ added in v0.23.10
Split is a convenience wrapper around Conv.Split. It creates a Conv from the given string and forwards the call to the existing method. This keeps the binary size small by reusing existing logic.
Example:
parts := fmt.Split("a,b,c", ",") // []string{"a", "b", "c"}
func Sprint ¶ added in v0.15.1
Sprint converts any value to its string representation. This is the equivalent of fmt.Sprint() from the standard library. Example: Sprint(42) returns "42" Example: Sprint(true) returns "true" Example: Sprint("hello") returns "hello"
func Sprintf ¶ added in v0.15.0
Sprintf formats a string using a printf-style format string and arguments. Example: Sprintf("Hello %s", "world") returns "Hello world"
func Sscanf ¶
Sscanf parses formatted text from a string using printf-style format specifiers. It returns the number of items successfully parsed and any error encountered. Example: Sscanf("!3F U+003F question", "!%x U+%x %s", &pos, &enc.uv, &enc.name)
func TrimPrefix ¶ added in v0.25.2
TrimPrefix mirrors strings.TrimPrefix.
func TrimSuffix ¶ added in v0.25.2
TrimSuffix mirrors strings.TrimSuffix.
Types ¶
type BuffDest ¶
type BuffDest int
Buffer destination selection for AnyToBuff universal conversion function
type Builder ¶ added in v0.18.14
type Builder = Conv
Builder is an alias for Conv to provide a familiar string building API
type Conv ¶
type Conv struct {
// contains filtered or unexported fields
}
func Convert ¶
Convert initializes a new Conv struct with optional value for string,bool and number manipulation. REFACTORED: Now accepts variadic parameters - Convert() or Convert(value) Phase 7: Uses object pool internally for memory optimization (transparent to user)
func Err ¶
Err creates a new error message with support for multilingual translations Supports LocStr types for translations (if fmt/lang is imported) eg: fmt.Err("invalid format") returns "invalid format" fmt.Err(D.Format, D.Invalid) returns "invalid format"
func Errf ¶
Errf creates a new Conv instance with error formatting similar to fmt.Errf Example: fmt.Errf("invalid value: %s", value).Error()
func GetConv ¶
func GetConv() *Conv
WASM is single-threaded: use simple allocation instead of sync.Pool
func Html ¶
Html creates a string for HTML content, similar to Translate but without automatic spacing. It supports two modes: 1. Format mode: If the first argument is a string containing '%', it behaves like Fmt. 2. Concatenation mode: Otherwise, it concatenates arguments (translating with hook) without spaces.
func PathJoin ¶
PathJoin joins path elements using the appropriate separator. Accepts variadic string arguments and returns a Conv instance for method chaining. Detects Windows paths (backslash) or Unix paths (forward slash). Empty elements are ignored.
Usage patterns:
- PathJoin("a", "b", "c").String() // -> "a/b/c"
- PathJoin("a", "B", "c").ToLower().String() // -> "a/b/c"
Examples:
PathJoin("a", "b", "c").String() // -> "a/b/c"
PathJoin("/root", "sub", "file").String() // -> "/root/sub/file"
PathJoin(`C:\dir`, "file").String() // -> "C:\dir\file"
PathJoin("a", "", "b").String() // -> "a/b"
PathJoin("a", "B", "c").ToLower().String() // -> "a/b/c"
func (*Conv) Apply ¶
func (t *Conv) Apply()
Apply updates the original string pointer with the current content and auto-releases to pool. This method should be used when you want to modify the original string directly without additional allocations.
func (*Conv) Bool ¶
Bool converts the Conv content to a boolean value using internal implementations Returns the boolean value and any error that occurred
func (*Conv) CamelLow ¶
converts Conv to camelCase (first word lowercase) eg: "Hello world" -> "helloWorld"
func (*Conv) CamelUp ¶
converts Conv to PascalCase (all words capitalized) eg: "hello world" -> "HelloWorld"
func (*Conv) Capitalize ¶
Capitalize transforms the first letter of each word to uppercase and the rest to lowercase. Preserves all whitespace formatting (spaces, tabs, newlines) without normalization. OPTIMIZED: Uses work buffer efficiently to minimize allocations For example: " hello world " -> " Hello World "
func (*Conv) EscapeAttr ¶
EscapeAttr returns a string safe to place inside an HTML attribute value.
func (*Conv) EscapeHTML ¶
EscapeHTML returns a string safe for inclusion into HTML content.
func (*Conv) ExtractValue ¶
ExtractValue extracts the value after the first delimiter. If not found, returns an error. Usage: Convert("key:value").ExtractValue(":") => "value", nil If no delimiter is provided, uses ":" by default.
func (*Conv) Float32 ¶
Float32 converts the value to a float32. Returns the converted float32 and any error that occurred during conversion.
func (*Conv) Float64 ¶
Float64 converts the value to a float64. Returns the converted float64 and any error that occurred during conversion.
func (*Conv) GetBytes ¶ added in v0.25.0
getBytes returns []byte content from specified buffer destination OPTIMIZED: Returns slice directly without string conversion for io.Writer compatibility
func (*Conv) GetKind ¶
GetKind returns the Kind of the value stored in the Conv This allows external packages to reuse tinystring's type detection logic
func (*Conv) GetString ¶
GetString returns string content from specified buffer destination SAFE: Uses standard conversion to avoid memory corruption in concurrent access NOTE: unsafeString() cannot be used here because returned strings outlive Conv lifecycle
func (*Conv) GetStringZeroCopy ¶
GetStringZeroCopy returns string content without heap allocation UNSAFE: Returned string shares underlying buffer - do not modify buffer after calling SAFE for: Immediate use where buffer is not modified until string is no longer needed
func (*Conv) Int ¶
Int converts the value to an integer with optional base specification. If no base is provided, base 10 is used. Supports bases 2-36. Returns the converted integer and any error that occurred during conversion.
func (*Conv) Int32 ¶
getInt32 extrae el valor del buffer de salida y lo convierte a int32. Int32 extrae el valor del buffer de salida y lo convierte a int32.
func (*Conv) Int64 ¶
getInt64 extrae el valor del buffer de salida y lo convierte a int64. Int64 extrae el valor del buffer de salida y lo convierte a int64.
func (*Conv) Join ¶
Join concatenates the elements of a string slice to create a single string. If no separator is provided, it uses a space as default. Can be called with varargs to specify a custom separator. eg: Convert([]string{"Hello", "World"}).Join() => "Hello World" eg: Convert([]string{"Hello", "World"}).Join("-") => "Hello-World"
func (*Conv) LoadBytes ¶ added in v0.18.18
LoadBytes loads raw bytes into the output buffer for subsequent parsing. Reuses existing buffer capacity — 0 allocations for data within capacity. Use with GetConv() + LoadBytes + Int64()/Float64() + PutConv() to parse numbers from byte slices without string creation or variadic boxing.
func (*Conv) PathBase ¶
PathBase returns the last element of path, similar to filepath.Base from the Go standard library. It treats trailing slashes specially ("/a/b/" -> "b") and preserves a single root slash ("/" -> "/"). An empty path returns ".".
The implementation uses tinystring helpers (HasSuffix and Index) to avoid importing the standard library and keep the function minimal and TinyGo-friendly.
Examples:
PathBase("/a/b/c.txt") // -> "c.txt"
PathBase("folder/file.txt") // -> "file.txt"
PathBase("") // -> "."
PathBase("c:\file program\app.exe") // -> "app.exe"
PathBase writes the last element of the path into the Conv output buffer. Use it as: Convert(path).PathBase().String() and it behaves similarly to filepath.Base. Examples:
Convert("/a/b/c.txt").PathBase().String() // -> "c.txt" Convert("folder/file.txt").PathBase().String() // -> "file.txt" Convert("").PathBase().String() // -> "." Convert(`c:\file program\app.exe`).PathBase().String() // -> "app.exe"
func (*Conv) PathExt ¶
PathExt extracts the file extension from a path and writes it to the Conv buffer. Returns the Conv instance for method chaining. An empty extension returns an empty string.
Examples:
Convert("/a/b/c.txt").PathExt().String() // -> ".txt"
Convert("file.tar.gz").PathExt().String() // -> ".gz"
Convert("noext").PathExt().String() // -> ""
Convert("C:\\dir\\app.EXE").PathExt().ToLower().String() // -> ".exe"
func (*Conv) PathShort ¶ added in v0.12.5
PathShort shortens absolute paths relative to base path. It can handle paths embedded in larger strings (e.g. log messages). Auto-detects base path via GetPathBase() if SetPathBase was not called. Returns relative path with "./" prefix for minimal output. Example: "Compiling /home/user/project/src/file.go ..." -> "Compiling ./src/file.go ..."
func (*Conv) Quote ¶
Quote wraps a string in double quotes and escapes any special characters Example: Quote("hello \"world\"") returns "\"hello \\\"world\\\"\""
func (*Conv) Repeat ¶
Repeat repeats the Conv content n times If n is 0 or negative, it clears the Conv content eg: Convert("abc").Repeat(3) => "abcabcabc"
func (*Conv) Replace ¶
Replace replaces up to n occurrences of old with new in the Conv content If n < 0, there is no limit on the number of replacements eg: "hello world" with old "world" and new "universe" will return "hello universe" Old and new can be any type, they will be converted to string using Convert
func (*Conv) Reset ¶
Reset clears all Conv fields and resets the buffer Useful for reusing the same Conv object for multiple operations
func (*Conv) ResetBuffer ¶
ResetBuffer resets specified buffer destination FIXED: Also resets slice length to prevent data contamination
func (*Conv) Round ¶
Round rounds or truncates the current numeric value to the specified number of decimal places.
- If the optional 'down' parameter is omitted or false, it applies "round half to even" (bankers rounding, like Go: 2.5 → 2, 3.5 → 4). - If 'down' is true, it truncates (floors) the value without rounding.
Example:
Convert("3.14159").Round(2) // "3.14" (rounded)
Convert("3.145").Round(2) // "3.14" (rounded)
Convert("3.155").Round(2) // "3.16" (rounded)
Convert("3.14159").Round(2, true) // "3.14" (truncated)
If the value is not numeric, returns "0" with the requested number of decimals.
func (*Conv) SnakeLow ¶
snakeCase converts a string to snake_case format with optional separator. If no separator is provided, underscore "_" is used as default. Example:
Input: "camelCase" -> Output: "camel_case" Input: "PascalCase", "-" -> Output: "pascal-case" Input: "APIResponse" -> Output: "api_response" Input: "user123Name", "." -> Output: "user123.name"
SnakeLow converts Conv to snake_case format
func (*Conv) String ¶
String method to return the content of the Conv and automatically returns object to pool Phase 7: Auto-release makes pool usage completely transparent to user
func (*Conv) StringErr ¶
StringErr returns the content of the Conv along with any error and auto-releases to pool
func (*Conv) StringType ¶
func (c *Conv) StringType() (string, MessageType)
StringType returns the string from BuffOut and its detected MessageType, then auto-releases the Conv
func (*Conv) TagPairs ¶ added in v0.14.0
TagPairs searches for a key in a Go struct tag and parses its value as multiple key-value pairs. Example: Convert(`options:"key1:text1,key2:text2"`).TagPairs("options") => []KeyValue{{Key: "key1", Value: "text1"}, {Key: "key2", Value: "text2"}}
func (*Conv) TagValue ¶
TagValue searches for the value of a key in a Go struct tag-like string. Example: Convert(`json:"name" Label:"Nombre"`).TagValue("Label") => "Nombre", true
func (*Conv) Thousands ¶
Thousands formats the number with thousand separators. By default (no param), uses EU style: 1.234.567,89 If anglo is true, uses Anglo style: 1,234,567.89
func (*Conv) Tilde ¶
Tilde removes accents and diacritics using index-based lookup OPTIMIZED: Uses work buffer to eliminate temporary allocations
func (*Conv) TrimPrefix ¶
TrimPrefix removes the specified prefix from the Conv content if it exists eg: "prefix-hello" with prefix "prefix-" will return "hello"
func (*Conv) TrimSpace ¶
TrimSpace removes spaces at the beginning and end of the Conv content eg: " hello world " will return "hello world"
func (*Conv) TrimSuffix ¶
TrimSuffix removes the specified suffix from the Conv content if it exists eg: "hello.txt" with suffix ".txt" will return "hello"
func (*Conv) Truncate ¶
Truncate truncates a Conv so that it does not exceed the specified width. If the Conv is longer, it truncates it and adds "..." if there is space. If the Conv is shorter or equal to the width, it remains unchanged. The reservedChars parameter indicates how many characters should be reserved for suffixes. This parameter is optional - if not provided, no characters are reserved (equivalent to passing 0). eg: Convert("Hello, World!").Truncate(10) => "Hello, ..." eg: Convert("Hello, World!").Truncate(10, 3) => "Hell..." eg: Convert("Hello").Truncate(10) => "Hello"
func (*Conv) TruncateName ¶
TruncateName truncates names and surnames in a user-friendly way for display in limited spaces like chart labels. It adds abbreviation dots where appropriate. This method processes the first word differently if there are more than 2 words in the Conv.
Parameters:
- maxCharsPerWord: maximum number of characters to keep per word (any numeric type)
- maxWidth: maximum total length for the final string (any numeric type)
Examples:
- Convert("Jeronimo Dominguez").TruncateName(3, 15) => "Jer. Dominguez"
- Convert("Ana Maria Rodriguez").TruncateName(2, 10) => "An. Mar..."
- Convert("Juan").TruncateName(3, 5) => "Juan"
func (*Conv) Uint ¶
Uint converts the value to an unsigned integer with optional base specification. If no base is provided, base 10 is used. Supports bases 2-36. Returns the converted uint and any error that occurred during conversion.
func (*Conv) WrIntBase ¶ added in v0.25.0
wrIntBase writes an integer in the given base to the buffer, with optional uppercase digits
func (*Conv) WrString ¶
WrString writes string to specified buffer destination (universal method) OPTIMIZED: Uses zero-allocation unsafe conversion for performance
func (*Conv) Write ¶
Write appends any value to the buffer using unified type handling This is the core builder method that enables fluent chaining
Usage:
c.Write("hello").Write(" ").Write("world") // Strings
c.Write(42).Write(" items") // Numbers
c.Write('A').Write(" grade") // Runes
func (*Conv) WriteByte ¶ added in v0.18.14
WriteByte appends a byte to the primary output buffer. Part of the Builder API.
func (*Conv) WriteFloat ¶ added in v0.18.17
WriteFloat writes a float64 as decimal text to the output buffer.
func (*Conv) WriteInt ¶ added in v0.18.17
WriteInt writes an int64 as decimal text to the output buffer.
func (*Conv) WriteString ¶ added in v0.18.14
WriteString appends a string to the primary output buffer. Part of the Builder API.
type Kind ¶
type Kind uint8
Kind represents the specific Kind of type that a Type represents (private) Unified with convert.go Kind, using K prefix for fmt naming convention.
IMPORTANT: The order and values of Kind must NOT be changed. These values are used in tinyreflect, a minimal version of reflectlite from the Go standard library. Keeping the order and values identical ensures compatibility with code and data shared between tinystring and tinyreflect.
type MessageType ¶
type MessageType uint8
MessageType represents the classification of message types in the system.
func (MessageType) IsAuth ¶
func (t MessageType) IsAuth() bool
func (MessageType) IsBroadcast ¶
func (t MessageType) IsBroadcast() bool
func (MessageType) IsDebug ¶ added in v0.16.1
func (t MessageType) IsDebug() bool
func (MessageType) IsError ¶
func (t MessageType) IsError() bool
func (MessageType) IsEvent ¶ added in v0.17.3
func (t MessageType) IsEvent() bool
func (MessageType) IsInfo ¶
func (t MessageType) IsInfo() bool
func (MessageType) IsNetworkError ¶
func (t MessageType) IsNetworkError() bool
IsNetworkError returns true for any network-related error type
func (MessageType) IsParse ¶
func (t MessageType) IsParse() bool
func (MessageType) IsRequest ¶ added in v0.17.3
func (t MessageType) IsRequest() bool
func (MessageType) IsResponse ¶ added in v0.17.3
func (t MessageType) IsResponse() bool
func (MessageType) IsSuccess ¶
func (t MessageType) IsSuccess() bool
func (MessageType) IsTimeout ¶
func (t MessageType) IsTimeout() bool
func (MessageType) IsWarning ¶
func (t MessageType) IsWarning() bool
func (MessageType) String ¶
func (t MessageType) String() string
Source Files
¶
- IDorPrimaryKey.go
- bool.go
- builder.go
- capitalize.go
- compact_float.go
- convert.front.go
- convert.go
- env.front.go
- error.go
- error_wrap.go
- filepath.go
- filepath.wasm.go
- fmt_number.go
- fmt_precision.go
- fmt_sci.go
- fmt_template.go
- html.go
- join.go
- kind.go
- mapping.go
- memory.front.go
- memory.go
- messagetype.go
- num_float.front.go
- num_float.go
- num_int.front.go
- num_int.go
- num_uint.go
- operations.go
- parse.go
- quote.go
- repeat.go
- replace.go
- search.go
- split.go
- sprint.go
- strings.go
- translate_hook.go
- truncate.go