tinystring

package module
v0.0.33 Latest Latest
Warning

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

Go to latest
Published: Jun 3, 2025 License: MIT Imports: 2 Imported by: 14

README

TinyString

TinyString is a lightweight Go library that provides text manipulation 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
  • 🔄 Common text transformations - All essential string operations included
  • 🧵 Concurrency safe - Thread-safe operations
  • 📦 Zero standard library dependencies - No fmt, strings, or strconv imports
  • 🎯 TinyGo compatible - Optimized for minimal binary size and embedded systems
  • 🌐 Web-ready - Perfect for WebAssembly deployments
  • 🔄 Universal type conversion - Support for converting any data type to string
  • Performance optimized - Manual implementations avoid standard library overhead
  • �️ Easily extensible - Clean architecture for adding new operations

Why TinyString?

Traditional Go string libraries rely heavily on the standard library (fmt, strings, strconv), which can significantly increase binary size when using TinyGo for embedded systems or WebAssembly targets. TinyString provides all essential string operations with manual implementations that:

  • ✅ Reduce binary size by avoiding standard library imports
  • ✅ Ensure TinyGo compatibility without compilation issues
  • ✅ Provide predictable performance without hidden allocations
  • ✅ Enable deployment to resource-constrained environments
  • ✅ Support WebAssembly with minimal overhead

Installation

go get github.com/cdvelop/tinystring

TinyGo Optimization

TinyString is specifically designed for environments where binary size matters. Unlike other string libraries that import standard packages like fmt, strings, and strconv, TinyString implements all functionality manually to achieve significant binary size reductions and optimal WebAssembly compatibility.

Technical Implementation

TinyString achieves its goals through manual implementations of commonly used standard library functions:

Replaced Standard Library Functions
Standard Library TinyString Implementation Purpose
strconv.ParseFloat parseFloatManual String to float conversion
strconv.FormatFloat floatToStringManual Float to string conversion
strconv.ParseInt parseIntManual String to integer conversion
strconv.FormatInt intToStringOptimized Integer to string conversion
strings.IndexByte indexByteManual Byte search in strings
fmt.Sprintf Custom sprintf implementation String formatting
Performance Benefits
  • No hidden allocations from standard library calls
  • Predictable memory usage with manual control
  • Reduced binary bloat from unused standard library code
  • TinyGo compatibility without compilation warnings
  • Custom optimizations for common use cases

Usage

import "github.com/cdvelop/tinystring"

// Basic example with string
text := tinystring.Convert("MÍ téxtO").RemoveTilde().String()
// Result: "MI textO"

// Examples with other data types
numText := tinystring.Convert(42).String()
// Result: "42"

boolText := tinystring.Convert(true).ToUpper().String()
// Result: "TRUE"

floatText := tinystring.Convert(3.14).String()
// Result: "3.14"

// Chaining operations
text := tinystring.Convert("Él Múrcielago Rápido")
    .RemoveTilde()
    .CamelCaseLower()
    .String()
// Result: "elMurcielagoRapido"

