tinystring

package module
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Jun 19, 2025 License: MIT Imports: 3 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 13 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?

Go's WebAssembly potential is incredible, but traditional applications face a critical challenge: massive binary sizes that make web deployment impractical.

The Problem

Every Go project needs string manipulation, type conversion, and error handling - but importing standard library packages (fmt, strings, strconv, errors) creates significant binary bloat that hurts:

  • 🌐 Web app performance - Slow loading times and poor user experience
  • Edge deployment - Resource constraints on small devices
  • 🚀 Distribution efficiency - Large binaries for simple operations
The Solution

TinyString replaces multiple standard library packages with lightweight, manual implementations that deliver:

  • 🏆 Up to smaller binaries - Dramatic size reduction for WebAssembly
  • Full TinyGo compatibility - No compilation issues or warnings
  • 🎯 Predictable performance - No hidden allocations or overhead
  • 🔧 Familiar API - Drop-in replacement for standard library functions

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").RemoveTilde().ToLower().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).RemoveTilde().CamelCaseLower().Apply()
// original is now: "elMurcielagoRapido"

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

OutLang(ES) // Set Spanish
err := Err(D.Invalid, D.Fmt)
// 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().ToLower().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).ToUpper().RemoveTilde().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.ToLower() Convert(s).ToLower().String()
strings.ToUpper() Convert(s).ToUpper().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").ToUpper().String() + " " + 
          tinystring.Convert("World").ToLower().String() + "!"
// Multiple Convert() calls = multiple allocations

// ✅ Builder approach - single allocation
result := tinystring.Convert().
    Write("Hello").ToUpper().
    Write(" ").
    Write("World").ToLower().
    Write("!").
    String()
// Single Convert() + reused buffer = optimal performance
String Transformations
// Case conversions
tinystring.Convert("HELLO").ToLower().String()              // out: "hello"
tinystring.Convert("world").ToUpper().String()              // out: "WORLD"
tinystring.Convert("hello world").Capitalize().String()     // out: "Hello World"

// Advanced case styles
tinystring.Convert("hello world").CamelCaseLower().String()   // out: "helloWorld"
tinystring.Convert("hello world").CamelCaseUpper().String()   // out: "HelloWorld"
tinystring.Convert("hello world").ToSnakeCaseLower().String() // out: "hello_world"
tinystring.Convert("hello world").ToSnakeCaseUpper().String() // out: "HELLO_WORLD"
String Search & Operations
// Search and count
found := tinystring.Contains("hello world", "world")              // out: true
count := tinystring.CountOccurrences("abracadabra", "abra")       // out: 2

