fmt

package module
v0.14.0 Latest Latest
Warning

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

Go to latest
Published: Jan 7, 2026 License: MIT Imports: 5 Imported by: 0

README

fmt

Project Badges

fmt is a lightweight Go library that provides comprehensive string manipulation, type conversion, formatting, and multilingual error handling with a fluid API, specifically designed for small devices and web applications using TinyGo as the target compiler.

Key Features

  • 🚀 Fluid and chainable API - Easy to use and readable operations
  • 📝 Complete string toolkit - Transformations, conversions, formatting, and error handling
  • 🌍 Multilingual error messages - Built-in dictionary system with 9 languages
  • 🧵 Concurrency safe - Thread-safe operations for concurrent environments
  • 📦 Zero dependencies - No fmt, strings, strconv, or errors imports
  • 🎯 TinyGo optimized - Manual implementations for minimal binary size
  • 🌐 WebAssembly-first - Designed for modern web deployment
  • 🔄 Universal type support - Works with strings, numbers, booleans, and slices
  • Performance focused - Predictable allocations and custom optimizations

Why fmt?

Installation

go get github.com/tinywasm/fmt

Usage

import . "github.com/tinywasm/fmt"

// Quick start - Basic conversion and transformation
text := Convert("Hóla Múndo").Tilde().ToLower().String() // out: "hola mundo"

// Working with different data types
numText := Convert(42).String()     // out: "42"
boolText := Convert(true).String()  // out: "true"

// Memory-efficient approach using string pointers
original := "Él Múrcielago Rápido"
Convert(&original).Tilde().CamelLow().Apply()
// original is now: "elMurcielagoRapido"

// Efficient builder and chaining with accent normalization
items := []string{"  ÁPPLE  ", "  banána  ", "  piñata  ","  ÑANDÚ  "}
builder := Convert() // without params reused buffer = optimal performance
for i, item := range items {
    processed := Convert(item).
        TrimSpace(). // TrimSpace whitespace
        Tilde(). // Normalize accents
        ToLower(). // Convert to lowercase
        Capitalize(). // Capitalize first letter
        String() // Finalize the string
    builder.Write(processed)
    if i < len(items)-1 {
        builder.Write(" - ")
    }
}

out := builder.String() // Finalize the string hiding the error
out, err := builder.StringErr() // OR finalize with error handling

// out: "Apple - Banana - Piñata - Ñandu", err: nil

// Check for uppercase prefix (supports Unicode)
isUpper := HasUpperPrefix("Ápple") // out: true

Documentation

Benchmarking

Examples


Contributing


License

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

Examples

Constants

View Source
const (
	// Group 1: Core Essential Languages (Maximum Global Reach)
	EN lang = iota // 0 - English (default)
	ES             // 1 - Spanish
	ZH             // 2 - Chinese
	HI             // 3 - Hindi
	AR             // 4 - Arabic

	// Group 2: Extended Reach Languages (Europe & Americas)
	PT // 5 - Portuguese
	FR // 6 - French
	DE // 7 - German
	RU // 8 - Russian

)

Variables