// Working with string pointers (avoids extra allocations)
// This method reduces memory allocations by modifying the original string directly
originalText := "Él Múrcielago Rápido"
tinystring.Convert(&originalText).RemoveTilde().CamelCaseLower().Apply()
// originalText is now modified directly: "elMurcielagoRapido"
Available Operations
  • Convert(v any): Initialize text processing with any data type (string, *string, int, float, bool, etc.). When using a string pointer (*string) along with the Apply() method, the original string will be modified directly, avoiding extra memory allocations.
  • Apply(): Updates the original string pointer with the current content. This method should be used when you want to modify the original string directly without additional allocations.
  • String(): Returns the content of the text as a string without modifying any original pointers.
  • RemoveTilde(): Removes accents and diacritics (e.g. "café" -> "cafe")
  • ToLower(): Converts to lowercase (e.g. "HELLO" -> "hello")
  • ToUpper(): Converts to uppercase (e.g. "hello" -> "HELLO")
  • Capitalize(): Capitalizes the first letter of each word (e.g. "hello world" -> "Hello World")
  • CamelCaseLower(): Converts to camelCase (e.g. "hello world" -> "helloWorld")
  • CamelCaseUpper(): Convert to UpperCase (e.g. "hello world" -> "HelloWorld")
  • ToSnakeCaseLower(): Converts to snake_case (e.g. "hello world" -> "hello_world"), With Other Params: ToSnakeCaseLower("-") -> "hello-world"
  • ToSnakeCaseUpper(): Convert to SNAKE_CASE (e.g. "hello world" -> "HELLO_WORLD"), With Other Params: ToSnakeCaseUpper("-") -> "HELLO-WORLD"
  • Split(data, separator string): Divides a string by a separator and returns a slice of substrings
  • Join(sep ...string): Joins elements of a string slice with a specified separator (default: space). (e.g. Convert([]string{"Hello", "World"}).Join() -> "Hello World" or Convert([]string{"Hello", "World"}).Join("-") -> "Hello-World")
  • ParseKeyValue(input string, delimiter string): Extracts the value from a key:value string format (e.g. ParseKeyValue("name:John") -> "John", nil)
  • Replace(old, new any, n ...int): Replaces occurrences of a substring. If n is provided, replaces up to n occurrences. If n < 0 or not provided, replaces all. The old and new parameters can be of any type (string, int, float, bool) and will be converted to string automatically. (e.g. "hello world" -> "hello universe" or "value 123 here" -> "value 456 here")
  • TrimPrefix(prefix string): Removes a specified prefix from the beginning of a string (e.g. "prefix-content" -> "content")
  • TrimSuffix(suffix string): Removes a specified suffix from the end of a string (e.g. "file.txt" -> "file")
  • Trim(): Removes spaces from the beginning and end of a string (e.g. " hello " -> "hello")
  • Contains(text, search string): Checks if a string contains another, returns boolean (e.g. Contains("hello world", "world") -> true)
  • CountOccurrences(text, search string): Counts how many times a string appears in another (e.g. CountOccurrences("hello hello world", "hello") -> 2)
  • Repeat(n int): Repeats the string n times (e.g. "abc".Repeat(3) -> "abcabcabc")
  • Truncate(maxWidth any, reservedChars ...any): Truncates text so that it does not exceed the specified width, adding ellipsis if necessary. If the text is shorter or equal, it remains unchanged. The maxWidth parameter accepts any numeric type. The reservedChars parameter is optional and also accepts any numeric type. (e.g. "Hello, World!".Truncate(10) -> "Hello, ..." or "Hello, World!".Truncate(10, 3) -> "Hell...")
  • TruncateName(maxCharsPerWord any, maxWidth any): Truncates names and surnames in a user-friendly way for displaying in limited spaces like chart labels. It adds abbreviation dots where appropriate and handles the first word specially when there are more than 2 words. Parameters: maxCharsPerWord (maximum characters per word), maxWidth (maximum total length). (e.g. Convert("Jeronimo Dominguez").TruncateName(3, 15) -> "Jer. Dominguez")
  • RoundDecimals(decimals int): Rounds a numeric value to the specified number of decimal places with ceiling rounding by default (e.g. Convert(3.154).RoundDecimals(2).String() -> "3.16")
  • Down(): Modifies rounding behavior to floor rounding (must be used after RoundDecimals, e.g. Convert(3.154).RoundDecimals(2).Down().String() -> "3.15")
  • FormatNumber(): Formats a number with thousand separators and removes trailing zeros after the decimal point (e.g. Convert(2189009.00).FormatNumber().String() -> "2.189.009")
  • Format(format string, args ...any): Static function for sprintf-style string formatting with support for %s, %d, %f, %b, %x, %o, %v, %% specifiers (e.g. Format("Hello %s, you have %d messages", "John", 5) -> "Hello John, you have 5 messages")
  • StringError(): Returns both the string result and any error that occurred during processing (e.g. result, err := Convert("123").ToInt(); text, err2 := FromInt(result).StringError())
  • Quote(): Wraps the string content in quotes with proper escaping of special characters (e.g. Convert("hello").Quote().String() -> "\"hello\"")
  • ToBool(): Converts text content to boolean, supporting string boolean values and numeric values where non-zero = true (e.g. Convert("true").ToBool() -> true, nil or Convert(42).ToBool() -> true, nil)
  • FromBool(value bool): Creates a new Text instance from a boolean value (e.g. FromBool(true).String() -> "true")
  • ToInt(base ...int): Converts text content to integer with optional base, supports float truncation (e.g. Convert("123").ToInt() -> 123, nil)
  • ToUint(base ...int): Converts text content to unsigned integer with optional base, supports float truncation (e.g. Convert("456").ToUint() -> 456, nil)
  • ToFloat(): Converts text content to float64 (e.g. Convert("3.14").ToFloat() -> 3.14, nil)
  • FromInt(value int, base ...int): Creates a new Text instance from an integer with optional base (e.g. FromInt(42).String() -> "42")
  • FromUint(value uint, base ...int): Creates a new Text instance from an unsigned integer with optional base (e.g. FromUint(123).String() -> "123")
  • FromFloat(value float64): Creates a new Text instance from a float64 value (e.g. FromFloat(3.14).String() -> "3.14")