// 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).ToFloat()
strconv.ParseBool() Convert(s).ToBool()
strconv.FormatFloat() Convert(f).RoundDecimals(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").ToFloat()     // 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
tinystring.Convert(3.154).RoundDecimals(2).String()           // out: "3.16" (ceiling)
tinystring.Convert(3.154).RoundDecimals(2).Down().String()    // out: "3.15" (floor)

// Number formatting with thousands separator
tinystring.Convert(2189009.00).FormatNumber().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
// Simple error creation
err := tinystring.Err("invalid input")
// out: "invalid input"

// Multiple error messages
err := tinystring.Err("invalid format", "expected number")
// out: "invalid format expected number"

// 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

🌍 Multilingual Error Messages

TinyString includes a comprehensive dictionary system for creating multilingual error messages:

import . "github.com/cdvelop/tinystring"

// Configure default language
OutLang(ES) // Spanish

// Use dictionary words to create error messages
err := Err(D.Invalid, D.Fmt)
// out: "inválido formato" (Spanish)

// Complex error message composition
err := Err(D.Negative, D.Numbers, D.Not, D.Supported)
// out: "negativo números no soportado" (Spanish)

// Mix languages inline
err := Err(FR, D.Empty, D.String)
// out: "vide chaîne" (French)

// Auto-detect system language
OutLang() // Detects browser/OS language automatically
err := Err(D.Cannot, D.Round, D.NonNumeric, D.Value)
// Output in user's system language
🗣️ Supported Languages

The dictionary system supports 13 languages:

  • 🇺🇸 EN - English (default)
  • 🇪🇸 ES - Spanish
  • 🇧🇷 PT - Portuguese
  • 🇫🇷 FR - French
  • 🇷🇺 RU - Russian
  • 🇩🇪 DE - German
  • 🇮🇹 IT - Italian
  • 🇮🇳 HI - Hindi
  • 🇧🇩 BN - Bengali
  • 🇮🇩 ID - Indonesian
  • 🇸🇦 AR - Arabic
  • 🇵🇰 UR - Urdu
  • 🇨🇳 ZH - Chinese
📖 Dictionary Words

The dictionary contains essential words for error composition:

// Common error words (alphabetically sorted)
D.Argument    // "argument", "argumento", "argumento", "argument"...
D.Base        // "base", "base", "base", "base"...
D.Cannot      // "cannot", "no puede", "não pode", "ne peut pas"...
D.Empty       // "empty", "vacío", "vazio", "vide"...
D.Fmt      // "format", "formato", "formato", "format"...
D.Invalid     // "invalid", "inválido", "inválido", "invalide"...
D.Missing     // "missing", "falta", "ausente", "manquant"...
D.Number      // "number", "número", "número", "nombre"...
D.String      // "string", "cadena", "string", "chaîne"...
D.Supported   // "supported", "soportado", "suportado", "pris en charge"...
D.Type        // "type", "tipo", "tipo", "type"...
D.Value       // "value", "valor", "valor", "valeur"...
// ... and more
🎨 Custom Dictionary Extensions

Create your own dictionary words for domain-specific errors:

// Define custom dictionary for your application
type MyDict struct {
    User     OL
    Email    OL
    Password OL
    Login    OL
}

// Initialize with translations
var MD = MyDict{
    User: OL{
        "user",            // EN
        "usuario",         // ES
        "usuário",         // PT
        "utilisateur",     // FR
        "пользователь",    // RU
        "Benutzer",        // DE
        "utente",          // IT
        "उपयोगकर्ता",      // HI
        "ব্যবহারকারী",     // BN
        "pengguna",        // ID
        "مستخدم",         // AR
        "صارف",           // UR
        "用户",            // ZH
    },
    Email: OL{
        "email",           // EN
        "correo",          // ES
        "email",           // PT
        "courriel",        // FR
        "электронная почта", // RU
        "E-Mail",          // DE
        "email",           // IT
        "ईमेल",            // HI
        "ইমেইল",           // BN
        "email",           // ID
        "بريد إلكتروني",   // AR
        "ای میل",          // UR
        "邮箱",            // ZH
    },
    // ... more custom words
}

// Combine system dictionary with custom words
OutLang(ES) // Spanish
err := Err(MD.User, D.Not, D.Found)
// out: "usuario no encontrado"

err := Err(D.Fmt,MD.Email, D.Invalid) 
// out: "formato correo inválido"
🔧 Language Configuration
// Set specific language
OutLang(ES)    // Spanish
OutLang(FR)    // French
OutLang(ZH)    // Chinese

// Auto-detect system language
OutLang()      // Detects from environment variables (backend) or browser (WASM)

// Override language inline
err := Err(DE, D.Invalid, D.Value)  // Force German
// out: "ungültig Wert"

Features not available in Go's standard library:

🌍 Multilingual Dictionary System

TinyString includes a comprehensive multilingual error system with zero external dependencies:

import . "github.com/cdvelop/tinystring"

// Configure language (auto-detects system language by default)
OutLang(ES) // Set Spanish as default

// Create translated error messages using dictionary words
err := Err(D.Invalid, D.Fmt).Error()
// out: "inválido formato" (Spanish)

// Complex compositions
err := Err(D.Negative, D.Numbers, D.Not, D.Supported, D.For, D.Unsigned, D.Integer).Error()
// out: "negativo números no soportado para sin signo entero" (Spanish)

// Language override inline
err := Err(FR, D.Cannot, D.Round, D.NonNumeric, D.Value).Error()
// out: "ne peut pas arrondir non numérique valeur" (French)

// Mixed with regular strings (backward compatible)
err := Err(D.Invalid, "user input:", "abc123").Error()
// out: "inválido user input: abc123"
🎯 Dictionary Features
  • 13 Languages Supported: EN, ES, PT, FR, RU, DE, IT, HI, BN, ID, AR, UR, ZH
  • 35+ Essential Words: Alphabetically sorted for maximum reusability
  • Composable Messages: Build complex errors from simple words
  • Zero Dependencies: No external translation libraries
  • TinyGo Compatible: Full WebAssembly support
  • Auto-Detection: Automatically detects system/browser language
  • Extensible: Create your own dictionary words
  • Backward Compatible: Works with existing string-based errors
🌍 Unicode & Localization
// Remove accents and diacritics
tinystring.Convert("café naïve résumé").RemoveTilde().String()  // out: "cafe naive resume"
tinystring.Convert("Ñoño niño").RemoveTilde().String()          // out: "Nono nino"
✂️ 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
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").ToSnakeCaseLower("-").String() // out: "hello-world"
tinystring.Convert("hello world").ToSnakeCaseUpper("_").String() // out: "HELLO_WORLD"

🌍 Complete Multilingual Example

Here's a practical example showing how to build a multilingual application:

package main

import . "github.com/cdvelop/tinystring"

func main() {
    // Auto-detect user's language
    OutLang() // Detects from environment/browser
    
    // Validation function with multilingual errors
    validateUserInput := func(input string) error {
        if input == "" {
            return Err(D.Empty, D.String, D.Not, D.Supported)
        }
        
        if len(input) < 3 {
            return Err(D.String, D.Value, "too short")
        }
        
        // Try to parse as number
        if _, err := Convert(input).ToInt(); err != nil {
            return Err(D.Invalid, D.Number, D.Fmt)
        }
        
        return nil
    }
    
    // Test with different inputs
    inputs := []string{"", "ab", "not_a_number", "123"}
    
    for _, input := range inputs {
        if err := validateUserInput(input); err != nil {
            output := Fmt("Input '%s': %s", input, err.Error())
            // out: "Input '': empty string not supported"
        } else {
            output := Fmt("Input '%s': OK", input)
            // out: "Input '123': OK"
        }
    }
    
    // Switch language dynamically
    OutLang(ES)
    
    // Same validation, different language
    if err := validateUserInput(""); err != nil {
        spanishError := err.Error()
        // out: "vacío cadena no soportado"
    }
    
    // Force specific language for specific errors
    criticalErr := Err(ZH, D.Cannot, D.Fmt, D.NonNumeric, D.Value)
    chineseError := criticalErr.Error()
    // out: "不能 格式 非数字 值"
}

// Example outputs (depends on system language):
// Input '': "empty string not supported"
// Input 'ab': "string value too short"  
// Input 'not_a_number': "invalid number format"
// Input '123': "OK"
//
// After switching to Spanish:
// Error: "vacío cadena no soportado"
// Chinese error: "不能 格式 非数字 值"

💡 Performance Tips

Memory Optimization
// ✅ Efficient: Modify original string directly
original := "Él Múrcielago Rápido"
tinystring.Convert(&original).RemoveTilde().ToLower().Apply()
// original is now modified in-place

// ❌ Less efficient: Creates new string
original := "Él Múrcielago Rápido"  
result := tinystring.Convert(original).RemoveTilde().ToLower().String()
Chaining Operations
// Combine multiple operations efficiently
result := tinystring.Convert("  HÓLA MÚNDO  ")
    .Trim()
    .RemoveTilde()
    .ToLower()
    .Replace(" ", "_")
    .String()
// out: "hola_mundo"

🔄 Output Methods: String() vs Apply()

Choose between two approaches for finalizing operations:

// ✅ String() - Returns result, keeps original unchanged
originalText := "Él Múrcielago Rápido"
result := tinystring.Convert(&originalText).RemoveTilde().ToLower().String()
// result: "el murcielago rapido"
// originalText: "Él Múrcielago Rápido" (unchanged)

// ✅ Apply() - Modifies original string directly (memory efficient)
originalText := "Él Múrcielago Rápido"
tinystring.Convert(&originalText).RemoveTilde().ToLower().Apply()
// originalText: "el murcielago rapido" (modified in-place)

Binary Size Comparison

Standard Library Example | TinyString Example

Last updated: 2025-06-18 23:51:33

Build Type Parameters Standard Library
go build
TinyString
tinygo build
Size Reduction Performance
🖥️ Default Native -ldflags="-s -w" 1.3 MB 1.1 MB -175.0 KB 13.3%
🌐 Default WASM (default -opt=z) 580.8 KB 322.7 KB -258.2 KB 44.4%
🌐 Ultra WASM -no-debug -panic=trap -scheduler=none -gc=leaking -target wasm 141.3 KB 40.4 KB -100.9 KB 🏆 71.4%
🌐 Speed WASM -opt=2 -target wasm 827.0 KB 391.9 KB -435.1 KB 52.6%
🌐 Debug WASM -opt=0 -target wasm 1.8 MB 1.0 MB -802.3 KB 43.8%
🎯 Performance Summary
  • 🏆 Peak Reduction: 71.4% (Best optimization)
  • Average WebAssembly Reduction: 53.1%
  • Average Native Reduction: 13.3%
  • 📦 Total Size Savings: 1.7 MB across all builds
Performance Legend
  • ❌ Poor (<5% reduction)
  • ➖ Fair (5-15% reduction)
  • ✅ Good (15-70% reduction)
  • 🏆 Outstanding (>70% reduction)

Memory Usage Comparison

Standard Library Example | TinyString Example

Last updated: 2025-06-18 23:51:51

Performance benchmarks comparing memory allocation patterns between standard Go library and TinyString:

🧪 Benchmark Category 📚 Library 💾 Memory/Op 🔢 Allocs/Op ⏱️ Time/Op 📈 Memory Trend 🎯 Alloc Trend 🏆 Performance
📝 String Processing 📊 Standard 1.2 KB 48 3.4μs - - -
🚀 TinyString 2.8 KB 119 14.1μs 140.3% more 147.9% more Poor
🔢 Number Processing 📊 Standard 912 B 42 2.7μs - - -
🚀 TinyString 2.5 KB 87 5.8μs 177.3% more 107.1% more Poor
🔄 Mixed Operations 📊 Standard 512 B 26 1.9μs - - -
🚀 TinyString 1.2 KB 52 5.2μs 144.9% more 100.0% more Poor
🎯 Performance Summary
  • 💾 Memory Efficiency: ❌ Poor (Significant overhead) (154.2% average change)
  • 🔢 Allocation Efficiency: ❌ Poor (Excessive allocations) (118.4% average change)
  • 📊 Benchmarks Analyzed: 3 categories
  • 🎯 Optimization Focus: Binary size reduction vs runtime efficiency
⚖️ Trade-offs Analysis

The benchmarks reveal important trade-offs between binary size and runtime performance:

📦 Binary Size Benefits
  • 🏆 16-84% smaller compiled binaries
  • 🌐 Superior WebAssembly compression ratios
  • 🚀 Faster deployment and distribution
  • 💾 Lower storage requirements
🧠 Runtime Memory Considerations ⚠️
  • 📈 Higher allocation overhead during execution
  • 🗑️ Increased GC pressure due to allocation patterns
  • Trade-off optimizes for distribution size over runtime efficiency
  • 🔄 Different optimization strategy than standard library
🎯 Optimization Recommendations
🎯 Use Case 💡 Recommendation 🔧 Best For
🌐 WebAssembly Apps TinyString Size-critical web deployment
📱 Embedded Systems TinyString Resource-constrained devices
☁️ Edge Computing TinyString Fast startup and deployment
🏢 Memory-Intensive Server ⚠️ Standard Library High-throughput applications
🔄 High-Frequency Processing ⚠️ Standard Library Performance-critical workloads
📊 Performance Legend
  • 🏆 Excellent (Better performance)
  • Good (Acceptable trade-off)
  • ⚠️ Caution (Higher resource usage)
  • Poor (Significant overhead)

Contributing

This project is currently being self-financed and developed independently. The development, testing, maintenance, and improvements are funded entirely out of my personal resources and time.

If you find this project useful and would like to support its continued development, you can make a donation here with PayPal. Your support helps cover:

  • 💻 Development time and effort
  • 🧪 Testing and quality assurance
  • 📚 Documentation improvements
  • 🔧 Bug fixes and feature enhancements
  • 🌐 Community support and maintenance

Any contribution, however small, is greatly appreciated and directly impacts the project's future development. 🙌

License

MIT 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).RemoveTilde().ToLower().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).RemoveTilde().CamelCaseLower().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).RemoveTilde().ToLower().String()
fmt.Println(processedText)

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

