tinystring

package module
v0.1.12 Latest Latest
Warning

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

Go to latest
Published: Jun 27, 2025 License: MIT Imports: 2 Imported by: 0

README

TinyString

Project Badges

TinyString 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 TinyString?

Installation

go get github.com/cdvelop/tinystring

Usage

import "github.com/cdvelop/tinystring"

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

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

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

// Multilingual error messages (NEW!)
import . "github.com/cdvelop/tinystring"

OutLang(ES) // Set Spanish
err := Err(D.Invalid, D.Format)
// out: "inválido formato"

OutLang()   // Auto-detect system language
err = Err(D.Cannot, D.Round, D.NonNumeric, D.Value).Error()
// Output in user's detected language

🔧 Builder API

TinyString features a high-performance builder API for memory-efficient string operations. All operations work on a single internal buffer with object pooling.

Efficient Loop Processing
import "github.com/cdvelop/tinystring"

// Memory-efficient processing in loops
items := []string{"  APPLE  ", "  banana  ", "  Cherry  "}

c := tinystring.Convert() // Empty initialization
for i, item := range items {
    c.Write(item).Trim().Low().Capitalize()
    if i < len(items)-1 {
        c.Write(" - ")
    }
}
result := c.String() // "Apple - Banana - Cherry"
Key Builder Operations
// Reuse builder for multiple operations
builder := tinystring.Convert()

// Operation 1: Reset and build
builder.Reset()
result1 := builder.Write("Hello").Write(" World").String()

// Operation 2: Reset and transform
builder.Reset()
original := "test string"
tinystring.Convert(&original).Up().Tilde().Apply()
// original is now: "TEST STRING" - modified in-place

📚 Standard Library Equivalents

🔤 strings Package

Replace common strings package functions with TinyString equivalents:

Go Standard TinyString Equivalent
strings.Low() Convert(s).Low().String()
strings.Up() Convert(s).Up().String()
strings.Contains() Contains(s, substr)
strings.Replace() Convert(s).Replace(old, new).String()
strings.Split() Split(s, sep)
strings.Join() Convert(slice).Join(sep).String()
strings.TrimSpace() Convert(s).Trim().String()
strings.TrimPrefix() Convert(s).TrimPrefix(prefix).String()
strings.TrimSuffix() Convert(s).TrimSuffix(suffix).String()
strings.Repeat() Convert(s).Repeat(n).String()
strings.Builder Convert().Write(a).Write(b).String()
Builder API Advantages

The Builder API is especially efficient for complex operations:

// ❌ Standard approach - multiple allocations
result := tinystring.Convert("Hello").Up().String() + " " + 
          tinystring.Convert("World").Low().String() + "!"
// Multiple Convert() calls = multiple allocations

// ✅ Builder approach - single allocation
result := tinystring.Convert().
    Write("Hello").Up().
    Write(" ").
    Write("World").Low().
    Write("!").
    String()
// Single Convert() + reused buffer = optimal performance
Chaining Operations
// Combine multiple operations efficiently
result := tinystring.Convert("  HÓLA MÚNDO  ")
    .Trim()
    .Tilde()
    .Low()
    .Replace(" ", "_")
    .String()
// out: "hola_mundo"
🌍 Unicode & Localization
// Remove accents and diacritics (Ñ/ñ are preserved)
tinystring.Convert("café naïve résumé Ñoño niño").Tilde().String()  
// out: "cafe naive resume Ñono nino"
String Transformations
// Case conversions
tinystring.Convert("HELLO").Low().String()              // out: "hello"
tinystring.Convert("world").Up().String()              // out: "WORLD"
tinystring.Convert("hello world").Capitalize().String()     // out: "Hello World"

// Advanced case styles
tinystring.Convert("hello world").CamelLow().String()   // out: "helloWorld"
tinystring.Convert("hello world").CamelUp().String()   // out: "HelloWorld"
tinystring.Convert("hello world").SnakeLow().String() // out: "hello_world"
tinystring.Convert("hello world").SnakeUp().String() // out: "HELLO_WORLD"
String Search & Operations