Enhanced Type Conversion and Formatting

TinyString now supports comprehensive type conversion with error handling and advanced formatting features:

String Formatting with Variable Arguments
// Format strings with sprintf-style formatting
result := tinystring.Format("Hello %s, you have %d messages", "John", 5)
// Result: "Hello John, you have 5 messages"

// Support for various format specifiers
result := tinystring.Format("Number: %d, Float: %.2f, Bool: %v", 42, 3.14159, true)
// Result: "Number: 42, Float: 3.14, Bool: true"

// Format with hex, binary, and octal
result := tinystring.Format("Hex: %x, Binary: %b, Octal: %o", 255, 10, 8)
// Result: "Hex: ff, Binary: 1010, Octal: 10"
Advanced Numeric Rounding
// Default rounding behavior (ceiling/up rounding)
result := tinystring.Convert(3.154).RoundDecimals(2).String()
// Result: "3.16"

// Explicit down rounding using Down() method
result := tinystring.Convert(3.154).RoundDecimals(2).Down().String() 
// Result: "3.15"

// Chain with other operations
result := tinystring.Convert(123.987).RoundDecimals(1).Down().ToUpper().String()
// Result: "123.9"
Boolean Conversion
// String to boolean conversion
result, err := tinystring.Convert("true").ToBool()
// Result: true, err: nil

// Numeric to boolean (non-zero = true)
result, err := tinystring.Convert(42).ToBool()
// Result: true, err: nil

result, err := tinystring.Convert(0).ToBool() 
// Result: false, err: nil

// Boolean to string
result := tinystring.FromBool(true).String()
// Result: "true"
Enhanced Numeric Conversions
// Integer conversions with float handling
result, err := tinystring.Convert("123").ToInt()
// Result: 123, err: nil

result, err := tinystring.Convert("123.45").ToInt() // Truncates float
// Result: 123, err: nil

// Unsigned integer conversions  
result, err := tinystring.Convert("456").ToUint()
// Result: 456, err: nil

result, err := tinystring.Convert("789.99").ToUint() // Truncates float
// Result: 789, err: nil

// Float conversions
result, err := tinystring.Convert("3.14159").ToFloat()
// Result: 3.14159, err: nil

// Creating from numeric types
result := tinystring.FromInt(42).String()
// Result: "42"

result := tinystring.FromUint(123).String() 
// Result: "123"

result := tinystring.FromFloat(3.14).String()
// Result: "3.14"
String Quoting
// Add quotes around strings with proper escaping
result := tinystring.Convert("hello").Quote().String()
// Result: "\"hello\""

// Handle special characters
result := tinystring.Convert("say \"hello\"").Quote().String()
// Result: "\"say \\\"hello\\\"\""

// Quote with newlines and tabs
result := tinystring.Convert("line1\nline2\ttab").Quote().String()
// Result: "\"line1\\nline2\\ttab\""
Error Handling with StringError()
// Get both result and error information
result, err := tinystring.Convert("invalid").ToInt()
if err != nil {
    fmt.Printf("Conversion failed: %v", err)
}

// Use StringError() method for operations that might fail
text := tinystring.Convert("123.45").RoundDecimals(2)
result, err := text.StringError()
// Result: "123.45", err: nil (or error if conversion failed)
Chaining New Operations
// Complex chaining with new functionality
result := tinystring.Format("User %s has %d points", "Alice", 95)
formatted := tinystring.Convert(result).Quote().ToUpper().String()
// Result: "\"USER ALICE HAS 95 POINTS\""

// Numeric processing chain
result := tinystring.FromFloat(123.987)
    .RoundDecimals(2)
    .Down()
    .FormatNumber()
    .String()
// Result: "123.98"

// Type conversion chain
result, err := tinystring.Convert("42")
    .ToInt()
if err == nil {
    formatted := tinystring.FromInt(result * 2).Quote().String()
    // Result: "\"84\""
}
Examples
// Remove accents
tinystring.Convert("áéíóú").RemoveTilde().String()
// Result: "aeiou"