texto con acentos
otro texto con acentos

Index

Examples

Constants

View Source
const (
	EN lang = iota // 0 - English (default)
	ES             // 1 - Spanish
	PT             // 2 - Portuguese
	FR             // 3 - French
	RU             // 4 - Russian
	DE             // 5 - German
	IT             // 6 - Italian
	HI             // 7 - Hindi
	BN             // 8 - Bengali
	ID             // 9 - Indonesian
	AR             // 10 - Arabic
	UR             // 11 - Urdu
	ZH             // 12 - Chinese
)

Variables

View Source
var D = dictionary{

	Argument:         OL{"argument", "argumento", "argumento", "argument", "аргумент", "Argument", "argomento", "तर्क", "যুক্তি", "argumen", "وسيط", "دلیل", "参数"},
	At:               OL{"at", "en", "em", "à", "в", "bei", "a", "पर", "এ", "di", "في", "میں", "在"},
	Base:             OL{"base", "base", "base", "base", "основание", "Basis", "base", "आधार", "ভিত্তি", "basis", "قاعدة", "بنیاد", "进制"},
	Boolean:          OL{"boolean", "booleano", "booleano", "booléen", "логический", "boolescher", "booleano", "बूलियन", "বুলিয়ান", "boolean", "منطقي", "بولین", "布尔"},
	Cannot:           OL{"cannot", "no puede", "não pode", "ne peut pas", "не может", "kann nicht", "non può", "नहीं कर सकते", "পারে না", "tidak bisa", "لا يمكن", "نہیں کر سکتے", "不能"},
	Empty:            OL{"empty", "vacío", "vazio", "vide", "пустой", "leer", "vuoto", "खाली", "খালি", "kosong", "فارغ", "خالی", "空"},
	End:              OL{"end", "fin", "fim", "fin", "конец", "Ende", "fine", "अंत", "শেষ", "akhir", "نهاية", "اختتام", "结束"},
	Float:            OL{"float", "flotante", "flutuante", "flottant", "число с плавающей точкой", "Gleitkomma", "virgola mobile", "फ्लोट", "ফ্লোট", "float", "عائم", "فلوٹ", "浮点"},
	For:              OL{"for", "para", "para", "pour", "для", "für", "per", "के लिए", "জন্য", "untuk", "لـ", "کے لیے", "为"},
	Fmt:              OL{"format", "formato", "formato", "format", "формат", "Fmt", "formato", "प्रारूप", "বিন্যাস", "format", "تنسيق", "فارمیٹ", "格式"},
	Found:            OL{"found", "encontrado", "encontrado", "trouvé", "найден", "gefunden", "trovato", "मिला", "পাওয়া", "ditemukan", "موجود", "ملا", "找到"},
	Integer:          OL{"integer", "entero", "inteiro", "entier", "целое число", "ganze Zahl", "intero", "पूर्णांक", "পূর্ণসংখ্যা", "integer", "عدد صحيح", "انٹیجر", "整数"},
	Invalid:          OL{"invalid", "inválido", "inválido", "invalide", "недопустимый", "ungültig", "non valido", "अमान्य", "অবৈধ", "tidak valid", "غير صالح", "غیر درست", "无效"},
	Missing:          OL{"missing", "falta", "ausente", "manquant", "отсутствует", "fehlend", "mancante", "गुम", "অনুপস্থিত", "hilang", "مفقود", "غائب", "缺少"},
	Negative:         OL{"negative", "negativo", "negativo", "négatif", "отрицательный", "negativ", "negativo", "नकारात्मक", "নেগেটিভ", "negatif", "سالب", "منفی", "负"},
	NegativeUnsigned: OL{"negative numbers are not supported for unsigned integers", "números negativos no soportados para enteros sin signo", "números negativos não suportados para inteiros sem sinal", "nombres négatifs non pris en charge pour les entiers non signés", "отрицательные числа не поддерживаются для беззнаковых целых чисел", "negative Zahlen werden für vorzeichenlose Ganzzahlen nicht unterstützt", "numeri negativi non supportati per interi senza segno", "नकारात्मक संख्याएं अहस्ताक्षरित पूर्णांकों के लिए समर्थित नहीं हैं", "স্বাক্ষরহীন পূর্ণসংখ্যার জন্য নেগেটিভ সংখ্যা সমর্থিত নয়", "angka negatif tidak didukung untuk integer tanpa tanda", "الأرقام السالبة غير مدعومة للأعداد الصحيحة غير الموقعة", "منفی نمبرز غیر دستخط انٹیجرز کے لیے معاون نہیں", "无符号整数不支持负数"},
	NonNumeric:       OL{"non-numeric", "no numérico", "não numérico", "non numérique", "нечисловой", "nicht numerisch", "non numerico", "गैर-संख्यात्मक", "অ-সংখ্যাসূচক", "non-numerik", "غير رقمي", "غیر عددی", "非数字"},
	Not:              OL{"not", "no", "não", "pas", "не", "nicht", "non", "नहीं", "না", "tidak", "ليس", "نہیں", "不"},
	Number:           OL{"number", "número", "número", "nombre", "число", "Zahl", "numero", "संख्या", "সংখ্যা", "angka", "رقم", "نمبر", "数字"},
	Numbers:          OL{"numbers", "números", "números", "nombres", "числа", "Zahlen", "numeri", "संख्याएं", "সংখ্যা", "angka", "أرقام", "نمبرز", "数字"},
	Of:               OL{"of", "de", "de", "de", "из", "von", "di", "का", "এর", "dari", "من", "کا", "的"},
	One:              OL{"one", "uno", "um", "un", "один", "eins", "uno", "एक", "একটি", "satu", "واحد", "ایک", "一"},
	Only:             OL{"only", "solo", "apenas", "seulement", "только", "nur", "solo", "केवल", "শুধুমাত্র", "hanya", "فقط", "صرف", "仅"},
	Overflow:         OL{"overflow", "desbordamiento", "estouro", "débordement", "переполнение", "Überlauf", "overflow", "ओवरफ्लो", "ওভারফ্লো", "overflow", "فيض", "اوور فلو", "溢出"},
	Range:            OL{"range", "rango", "intervalo", "plage", "диапазон", "Bereich", "intervallo", "रेंज", "পরিসর", "rentang", "نطاق", "رینج", "范围"},
	Required:         OL{"required", "requerido", "necessário", "requis", "обязательный", "erforderlich", "richiesto", "आवश्यक", "প্রয়োজনীয়", "diperlukan", "مطلوب", "ضروری", "必需"},
	Round:            OL{"round", "redondear", "arredondar", "arrondir", "округлить", "runden", "arrotondare", "गोल", "গোল", "bulatkan", "جولة", "گول", "圆"},
	Specifier:        OL{"specifier", "especificador", "especificador", "spécificateur", "спецификатор", "Spezifizierer", "specificatore", "निर्दिष्टकर्ता", "নির্দিষ্টকারী", "penentu", "محدد", "تعین کنندہ", "说明符"},
	String:           OL{"string", "cadena", "string", "chaîne", "строка", "Zeichenkette", "stringa", "स्ट्रिंग", "স্ট্রিং", "string", "سلسلة", "سٹرنگ", "字符串"},
	Supported:        OL{"supported", "soportado", "suportado", "pris en charge", "поддерживается", "unterstützt", "supportato", "समर्थित", "সমর্থিত", "didukung", "مدعوم", "معاون", "支持"},
	Text:             OL{"text", "texto", "texto", "texte", "текст", "Text", "testo", "पाठ", "পাঠ", "teks", "نص", "متن", "文本"},
	Type:             OL{"type", "tipo", "tipo", "type", "тип", "Typ", "tipo", "प्रकार", "টাইপ", "tipe", "نوع", "قسم", "类型"},
	Unknown:          OL{"unknown", "desconocido", "desconhecido", "inconnu", "неизвестный", "unbekannt", "sconosciuto", "अज्ञात", "অজানা", "tidak diketahui", "غير معروف", "نامعلوم", "未知"},
	Unsigned:         OL{"unsigned", "sin signo", "sem sinal", "non signé", "беззнаковый", "vorzeichenlos", "senza segno", "अहस्ताक्षरित", "স্বাক্ষরহীন", "tidak bertanda", "غير موقع", "غیر دستخط شدہ", "无符号"},
	Unsupported:      OL{"unsupported", "no soportado", "não suportado", "non pris en charge", "не поддерживается", "nicht unterstützt", "non supportato", "असमर्थित", "অসমর্থিত", "tidak didukung", "غير مدعوم", "غیر معاون", "不支持"},
	Value:            OL{"value", "valor", "valor", "valeur", "значение", "Wert", "valore", "मूल्य", "মান", "nilai", "قيمة", "قیمت", "值"},
	Wrong:            OL{"wrong", "incorrecto", "errado", "mauvais", "неправильный", "falsch", "sbagliato", "गलत", "ভুল", "salah", "خطأ", "غلط", "错误"},
}

Global dictionary instance - populated with all translations using horizontal format

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 CountOccurrences added in v0.0.8

func CountOccurrences(conv, search string) int

CountOccurrences 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(values ...any) *conv

Err creates a new error message with support for multilingual translations REFACTORED: Uses T function and pool for optimal performance Supports OL types for translations and lang types for language specification Maintains backward compatibility with existing string-based errors eg: tinystring.Err("invalid format") returns "invalid format" tinystring.Err(D.Invalid, D.Fmt) returns "invalid format" tinystring.Err(ES,D.Fmt, D.Invalid) returns "formato inválido"

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) *conv

Fmt creates a new conv instance with variadic formatting similar to fmt.Sprintf Example: tinystring.Fmt("Hello %s, you have %d messages", "Alice", 5).String() with error: out, err := tinystring.Fmt("Hello %s, you have %d messages", "Alice", 5).StringError()

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

Types

type OL added in v0.1.3

type OL [13]string

OL represents Output Language translations using fixed array for efficiency

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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