View Source
var D = struct {
	// A
	All        LocStr // "all"
	Allowed    LocStr // "allowed"
	Arrow      LocStr // "arrow"
	Argument   LocStr // "argument"
	Assign     LocStr // "assign"
	Assignable LocStr // "assignable"

	// B
	BackingUp LocStr // "backing up"
	Be        LocStr // "be"
	Begin     LocStr // "begin"
	Binary    LocStr // "binary"

	// C
	Call          LocStr // "call"
	Can           LocStr // "can"
	Cannot        LocStr // "cannot"
	Cancel        LocStr // "cancel"
	Changed       LocStr // "changed"
	Character     LocStr // "character"
	Chars         LocStr // "chars"
	Checker       LocStr // "checker"
	Coding        LocStr // "coding"
	Compilation   LocStr // "compilation"
	Configuration LocStr // "configuration"
	Connection    LocStr // "connection"
	Content       LocStr // "content"
	Create        LocStr // "create"

	// D
	Date       LocStr // "date"
	Debugging  LocStr // "debugging"
	Decimal    LocStr // "decimal"
	Delimiter  LocStr // "delimiter"
	Dictionary LocStr // "dictionary"
	Digit      LocStr // "digit"
	Down       LocStr // "down"

	// E
	Edit    LocStr // "edit"
	Element LocStr // "element"
	Email   LocStr // "email"
	Empty   LocStr // "empty"
	End     LocStr // "end"
	Example LocStr // "example"
	Exceeds LocStr // "exceeds"
	Execute LocStr // "execute"

	// F
	Failed LocStr // "failed"
	Female LocStr // "female
	Field  LocStr // "field"
	Fields LocStr // "fields"
	Files  LocStr // "files"
	Format LocStr // "format"
	Found  LocStr // "found"

	// H
	Handler LocStr // "handler"
	Hyphen  LocStr // "hyphen"
	Hour    LocStr // "hour"

	// I
	Icons        LocStr // "icons"
	Insert       LocStr // "insert"
	Left         LocStr // "left"
	Implemented  LocStr // "implemented"
	In           LocStr // "in"
	Index        LocStr // "index"
	Information  LocStr // "information"
	Input        LocStr // "input"
	Install      LocStr // "install"
	Installation LocStr // "installation"
	Invalid      LocStr // "invalid"

	// K
	Keyboard LocStr // "keyboard"

	// L
	Language LocStr // "language"
	Letters  LocStr // "letters"
	Line     LocStr // "line"

	// M
	Male     LocStr // "male"
	Maximum  LocStr // "maximum"
	Method   LocStr // "method"
	Missing  LocStr // "missing"
	Mismatch LocStr // "mismatch"
	Mode     LocStr // "mode"
	Modes    LocStr // "modes"
	More     LocStr // "more"
	Move     LocStr // "move"
	Must     LocStr // "must"

	// N
	Negative   LocStr // "negative"
	Nil        LocStr // "null"
	NonNumeric LocStr // "non-numeric"
	Not        LocStr // "not"
	NotOfType  LocStr // "not of type"
	Number     LocStr // "number"
	Numbers    LocStr // "numbers"

	// O
	Of       LocStr // "of"
	Options  LocStr // "options"
	Out      LocStr // "out"
	Overflow LocStr // "overflow"

	// P
	Page       LocStr // "page"
	Pointer    LocStr // "pointer"
	Point      LocStr // "point"
	Preparing  LocStr // "preparing"
	Production LocStr // "production"
	Provided   LocStr // "provided"

	// Q
	Quit LocStr // "quit"

	// R
	Range    LocStr // "range"
	Read     LocStr // "read"
	Required LocStr // "required"
	Right    LocStr // "right"
	Round    LocStr // "round"

	// S
	Seconds   LocStr // "seconds"
	Session   LocStr // "session"
	Slice     LocStr // "slice"
	Space     LocStr // "space"
	Status    LocStr // "status"
	String    LocStr // "string"
	Shortcuts LocStr // "shortcuts"
	Supported LocStr // "supported"
	Switch    LocStr // "switch"
	Switching LocStr // "switching"
	Sync      LocStr // "sync"
	System    LocStr // "system"

	// Translate
	Tab     LocStr // "tab"
	Test    LocStr // "test"
	Testing LocStr // "testing"
	Text    LocStr // "text"
	Time    LocStr // "time"
	To      LocStr // "to"
	Type    LocStr // "type"

	// U
	Unexported LocStr // "unexported"
	Unknown    LocStr // "unknown"
	Unsigned   LocStr // "unsigned"
	Up         LocStr // "up"
	Use        LocStr // "use"

	// V
	Valid      LocStr // "valid"
	Validating LocStr // "validating"
	Value      LocStr // "value"
	Visible    LocStr // "visible"

	// W
	Warning LocStr // "warning"
	With    LocStr // "with"

	// Z
	Zero LocStr // "zero"

}{}/* 128 elements not displayed */

Global dictionary instance - populated with all translations using horizontal format Language order: EN, ES, ZH, HI, AR, PT, FR, DE, RU

By using an anonymous struct, we define and initialize the dictionary in a single step, avoiding the need for a separate 'type dictionary struct' declaration. The usage API (e.g., D.Argument) remains unchanged.