// Search and count
found := tinystring.Contains("hello world", "world")              // out: true
count := tinystring.Count("abracadabra", "abra")       // out: 2

// ⚠️ Note: Contains is a global function, not a method.
// Do NOT use: tinystring.Convert(s).Contains(substr) // ❌ Incorrect, will not compile
// Use:        tinystring.Contains(s, substr)         // ✅ Correct

// Replace operations
tinystring.Convert("hello world").Replace("world", "Go").String() // out: "hello Go"
tinystring.Convert("test 123 test").Replace(123, 456).String()    // out: "test 456 test"
String Splitting & Joining
// Split strings
parts := tinystring.Split("apple,banana,cherry", ",")    
// out: []string{"apple", "banana", "cherry"}

parts := tinystring.Split("hello\tworld\nnew")  // Handles whitespace
// out: []string{"hello", "world", "new"}

// Join slices
tinystring.Convert([]string{"Hello", "World"}).Join().String()    // out: "Hello World"
tinystring.Convert([]string{"a", "b", "c"}).Join("-").String()    // out: "a-b-c"
String Trimming & Cleaning
// Trim operations
tinystring.Convert("  hello  ").Trim().String()                    // out: "hello"
tinystring.Convert("prefix-data").TrimPrefix("prefix-").String()    // out: "data"
tinystring.Convert("file.txt").TrimSuffix(".txt").String()          // out: "file"

// Repeat strings
tinystring.Convert("Go").Repeat(3).String()                        // out: "GoGoGo"
🔢 strconv Package

Replace strconv package functions for type conversions:

Go Standard TinyString Equivalent
strconv.Itoa() Convert(i).String()
strconv.Atoi() Convert(s).ToInt()
strconv.ParseFloat() Convert(s).ToFloat64()
strconv.ParseBool() Convert(s).ToBool()
strconv.FormatFloat() Convert(f).Round(n).String()
strconv.Quote() Convert(s).Quote().String()
Type Conversions
// String to numbers
result, err := tinystring.Convert("123").ToInt()        // out: 123, nil
result, err := tinystring.Convert("456").ToUint()       // out: 456, nil  
result, err := tinystring.Convert("3.14").ToFloat64()     // out: 3.14, nil

// Numbers to string
tinystring.Convert(42).String()      // out: "42"
tinystring.Convert(3.14159).String() // out: "3.14159"

// Boolean conversions
result, err := tinystring.Convert("true").ToBool()  // out: true, nil
result, err := tinystring.Convert(42).ToBool()      // out: true, nil (non-zero = true)
result, err := tinystring.Convert(0).ToBool()       // out: false, nil

// String quoting
tinystring.Convert("hello").Quote().String()           // out: "\"hello\""
tinystring.Convert("say \"hello\"").Quote().String()  // out: "\"say \\\"hello\\\"\""
Number Formatting
// Decimal rounding: keep N decimals, round or truncate
// By default, rounds using "round half to even" (bankers rounding)
// Pass true as second argument to truncate instead of round
Convert("3.14159").Round(2)        // "3.14"
Convert("3.155").Round(2)          // "3.16"
Convert("3.14159").Round(2, true)  // "3.14" (truncated)

// Formatting with thousands separator
tinystring.Convert(2189009.00).Thousands().String()        // out: "2.189.009"
🖨️ fmt Package

Replace fmt package functions for formatting:

Go Standard TinyString Equivalent
fmt.Sprintf() Fmt(format, args...)
fmt.Sprint() Convert(v).String()
String Formatting
// Printf-style formatting
result := tinystring.Fmt("Hello %s, you have %d messages", "John", 5)
// out: "Hello John, you have 5 messages"

// Multiple format specifiers
result := tinystring.Fmt("Number: %d, Float: %.2f, Bool: %v", 42, 3.14159, true)
// out: "Number: 42, Float: 3.14, Bool: true"

// Advanced formatting (hex, binary, octal)
result := tinystring.Fmt("Hex: %x, Binary: %b, Octal: %o", 255, 10, 8)
// out: "Hex: ff, Binary: 1010, Octal: 10"
❌ errors Package

Replace errors package functions for error handling with multilingual support:

Go Standard TinyString Equivalent
errors.New() Err(message)
fmt.Errorf() Errf(format, args...)
Error Creation
// Multiple error messages and types
err := tinystring.Err("invalid format", "expected number", 404)
// out: "invalid format expected number 404"

// Formatted errors (like fmt.Errorf)
err := tinystring.Errf("invalid value: %s at position %d", "abc", 5)
// out: "invalid value: abc at position 5"

🚀 TinyString Exclusive Features

🌍 TinyString: Multilingual & Translation Support

TinyString enables multilingual error messages using reusable dictionary terms. It supports 9 languages and allows global or inline language selection.

import . "github.com/cdvelop/tinystring"

OutLang(ES) // Set global language to Spanish or OutLang() without parameters to Auto-detect system/browser language

err := Err(D.Format, D.Invalid)
// → "formato inválido"

// Force French
err = Err(FR, D.Empty, D.String)
// → "vide chaîne"

See dictionary.go for built-in words. Combine D. (default terms) and custom dictionaries for flexible messaging.

📘 Full documentation available in docs/TRANSLATE.md

✂️ Smart Truncation
// Basic truncation with ellipsis
tinystring.Convert("Hello, World!").Truncate(10).String()       
// out: "Hello, ..."

// Name truncation for UI display
tinystring.Convert("Jeronimo Dominguez").TruncateName(3, 15).String()
// out: "Jer. Dominguez"

// Advanced name handling
tinystring.Convert("Juan Carlos Rodriguez").TruncateName(3, 20).String()
// out: "Jua. Car. Rodriguez"
🔧 Advanced Utilities
// Key-value parsing default use :
value, err := tinystring.ParseKeyValue("user:admin")            // out: "admin", nil
value, err := tinystring.ParseKeyValue("count=42", "=")         // out: "42", nil

// Snake case with custom separators
tinystring.Convert("hello world").SnakeLow("-").String() // out: "hello-world"
tinystring.Convert("hello world").SnakeUp("_").String() // out: "HELLO_WORLD"

💡 Performance Tips String() vs Apply()

// String() - Returns the result, original remains unchanged
original := "Él Múrcielago Rápido"
result := tinystring.Convert(original).Tilde().Low().String()
// result: "el murcielago rapido"
// original: "Él Múrcielago Rápido"

// Apply() - Modifies the original string directly (more memory efficient)
// note: only support strings pointer
tinystring.Convert(&original).Tilde().Low().Apply()
// original: "el murcielago rapido"

// There are only two ways to finalize operations: using String() or Apply().

Benchmarking


Contributing

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().Low().Apply()

// La variable original ha sido modificada
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()

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().Low().String()
fmt.Println(processedText)

// Método con punteros (modifica directamente la variable original)
directText := "Otro TEXTO con ACENTOS"
Convert(&directText).Tilde().Low().Apply()
fmt.Println(directText)
Output:

texto con acentos
otro texto con acentos

Index

Examples

Constants