// Convert to camelCase
tinystring.Convert("hello world").CamelCaseLower().String()
// Result: "helloWorld"

// Combining operations
tinystring.Convert("HÓLA MÚNDO")
    .RemoveTilde()
    .ToLower()
    .String()
// Result: "hola mundo"

// Converting different data types
tinystring.Convert(123).String()
// Result: "123"

tinystring.Convert(45.67).String()
// Result: "45.67"

tinystring.Convert(true).String()
// Result: "true"

// Convert and transform other data types
tinystring.Convert(456).CamelCaseUpper().String()
// Result: "456"

tinystring.Convert(false).ToUpper().String()
// Result: "FALSE"

// Format number with decimal places
tinystring.Convert(3.12221).RoundDecimals(2).String()
// Result: "3.12"

// Format number with thousand separators
tinystring.Convert(2189009.00).FormatNumber().String()
// Result: "2.189.009"
// Result: "FALSE"

// Split a string by separator
result := tinystring.Split("apple,banana,cherry", ",")
// Result: []string{"apple", "banana", "cherry"}

// Split a string by whitespace (default)
result := tinystring.Split("hello world  test")
// Result: []string{"hello", "world", "test"}

// Split with mixed whitespace characters
result := tinystring.Split("hello\tworld\nnew")
// Result: []string{"hello", "world", "new"}

// Parse key-value string
value, err := tinystring.ParseKeyValue("user:admin")
// Result: value = "admin", err = nil

// Parse with custom delimiter
value, err := tinystring.ParseKeyValue("count=42", "=")
// Result: value = "42", err = nil

// Multiple values with same delimiter
value, err := tinystring.ParseKeyValue("path:usr:local:bin")
// Result: value = "usr:local:bin", err = nil

// Handle error when delimiter is not found
value, err := tinystring.ParseKeyValue("invalidstring")
// Result: value = "", err = error("delimiter ':' not found in string invalidstring")

// Join string slices with default space separator
result := tinystring.Convert([]string{"Hello", "World"}).Join().String()
// Result: "Hello World" 

// Join with custom separator
result := tinystring.Convert([]string{"apple", "banana", "orange"}).Join("-").String()
// Result: "apple-banana-orange"

// Join and chain with other transformations
result := tinystring.Convert([]string{"hello", "world"}).Join().ToUpper().String()
// Result: "HELLO WORLD"

// Replace text
tinystring.Convert("hello world").Replace("world", "universe").String()
// Result: "hello universe"

// Trim prefix and suffix
tinystring.Convert("prefix-content.txt").TrimPrefix("prefix-").TrimSuffix(".txt").String()
// Result: "content"

// Trim spaces and remove file extension
tinystring.Convert("  file.txt  ").Trim().TrimSuffix(".txt").String()
// Result: "file"

// Chain multiple operations
text := tinystring.Convert(" User Name ")
    .Trim()
    .Replace(" ", "_")
    .ToLower()
    .String()
// Result: "user_name"

// Search examples
// Check if a string contains another
result := tinystring.Contains("hello world", "world")
// Result: true

// Count occurrences
count := tinystring.CountOccurrences("abracadabra", "abra")
// Result: 2

// Capitalize each word
tinystring.Convert("hello world").Capitalize().String()
// Result: "Hello World"

// Capitalize with accent removal
tinystring.Convert("hólá múndo")
    .RemoveTilde()
    .Capitalize()
    .String()
// Result: "Hola Mundo"

// Repeat a string multiple times
tinystring.Convert("hello ").Repeat(3).String()
// Result: "hello hello hello "

// Repeat with other transformations
tinystring.Convert("test")
    .ToUpper()
    .Repeat(2)
    .String()
// Result: "TESTTEST"

// Zero or negative repetitions returns an empty string
tinystring.Convert("test").Repeat(0).String()
// Result: ""

// Truncate a long string to specific width
tinystring.Convert("Hello, World!").Truncate(10).String()
// Result: "Hello, ..."

// Truncate with reserved characters (explicitly provided)
tinystring.Convert("Hello, World!").Truncate(10, 3).String()
// Result: "Hell..."

// Text shorter than max width remains unchanged
tinystring.Convert("Hello").Truncate(10).String()
// Result: "Hello"

// Truncate names and surnames for display in charts or limited spaces
tinystring.Convert("Jeronimo Dominguez").TruncateName(3, 15).String()
// Result: "Jer. Dominguez"