View Source
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.

View Source
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
}{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

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

func Contains(Conv, search string) bool

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

func Count(Conv, search string) int

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 Fmt

func Fmt(format string, args ...any) string

Fmt formats a string using a printf-style format string and arguments. Example: Fmt("Hello %s", "world") returns "Hello world"

func Fprintf

func Fprintf(w io.Writer, format string, args ...any) (n int, err error)

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 base path using os.Getwd().

func HasPrefix

func HasPrefix(conv, prefix string) bool

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

func HasSuffix(conv, suffix string) bool

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

func HasUpperPrefix(s string) bool

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

func IDorPrimaryKey(tableName, fieldName string) (isID, isPK bool)

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

func Index(s, substr string) int

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 LastIndex

func LastIndex(s, substr string) int

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 OutLang

func OutLang(l ...any) string

OutLang sets and returns the current output language as a string.

OutLang() // Auto-detects system/browser language, returns code (e.g. "EN") OutLang(ES) // Set Spanish as default (using lang constant), returns "ES" OutLang("ES") // Set Spanish as default (using string code), returns "ES" OutLang("fr") // Set French as default (case-insensitive), returns "FR" OutLang("en-US") // Accepts locale strings, parses to EN, returns "EN"

If a string is passed, it is automatically parsed using supported codes. If a lang value is passed, it is assigned directly. If another type is passed, nothing happens. Always returns the current language code as string (e.g. "EN", "ES", etc).

func SetPathBase added in v0.12.4

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 Sscanf

func Sscanf(src string, format string, args ...any) (n int, err error)

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)

Types

type BuffDest

type BuffDest int

Buffer destination selection for AnyToBuff universal conversion function

const (
	BuffOut  BuffDest = iota // Primary output buffer
	BuffWork                 // Working/temporary buffer
	BuffErr                  // Error message buffer
)

type Conv

type Conv struct {
	// contains filtered or unexported fields
}

func Convert

func Convert(v ...any) *Conv

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

func Err(msgs ...any) *Conv

func Errf

func Errf(format string, args ...any) *Conv

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

GetConv gets a reusable Conv from the pool FIXED: Ensures object is completely clean to prevent race conditions

func Html

func Html(values ...any) *Conv

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 LocStr) without spaces.

Usage: Html("div", "span").String() -> "divspan" Html("<div class='%s'>", "foo").String() -> "<div class='foo'>"

func PathJoin

func PathJoin(elem ...string) *Conv

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 Translate

func Translate(values ...any) *Conv

Translate creates a translated string with support for multilingual translations Same functionality as Err but returns string directly instead of *Conv This function is used internally by the builder API for efficient string construction

Usage examples: Translate(D.Format, D.Invalid) returns "invalid format" Translate(ES, D.Format, D.Invalid) returns "formato inválido" Translate creates a translated string with support for multilingual translations Same functionality as Err but returns *Conv for further formatting This function is used internally by the builder API for efficient string construction

Usage examples: Translate(D.Format, D.Invalid) returns *Conv with "invalid format" Translate(ES, D.Format, D.Invalid) returns *Conv with "formato inválido"

MEMORY MANAGEMENT: The returned *Conv object is pooled. - Calling .String() or .Apply() automatically returns it to the pool. - If you use .Bytes() or other methods, you MUST call .PutConv() manually to avoid memory leaks.

PERFORMANCE OPTIMIZATION: For zero-allocation performance, pass pointers to LocStr instead of values:

Translate(D.Format)     // 1 alloc/op  (LocStr boxing)
Translate(&D.Format)    // 0 allocs/op (pointer fits in interface)

This is useful in hot paths where allocation-free operation is critical.

func (*Conv) AnyToBuff

func (c *Conv) AnyToBuff(dest BuffDest, value any)

AnyToBuff converts any supported type to buffer using existing conversion logic REUSES: floatToOut, wrStringToOut, wrStringToErr Supports: string, int variants, uint variants, float variants, bool, []byte, LocStr

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

func (c *Conv) Bool() (bool, error)