View Source
const (
	KArray kind = iota
	KBool
	KChan
	KComplex128
	KComplex64
	KErr // Error type (separate from KInvalid)
	KFloat32
	KFloat64
	KFunc
	KInt
	KInt16
	KInt32
	KInt64
	KInt8
	KInterface
	KInvalid
	KMap
	KPointer
	KSlice
	KString
	KSliceStr // Slice of strings
	KStruct
	KUint
	KUint16
	KUint32
	KUint64
	KUint8
	KUintptr
	KUnsafePtr
)
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 {
	// Basic words sorted alphabetically for maximum reusability
	Allowed    LocStr // "allowed"
	Argument   LocStr // "argument"
	At         LocStr // "at"
	Base       LocStr // "base"
	Boolean    LocStr // "boolean"
	Cannot     LocStr // "cannot"
	Character  LocStr // "character"
	Decimal    LocStr // "decimal"
	Delimiter  LocStr // "delimiter"
	Digit      LocStr // "digit"
	Empty      LocStr // "empty"
	End        LocStr // "end"
	Float      LocStr // "float"
	For        LocStr // "for"
	Format     LocStr // "format"
	Found      LocStr // "found"
	In         LocStr // "in"
	Integer    LocStr // "integer"
	Invalid    LocStr // "invalid"
	Missing    LocStr // "missing"
	Negative   LocStr // "negative"
	NonNumeric LocStr // "non-numeric"
	Not        LocStr // "not"
	Number     LocStr // "number"
	Numbers    LocStr // "numbers"
	Of         LocStr // "of"
	Out        LocStr // "out"
	Overflow   LocStr // "overflow"
	Range      LocStr // "range"
	Required   LocStr // "required"
	Round      LocStr // "round"
	Specifier  LocStr // "specifier"
	String     LocStr // "string"
	Supported  LocStr // "supported"
	Type       LocStr // "type"
	Unknown    LocStr // "unknown"
	Unsigned   LocStr // "unsigned"
	Value      LocStr // "value"
}{
	Allowed:    LocStr{"allowed", "permitido", "允许", "अनुमति", "مسموح", "permitido", "autorisé", "erlaubt", "разрешено"},
	Argument:   LocStr{"argument", "argumento", "参数", "तर्क", "وسيط", "argumento", "argument", "Argument", "аргумент"},
	At:         LocStr{"at", "en", "在", "पर", "في", "em", "à", "bei", "в"},
	Base:       LocStr{"base", "base", "进制", "आधार", "قاعدة", "base", "base", "Basis", "основание"},
	Boolean:    LocStr{"boolean", "booleano", "布尔", "बूलियन", "منطقي", "booleano", "booléen", "boolescher", "логический"},
	Cannot:     LocStr{"cannot", "no puede", "不能", "नहीं कर सकते", "لا يمكن", "não pode", "ne peut pas", "kann nicht", "не может"},
	Character:  LocStr{"character", "caracter", "字符", "वर्ण", "حرف", "caractere", "caractère", "Zeichen", "символ"},
	Decimal:    LocStr{"decimal", "decimal", "十进制", "दशमलव", "عشري", "decimal", "décimal", "Dezimal", "десятичная"},
	Delimiter:  LocStr{"delimiter", "delimitador", "分隔符", "सीमांकक", "محدد", "delimitador", "délimiteur", "Trennzeichen", "разделитель"},
	Digit:      LocStr{"digit", "dígito", "数字", "अंक", "رقم", "dígito", "chiffre", "Ziffer", "цифра"},
	Empty:      LocStr{"empty", "vacío", "空", "खाली", "فارغ", "vazio", "vide", "leer", "пустой"},
	End:        LocStr{"end", "fin", "结束", "अंत", "نهاية", "fim", "fin", "Ende", "конец"},
	Float:      LocStr{"float", "flotante", "浮点", "फ्लोट", "عائم", "flutuante", "flottant", "Gleitkomma", "число с плавающей точкой"},
	For:        LocStr{"for", "para", "为", "के लिए", "لـ", "para", "pour", "für", "для"},
	Format:     LocStr{"format", "formato", "格式", "प्रारूप", "تنسيق", "formato", "format", "Fmt", "формат"},
	Found:      LocStr{"found", "encontrado", "找到", "मिला", "موجود", "encontrado", "trouvé", "gefunden", "найден"},
	Integer:    LocStr{"integer", "entero", "整数", "पूर्णांक", "عدد صحيح", "inteiro", "entier", "ganze Zahl", "целое число"},
	Invalid:    LocStr{"invalid", "inválido", "无效", "अमान्य", "غير صالح", "inválido", "invalide", "ungültig", "недопустимый"},
	Missing:    LocStr{"missing", "falta", "缺少", "गुम", "مفقود", "ausente", "manquant", "fehlend", "отсутствует"},
	Negative:   LocStr{"negative", "negativo", "负", "नकारात्मक", "سالب", "negativo", "négatif", "negativ", "отрицательный"},
	NonNumeric: LocStr{"non-numeric", "no numérico", "非数字", "गैर-संख्यात्मक", "غير رقمي", "não numérico", "non numérique", "nicht numerisch", "нечисловой"},
	Not:        LocStr{"not", "no", "不", "नहीं", "ليس", "não", "pas", "nicht", "не"},
	Number:     LocStr{"number", "número", "数字", "संख्या", "رقم", "número", "nombre", "Zahl", "число"},
	Numbers:    LocStr{"numbers", "números", "数字", "संख्याएं", "أرقام", "números", "nombres", "Zahlen", "числа"},
	Of:         LocStr{"of", "de", "的", "का", "من", "de", "de", "von", "из"},
	Out:        LocStr{"out", "fuera", "出", "बाहर", "خارج", "fora", "hors", "aus", "вне"},
	Overflow:   LocStr{"overflow", "desbordamiento", "溢出", "ओवरफ्लो", "فيض", "estouro", "débordement", "Überlauf", "переполнение"},
	Range:      LocStr{"range", "rango", "范围", "रेंज", "نطاق", "intervalo", "plage", "Bereich", "диапазон"},
	Required:   LocStr{"required", "requerido", "必需", "आवश्यक", "مطلوب", "necessário", "requis", "erforderlich", "обязательный"},
	Round:      LocStr{"round", "redondear", "圆", "गोल", "جولة", "arredondar", "arrondir", "runden", "округлить"},
	Specifier:  LocStr{"specifier", "especificador", "说明符", "निर्दिष्टकर्ता", "محدد", "especificador", "spécificateur", "Spezifizierer", "спецификатор"},
	String:     LocStr{"string", "cadena", "字符串", "स्ट्रिंग", "سلسلة", "string", "chaîne", "Zeichenkette", "строка"},
	Supported:  LocStr{"supported", "soportado", "支持", "समर्थित", "مدعوم", "suportado", "pris en charge", "unterstützt", "поддерживается"},
	Type:       LocStr{"type", "tipo", "类型", "प्रकार", "نوع", "tipo", "type", "Typ", "тип"},
	Unknown:    LocStr{"unknown", "desconocido", "未知", "अज्ञात", "غير معروف", "desconhecido", "inconnu", "unbekannt", "неизвестный"},
	Unsigned:   LocStr{"unsigned", "sin signo", "无符号", "अहस्ताक्षरित", "غير موقع", "sem sinal", "non signé", "vorzeichenlos", "безzнаковый"},
	Value:      LocStr{"value", "valor", "值", "मूल्य", "قيمة", "valor", "valeur", "Wert", "значение"},
}

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.