// Truncate multiple names and surnames with total length limit
tinystring.Convert("Ana Maria Rodriguez").TruncateName(2, 10).String()
// Result: "An. Mar..."

// Handle first word specially when more than 2 words
tinystring.Convert("Juan Carlos Rodriguez").TruncateName(3, 20).String()
// Result: "Jua. Car. Rodriguez"

// Truncate and transform
tinystring.Convert("hello world")
    .ToUpper()
    .Truncate(8)
    .String()
// Result: "HELLO..."

// Truncate with different numeric types
tinystring.Convert("Hello, World!").Truncate(uint8(10), float64(3)).String()
// Result: "Hell..."

// Chaining truncate and repeat
tinystring.Convert("hello")
    .Truncate(6) // Truncate(6) doesn't change "hello"
    .Repeat(2)
    .String()
// Result: "hellohello"
Working with String Pointers

TinyString supports working directly with string pointers to avoid additional memory allocations. This can be especially useful in performance-critical applications or when processing large volumes of text.

// Create a string variable
text := "Él Múrcielago Rápido"

// Modify it directly using string pointer and Apply()
// No need to reassign the result
Convert(&text).RemoveTilde().ToLower().Apply()

// The original variable is modified
fmt.Println(text) // Output: "el murcielago rapido"

// This approach can reduce memory pressure in high-performance scenarios
// by avoiding temporary string allocations

String() vs Apply()

The library offers two ways to finish a chain of operations:

// 1. Using String() - Returns the result without modifying the original
originalText := "Él Múrcielago Rápido"
result := Convert(&originalText).RemoveTilde().ToLower().String()
fmt.Println(result)        // Output: "el murcielago rapido"
fmt.Println(originalText)  // Output: "Él Múrcielago Rápido" (unchanged)

// 2. Using Apply() - Modifies the original string directly
originalText = "Él Múrcielago Rápido"
Convert(&originalText).RemoveTilde().ToLower().Apply()
fmt.Println(originalText)  // Output: "el murcielago rapido" (modified)

Performance benchmarks show that using string pointers can reduce memory allocations when processing large volumes of text, which can be beneficial in high-throughput applications or systems with memory constraints.

// Sample benchmark results:

Binary Size Comparison

Last updated: 2025-05-26 20:40:55

Default Optimization

Default TinyGo optimization (-opt=z)

Platform Standard Library TinyString Improvement
Native 1.3 MB 1.1 MB 16.7% smaller
WebAssembly 580.7 KB 232.4 KB 60.0% smaller
Ultra Optimization

Ultra size optimization

Platform Standard Library TinyString Improvement
WebAssembly 141.1 KB 22.8 KB 83.9% smaller
Speed Optimization

Speed optimization

Platform Standard Library TinyString Improvement
WebAssembly 816.0 KB 331.6 KB 59.4% smaller
Debug Optimization

Debug build

Platform Standard Library TinyString Improvement
WebAssembly 1.8 MB 681.5 KB 62.8% smaller
Summary

TinyString consistently produces smaller binaries across all optimization levels and platforms:

  • Average binary size reduction: 16.7%
  • Consistent improvements across all optimization levels
  • WebAssembly builds show similar or better improvements
  • Best results with ultra optimization settings

Memory Usage Comparison

Last updated: 2025-05-26 20:41:21

Performance benchmarks comparing memory allocation patterns:

Benchmark Library Bytes/Op Allocs/Op Time/Op Memory Improvement Alloc Improvement
String Processing Standard 1.2 KB 48 3.1μs - -
TinyString 3.7 KB 95 10.8μs 218.7% more 97.9% more
Number Processing Standard 1.2 KB 132 4.0μs - -
TinyString 7.2 KB 682 14.1μs 512.0% more 416.7% more
Mixed Operations Standard 546 B 44 2.1μs - -
TinyString 2.6 KB 191 6.4μs 380.8% more 334.1% more
String Processing (Pointer Optimization) Standard 1.2 KB 48 3.1μs - -
TinyString 3.6 KB 87 10.6μs 208.0% more 81.2% more
Trade-offs Analysis

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

Binary Size Benefits:

  • Significantly smaller compiled binaries (16-84% reduction)
  • Better compression for WebAssembly targets
  • Reduced distribution and deployment overhead

Runtime Memory Considerations:

  • Higher memory allocation overhead during execution
  • Increased GC pressure due to more allocations
  • Trade-off optimizes for storage/distribution size over runtime efficiency