Bool converts the Conv content to a boolean value using internal implementations Returns the boolean value and any error that occurred

func (*Conv) Bytes

func (c *Conv) Bytes() []byte

Bytes returns the content of the Conv as a byte slice

func (*Conv) CamelLow

func (t *Conv) CamelLow() *Conv

converts Conv to camelCase (first word lowercase) eg: "Hello world" -> "helloWorld"

func (*Conv) CamelUp

func (t *Conv) CamelUp() *Conv

converts Conv to PascalCase (all words capitalized) eg: "hello world" -> "HelloWorld"

func (*Conv) Capitalize

func (t *Conv) Capitalize() *Conv

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

func (c *Conv) Error() string

func (*Conv) EscapeAttr

func (c *Conv) EscapeAttr() string

EscapeAttr returns a string safe to place inside an HTML attribute value.

It escapes the following characters:

& -> &amp;
" -> &quot;
' -> &#39;
< -> &lt;
> -> &gt;

Example:

s := Convert(`Tom & Jerry's "House" <tag>`).EscapeAttr()
// s == `Tom &amp; Jerry&#39;s &quot;House&quot; &lt;tag&gt;`

Note: this method performs plain string replacements and does not detect existing HTML entities. Calling EscapeAttr on a string that already contains entities (for example `&amp;`) will produce double-escaped output (`&amp;amp;`). This behavior is intentional and matches a simple escape-for-attribute semantics.

func (*Conv) EscapeHTML

func (c *Conv) EscapeHTML() string

EscapeHTML returns a string safe for inclusion into HTML content.

It escapes the following characters:

& -> &amp;
< -> &lt;
> -> &gt;
" -> &quot;
' -> &#39;

Example:

s := Convert(`<div class="x">Tom & Jerry's</div>`).EscapeHTML()
// s == `&lt;div class=&quot;x&quot;&gt;Tom &amp; Jerry&#39;s&lt;/div&gt;`

Like EscapeAttr, this method uses simple replacements and will double-escape existing entities.

func (*Conv) ExtractValue

func (c *Conv) ExtractValue(delimiters ...string) (string, error)

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

func (c *Conv) Float32() (float32, error)

Float32 converts the value to a float32. Returns the converted float32 and any error that occurred during conversion.

func (*Conv) Float64

func (c *Conv) Float64() (float64, error)

Float64 converts the value to a float64. Returns the converted float64 and any error that occurred during conversion.

func (*Conv) GetKind

func (c *Conv) GetKind() Kind

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

func (c *Conv) GetString(dest BuffDest) string

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

func (c *Conv) GetStringZeroCopy(dest BuffDest) string

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

func (c *Conv) Int(base ...int) (int, error)

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

func (c *Conv) Int32(base ...int) (int32, error)

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

func (c *Conv) Int64(base ...int) (int64, error)

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

func (c *Conv) Join(sep ...string) *Conv

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

func (c *Conv) PathBase() *Conv

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

func (c *Conv) PathExt() *Conv

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.4

func (c *Conv) PathShort() *Conv

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

func (c *Conv) PutConv()

PutConv returns a Conv to the pool after resetting it

func (*Conv) Quote

func (c *Conv) Quote() *Conv

Quote wraps a string in double quotes and escapes any special characters Example: Quote("hello \"world\"") returns "\"hello \\\"world\\\"\""

func (*Conv) Repeat

func (t *Conv) Repeat(n int) *Conv

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

func (c *Conv) Replace(oldAny, newAny any, n ...int) *Conv

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

func (c *Conv) Reset() *Conv

Reset clears all Conv fields and resets the buffer Useful for reusing the same Conv object for multiple operations

func (*Conv) ResetBuffer

func (c *Conv) ResetBuffer(dest BuffDest)

ResetBuffer resets specified buffer destination FIXED: Also resets slice length to prevent data contamination

func (*Conv) Round

func (t *Conv) Round(decimals int, down ...bool) *Conv

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

func (c *Conv) SmartArgs(dest BuffDest, separator string, allowStringCode bool, detectFormat bool, values ...any) *Conv