Functions

func Contains added in v0.0.8

func Contains(conv, search string) bool

Contains checks if the string 'search' is present in 'conv' Returns true if found, false otherwise This matches the behavior of the standard library strings.Contains

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 Count added in v0.1.6

func Count(conv, search string) int

Count checks how many times the string 'search' is present in 'conv' eg: "hello world" with search "world" will return 1

func Err added in v0.0.37

func Err(msgs ...any) *conv

func Errf added in v0.1.3

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

Errf creates a new conv instance with error formatting similar to fmt.Errf Example: tinystring.Errf("invalid value: %s", value).Error()

func Fmt added in v0.1.3

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 OutLang added in v0.1.3

func OutLang(l ...lang)

OutLang sets the default output language OutLang() without parameters auto-detects system language OutLang(ES) sets Spanish as default

func ParseKeyValue added in v0.0.10

func ParseKeyValue(in string, delimiters ...string) (value string, err error)

ParseKeyValue extracts the value part from a "key:value" formatted string. By default, it uses ":" as the delimiter but accepts an optional custom delimiter. The function returns the value part and an error (nil if successful).

Examples:

value, err := ParseKeyValue("name:John")
// value = "John", err = nil

value, err := ParseKeyValue("data=123", "=")
// value = "123", err = nil

value, err := ParseKeyValue("invalid-string")
// value = "", err = error containing "delimiter ':' not found in string invalid-string"

func Split added in v0.0.7

func Split(data string, separator ...string) (out []string)

func T added in v0.1.3

func T(values ...any) string

T 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: T(D.Format, D.Invalid) returns "invalid format" T(ES, D.Format, D.Invalid) returns "formato inválido"

Types

type LocStr added in v0.1.4

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.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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