Recommendation:

  • Use TinyString for size-constrained environments (embedded, edge computing)
  • Consider standard library for memory-intensive runtime workloads
  • Evaluate based on specific deployment constraints

Contributing

Contributions are welcome. Please open an issue to discuss proposed changes.

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

This section is empty.

Variables

This section is empty.

Functions

func Contains added in v0.0.8

func Contains(text, search string) bool

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

func CountOccurrences added in v0.0.8

func CountOccurrences(text, search string) int

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

func ParseKeyValue added in v0.0.10

func ParseKeyValue(input 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)

Types

type Text

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

Text struct to store the content of the text - optimized for memory efficiency

func Convert

func Convert(v any) *Text

Convert initializes a new Text struct with any type of value for string manipulation.

Supported input types:

  • string: Direct string value
  • *string: Pointer to string (allows in-place modification with Apply())
  • []string: Slice of strings (use Join() to combine)
  • int, int8, int16, int32, int64: Integer types
  • uint, uint8, uint16, uint32, uint64: Unsigned integer types
  • float32, float64: Floating point types
  • bool: Boolean values (true/false)
  • any other type: Converted to string representation

Usage patterns:

  1. Basic string manipulation: result := Convert("hello world").ToUpper().String() // result: "HELLO WORLD"
  1. In-place modification of string pointer: original := "hello world" Convert(&original).ToUpper().Apply() // original is now: "HELLO WORLD"
  1. Working with slices: words := []string{"hello", "world"} result := Convert(words).Join(" ").ToUpper().String() // result: "HELLO WORLD"
  1. Numeric conversions: result := Convert(42).String() // result: "42"

The Convert function returns a *Text instance that supports method chaining for various string transformations like case conversion, joining, parsing, etc. Use String() to get the final result or Apply() to modify the original pointer.

func Format added in v0.0.30

func Format(format string, args ...any) *Text

Format creates a new Text instance with variadic formatting similar to fmt.Sprintf Example: tinystring.Format("Hello %s, you have %d messages", "Alice", 5).String()

func FromBool added in v0.0.30

func FromBool(value bool) *Text

FromBool creates a new Text instance from a boolean value

func FromFloat added in v0.0.30

func FromFloat(value float64, precision ...int) *Text

FromFloat creates a new Text instance from a float64 with optional precision specification.

Parameters:

  • value: The float64 value to convert to Text
  • precision (optional): Number of decimal places to include. Default is -1 (full precision). Use 0 for no decimal places, positive values for fixed decimal places.

Returns:

  • *Text: A new Text instance containing the string representation of the float

Usage examples:

// Full precision (default)
text := FromFloat(123.456789)
result := text.String() // "123.456789" (or full precision representation)

// No decimal places
text := FromFloat(123.456, 0)
result := text.String() // "123"

// Fixed decimal places
text := FromFloat(123.456, 2)
result := text.String() // "123.46" (rounded)

// Scientific notation values
text := FromFloat(1.23e-4, 6)
result := text.String() // "0.000123"

// Negative numbers
text := FromFloat(-99.99, 1)
result := text.String() // "-100.0"

// Chain with other operations
text := FromFloat(123.456, 2).ToUpper()
result := text.String() // "123.46" (case conversion doesn't affect numbers)

Note: The precision parameter controls the number of digits after the decimal point. The resulting Text instance can be used for further string manipulations.

func FromInt added in v0.0.30

func FromInt(value int, base ...int) *Text

FromInt creates a new Text instance from an integer with optional base specification.

Parameters:

  • value: The integer value to convert to Text
  • base (optional): The numeric base for string representation (2-36). Default is 10 (decimal). Common bases: 2 (binary), 8 (octal), 10 (decimal), 16 (hexadecimal)

Returns:

  • *Text: A new Text instance containing the string representation of the integer

Usage examples:

// Basic decimal conversion
text := FromInt(123)
result := text.String() // "123"

// Binary representation
text := FromInt(10, 2)
result := text.String() // "1010"

// Hexadecimal representation
text := FromInt(255, 16)
result := text.String() // "ff"

// Octal representation
text := FromInt(64, 8)
result := text.String() // "100"

// Negative numbers (only base 10)
text := FromInt(-42)
result := text.String() // "-42"

Note: The resulting Text instance can be used for further string manipulations like case conversion, joining, etc.

func FromUint added in v0.0.30

func FromUint(value uint, base ...int) *Text