SmartArgs handles language detection, format string detection, and argument processing This unifies logic between Html (detectFormat=true, allowStringCode=false) and Translate (detectFormat=false, allowStringCode=true)

func (*Conv) SnakeLow

func (t *Conv) SnakeLow(sep ...string) *Conv

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

func (t *Conv) SnakeUp(sep ...string) *Conv

SnakeUp converts Conv to Snake_Case format

func (*Conv) Split

func (c *Conv) Split(separator ...string) []string

func (*Conv) String

func (c *Conv) String() 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

func (c *Conv) StringErr() (out string, err error)

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

func (c *Conv) TagPairs(key string) []KeyValue

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

func (c *Conv) TagValue(key string) (string, bool)

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

func (t *Conv) Thousands(anglo ...bool) *Conv

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

func (t *Conv) Tilde() *Conv

Tilde removes accents and diacritics using index-based lookup OPTIMIZED: Uses work buffer to eliminate temporary allocations

func (*Conv) ToLower

func (t *Conv) ToLower() *Conv

convert to lower case eg: "HELLO WORLD" -> "hello world"

func (*Conv) ToUpper

func (t *Conv) ToUpper() *Conv

convert to upper case eg: "hello world" -> "HELLO WORLD"

func (*Conv) TrimPrefix

func (c *Conv) TrimPrefix(prefix string) *Conv

TrimPrefix removes the specified prefix from the Conv content if it exists eg: "prefix-hello" with prefix "prefix-" will return "hello"

func (*Conv) TrimSpace

func (c *Conv) TrimSpace() *Conv

TrimSpace removes spaces at the beginning and end of the Conv content eg: " hello world " will return "hello world"

func (*Conv) TrimSuffix

func (c *Conv) TrimSuffix(suffix string) *Conv

TrimSuffix removes the specified suffix from the Conv content if it exists eg: "hello.txt" with suffix ".txt" will return "hello"

func (*Conv) Truncate

func (t *Conv) Truncate(maxWidth any, reservedChars ...any) *Conv

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

func (t *Conv) TruncateName(maxCharsPerWord, maxWidth any) *Conv

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

func (c *Conv) Uint(base ...int) (uint, error)

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

func (c *Conv) Uint32(base ...int) (uint32, error)

Uint32 extrae el valor del buffer de salida y lo convierte a uint32.

func (*Conv) Uint64

func (c *Conv) Uint64(base ...int) (uint64, error)

Uint64 extrae el valor del buffer de salida y lo convierte a uint64.

func (*Conv) WrString

func (c *Conv) WrString(dest BuffDest, s string)

WrString writes string to specified buffer destination (universal method) OPTIMIZED: Uses zero-allocation unsafe conversion for performance

func (*Conv) Write

func (c *Conv) Write(v any) *Conv

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

type KeyValue added in v0.14.0

type KeyValue struct {
	Key   string // Key
	Value string // Value
}

KeyValue represents a key-value pair extracted from a string.

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.

func (Kind) String

func (k Kind) String() string

String returns the name of the Kind as a string

type LocStr

type LocStr [9]string

LocStr represents a string with translations for multiple languages.

It is a fixed-size array where each index corresponds to a language constant (EN, ES, PT, etc.). This design ensures type safety and efficiency, as the compiler can verify that all translations are provided.

The order of translations must match the order of the language constants.

Example of creating a new translatable term for "File":

var MyDictionary = struct {
	File LocStr
}{
	File: LocStr{
		EN: "file",
		ES: "archivo",
		ZH: "文件",
		HI: "फ़ाइल",
		AR: "ملف",
		PT: "arquivo",
		FR: "fichier",
		DE: "Datei",
		RU: "файл",
	},
}

Usage in code:

err := Err(MyDictionary.File, D.Not, D.Found) // -> "file not found", "archivo no encontrado", etc.

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

func (t MessageType) IsConnect() bool

Network/SSE helper methods

func (MessageType) IsError

func (t MessageType) IsError() 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) IsNormal

func (t MessageType) IsNormal() bool

Helper methods for MessageType

func (MessageType) IsParse

func (t MessageType) IsParse() 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

Directories

Path Synopsis
example
web command

Jump to

Keyboard shortcuts

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