FromUint creates a new Text instance from an unsigned integer with optional base specification.

Parameters:

  • value: The unsigned integer value to convert to Text
  • base (optional): The numeric base for string representation (2-36). Default is 10 (decimal). Common bases: 2 (binary), 8 (octal), 10 (decimal), 16 (hexadecimal)

Returns:

  • *Text: A new Text instance containing the string representation of the unsigned integer

Usage examples:

// Basic decimal conversion
text := FromUint(123)
result := text.String() // "123"

// Binary representation
text := FromUint(10, 2)
result := text.String() // "1010"

// Hexadecimal representation
text := FromUint(255, 16)
result := text.String() // "ff"

// Large unsigned values
text := FromUint(18446744073709551615) // max uint64
result := text.String() // "18446744073709551615"

// Chain with other operations
text := FromUint(255, 16).ToUpper()
result := text.String() // "FF"

Note: Unlike FromInt, this function only works with non-negative values. The resulting Text instance can be used for further string manipulations.

func (*Text) Apply added in v0.0.28

func (t *Text) Apply()

Apply updates the original string pointer with the current content. This method should be used when you want to modify the original string directly without additional allocations.

func (*Text) CamelCaseLower

func (t *Text) CamelCaseLower() *Text

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

func (*Text) CamelCaseUpper

func (t *Text) CamelCaseUpper() *Text

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

func (*Text) Capitalize added in v0.0.11

func (t *Text) Capitalize() *Text

Capitalize transforms the first letter of each word to uppercase and the rest to lowercase. For example: "hello world" -> "Hello World"

func (*Text) Down added in v0.0.30

func (t *Text) Down() *Text

Down applies downward rounding to a previously rounded number This method works by taking the current rounded value and ensuring it represents the floor Example: Convert(3.154).RoundDecimals(2).Down().String() → "3.15"

func (*Text) FormatNumber added in v0.0.17

func (t *Text) FormatNumber() *Text

FormatNumber formats a numeric value with thousand separators Example: Convert(1234567).FormatNumber().String() → "1,234,567"

func (*Text) Join added in v0.0.24

func (t *Text) Join(sep ...string) *Text

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 (*Text) Quote added in v0.0.30

func (t *Text) Quote() *Text

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

func (*Text) RemoveTilde

func (t *Text) RemoveTilde() *Text

Remueve tildes y diacríticos

func (*Text) Repeat added in v0.0.13

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

Repeat returns the string s repeated n times. If n is less than or equal to zero, or if s is empty, it returns an empty string. eg: Convert("abc").Repeat(3) => "abcabcabc"

func (*Text) Replace added in v0.0.7

func (t *Text) Replace(oldAny, newAny any, n ...int) *Text

Replace replaces up to n occurrences of old with new in the text 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 anyToString

func (*Text) RoundDecimals added in v0.0.17

func (t *Text) RoundDecimals(decimals int) *Text

RoundDecimals rounds a numeric value to the specified number of decimal places Default behavior is rounding up. Use .Down() to round down. Example: Convert(3.154).RoundDecimals(2).String() → "3.16"

func (*Text) String

func (t *Text) String() string

String method to return the content of the text without modifying any original pointers

func (*Text) StringError added in v0.0.30

func (t *Text) StringError() (string, error)

StringError returns the content of the text along with any error that occurred during processing

func (*Text) ToBool added in v0.0.30

func (t *Text) ToBool() (bool, error)

ToBool converts the text content to a boolean value Returns the boolean value and any error that occurred

func (*Text) ToFloat added in v0.0.30

func (t *Text) ToFloat() (float64, error)

ToFloat converts the text content to a float64 (double precision floating point).

Returns:

  • float64: The converted floating point value
  • error: Any error that occurred during conversion

Conversion behavior:

  • Parses the string content as a floating point number
  • Supports both positive and negative numbers
  • Handles decimal points and scientific notation (if implemented)
  • Returns error for invalid number formats

Supported input formats:

  • Integer strings: "123" -> 123.0, "-456" -> -456.0
  • Decimal numbers: "123.45", "-99.99", "0.001"
  • Numbers with leading signs: "+123.45", "-0.99"
  • Zero values: "0", "0.0", "0.000"

Usage examples:

// Basic decimal conversion
val, err := Convert("123.45").ToFloat()
// val: 123.45, err: nil

// Integer to float
val, err := Convert("42").ToFloat()
// val: 42.0, err: nil

// Negative numbers
val, err := Convert("-99.99").ToFloat()
// val: -99.99, err: nil

// Error handling
val, err := Convert("invalid").ToFloat()
// val: 0.0, err: conversion error

Note: This method uses a custom float parsing implementation that may have different precision characteristics compared to the standard library.

func (*Text) ToInt added in v0.0.30

func (t *Text) ToInt(base ...int) (int, error)

ToInt converts the text content to an integer with optional base specification.

Parameters:

  • base (optional): The numeric base for conversion (2-36). Default is 10 (decimal). Common bases: 2 (binary), 8 (octal), 10 (decimal), 16 (hexadecimal)

Returns:

  • int: The converted integer value
  • error: Any error that occurred during conversion

Conversion behavior:

  1. First attempts direct integer parsing with the specified base
  2. If that fails, tries to parse as float and truncates to integer
  3. Returns error if both methods fail

Supported input formats:

  • Integer strings: "123", "-456"
  • Float strings (truncated): "123.45" -> 123, "99.99" -> 99
  • Different bases: "1010" (base 2) -> 10, "FF" (base 16) -> 255
  • Negative numbers: Only supported for base 10

Usage examples:

// Basic decimal conversion
val, err := Convert("123").ToInt()
// val: 123, err: nil

// Binary conversion
val, err := Convert("1010").ToInt(2)
// val: 10, err: nil

// Hexadecimal conversion
val, err := Convert("FF").ToInt(16)
// val: 255, err: nil

// Float truncation
val, err := Convert("123.99").ToInt()
// val: 123, err: nil

// Error handling
val, err := Convert("invalid").ToInt()
// val: 0, err: conversion error

Note: Negative numbers are only supported for base 10. For other bases, negative signs will result in an error.

func (*Text) ToLower

func (t *Text) ToLower() *Text

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

func (*Text) ToSnakeCaseLower

func (t *Text) ToSnakeCaseLower(sep ...string) *Text

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"

ToSnakeCaseLower converts text to snake_case format

func (*Text) ToSnakeCaseUpper

func (t *Text) ToSnakeCaseUpper(sep ...string) *Text

ToSnakeCaseUpper converts text to Snake_Case format

func (*Text) ToUint added in v0.0.30

func (t *Text) ToUint(base ...int) (uint, error)

ToUint converts the text content to an unsigned integer with optional base specification.

Parameters:

  • base (optional): The numeric base for conversion (2-36). Default is 10 (decimal). Common bases: 2 (binary), 8 (octal), 10 (decimal), 16 (hexadecimal)

Returns:

  • uint: The converted unsigned integer value
  • error: Any error that occurred during conversion

Conversion behavior:

  1. First attempts direct unsigned integer parsing with the specified base
  2. If that fails, tries to parse as float and truncates to unsigned integer
  3. Returns error if both methods fail or if the value is negative

Supported input formats:

  • Positive integer strings: "123", "456"
  • Float strings (truncated): "123.45" -> 123, "99.99" -> 99
  • Different bases: "1010" (base 2) -> 10, "FF" (base 16) -> 255
  • Negative numbers: NOT supported, will return error

Usage examples:

// Basic decimal conversion
val, err := Convert("123").ToUint()
// val: 123, err: nil

// Binary conversion
val, err := Convert("1010").ToUint(2)
// val: 10, err: nil

// Hexadecimal conversion
val, err := Convert("FF").ToUint(16)
// val: 255, err: nil

// Float truncation
val, err := Convert("123.99").ToUint()
// val: 123, err: nil

// Error with negative number
val, err := Convert("-123").ToUint()
// val: 0, err: "negative numbers are not supported for unsigned integers"

Note: Negative numbers are never supported for unsigned integers and will always result in an error, regardless of the base.

func (*Text) ToUpper

func (t *Text) ToUpper() *Text

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

func (*Text) Trim added in v0.0.7

func (t *Text) Trim() *Text

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

func (*Text) TrimPrefix added in v0.0.9

func (t *Text) TrimPrefix(prefix string) *Text

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

func (*Text) TrimSuffix added in v0.0.7

func (t *Text) TrimSuffix(suffix string) *Text

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

func (*Text) Truncate added in v0.0.13

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

Truncate truncates a text so that it does not exceed the specified width. If the text is longer, it truncates it and adds "..." if there is space. If the text 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 (*Text) TruncateName added in v0.0.20

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

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

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"

Jump to

Keyboard shortcuts

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