strchain

package
v0.1.37 Latest Latest
Warning

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

Go to latest
Published: Aug 22, 2026 License: GPL-3.0 Imports: 7 Imported by: 0

README

StrChain — Fluent String Builder for Go

A high-performance string builder for Go that wraps strings.Builder with a fluent, chainable API. Choose between a pure implementation for maximum throughput or a thread-safe variant for concurrent workloads.

✨ Features

  • ⛓️ Fluent API — All methods return Weaver for expressive chainable calls
  • 🚀 Zero OverheadStringWeaver wraps strings.Builder directly, no mutex
  • 🔒 Thread-Safe OptionSafeStringWeaver adds sync.Mutex protection
  • 🎯 Type-Safe — Full numeric type support (int8–64, uint8–64, float32/64, bool)
  • 📦 Zero Dependencies — Built entirely on Go's standard library
  • 🧩 Interface-DrivenWeaver interface enables polymorphism between implementations
  • 💡 Intuitive — Natural, readable syntax that mirrors how you think about string construction

📥 Installation

go get github.com/polarixa/replify

Import:

import "github.com/polarixa/replify/pkg/strchain"

🏗️ Architecture

                    ┌────────────┐
                    │   Weaver   │ (interface)
                    │  48 methods│
                    └─────┬──────┘
                          │
              ┌───────────┴───────────┐
              │                       │
     ┌────────┴────────┐    ┌─────────┴─────────┐
     │  StringWeaver   │    │ SafeStringWeaver   │
     │  (no mutex)     │    │ (sync.Mutex)       │
     │  max performance│    │ thread-safe        │
     └─────────────────┘    └────────────────────┘

Choose the right type:

When to use Type Constructor
Single goroutine, max performance StringWeaver New(), From(), NewWithCapacity()
Multiple goroutines, concurrent access SafeStringWeaver NewSafe(), SafeFrom(), NewSafeWithCapacity()

🚀 Quick Start

Basic Usage (Single-Threaded)
result := strchain.New().
    Append("Hello").
    Space().
    Append("World").
    Build()

fmt.Println(result) // Output: Hello World
Thread-Safe Usage
logger := strchain.NewSafe()
var wg sync.WaitGroup

for i := 1; i <= 5; i++ {
    wg.Add(1)
    go func(id int) {
        defer wg.Done()
        logger.LineF("[Thread %d] Processing completed", id)
    }(i)
}

wg.Wait()
fmt.Println(logger.Build())
Polymorphism via Weaver Interface
func buildGreeting(w strchain.Weaver, name string) string {
    return w.Append("Hello, ").Append(name).Append("!").Build()
}

// Works with either implementation
buildGreeting(strchain.New(), "Alice")         // fast, single-threaded
buildGreeting(strchain.NewSafe(), "Bob")       // safe, multi-threaded

📚 Core API

Both StringWeaver and SafeStringWeaver share the same method set, unified by the Weaver interface.

Constructors
// StringWeaver (non-thread-safe, maximum performance)
strchain.New()                    // Create new instance
strchain.NewWithCapacity(1000)    // Pre-allocate capacity
strchain.From("initial text")     // Start from existing string

// SafeStringWeaver (thread-safe with mutex)
strchain.NewSafe()                // Create new instance
strchain.NewSafeWithCapacity(1000)// Pre-allocate capacity
strchain.SafeFrom("initial text") // Start from existing string
String Operations
.Append("text")                   // Append string
.AppendF("Hello %s", name)        // Formatted append (printf-style)
.AppendByte('A')                  // Single byte
.AppendRune('🔒')                 // Single rune
.AppendBytes([]byte{...})         // Byte slice
Type-Specific Appends
.AppendInt(42)                    // int
.AppendInt8(8)                    // int8
.AppendInt16(16)                  // int16
.AppendInt32(32)                  // int32
.AppendInt64(64)                  // int64
.AppendUint(42)                   // uint
.AppendUint8(8)                   // uint8
.AppendUint16(16)                 // uint16
.AppendUint32(32)                 // uint32
.AppendUint64(64)                 // uint64
.AppendUintptr(100)               // uintptr
.AppendFloat32(3.14)              // float32
.AppendFloat64(2.718)             // float64
.AppendBool(true)                 // bool
Whitespace
.Space()                          // Single space
.Spaces(5)                        // Multiple spaces
.Tab()                            // Single tab
.Tabs(3)                          // Multiple tabs
.NewLine()                        // Single newline
.NewLines(2)                      // Multiple newlines
.Line("text")                     // Text + newline
.LineF("Hello %s", name)          // Formatted + newline
Collections
.Join(", ", "A", "B", "C")        // Join with separator
.Repeat("*", 10)                  // Repeat string n times
.Each(items, func(sw, item) {     // Iterate over slice
    sw.Append(item)
})
Conditional Building
.AppendIf(condition, "text")      // Append if true
.AppendIfF(condition, "%s", val)  // Formatted append if true
.When(condition, func(sw) {       // Execute block if true
    sw.Append("text")
})
.Unless(condition, func(sw) {     // Execute block if false
    sw.Append("text")
})

Note: When, Unless, and Each accept callbacks with concrete receiver types (*StringWeaver or *SafeStringWeaver). These methods are not part of the Weaver interface.

Formatting
.Indent(2, "text")                // Indent (2 spaces per level)
.IndentLine(1, "text")            // Indent + newline
.Quote("text")                    // "text"
.SingleQuote("text")              // 'text'
.Parenthesize("text")             // (text)
.Bracket("text")                  // [text]
.Brace("text")                    // {text}
.Wrap("<", "text", ">")           // <text>
Punctuation
.Comma()                          // ,
.Dot()                            // .
.Colon()                          // :
.Semicolon()                      // ;
.Equals()                         // =
.Arrow()                          // ->
.FatArrow()                       // =>
Utilities
.Grow(1000)                       // Pre-allocate capacity
.Reset()                          // Clear and reuse
.Len()                            // Current length
.Cap()                            // Current capacity
.Clone()                          // Create independent copy
.Inspect(func(current) {          // Debug current state
    fmt.Println(current)
})
Output
.Build()                          // Get final string
.String()                         // Alias for Build()

🎯 Real-World Examples

SQL Query Building
query := strchain.New().
    Append("SELECT ").
    Join(", ", "id", "name", "email").NewLine().
    Append("FROM users").NewLine().
    Append("WHERE active = true").NewLine().
    Append("ORDER BY created_at DESC").
    Build()
JSON Construction
json := strchain.New().
    Line("{").
    IndentLine(1, `"name": "John",`).
    IndentLine(1, `"age": 30,`).
    IndentLine(1, `"active": true`).
    Append("}").
    Build()
HTML Generation
html := strchain.New().
    Append("<div class=").Quote("container").Append(">").NewLine().
    Indent(1, "<h1>").Append("Welcome").Append("</h1>").NewLine().
    Indent(1, "<p>").Append("Content").Append("</p>").NewLine().
    Append("</div>").
    Build()
Concurrent Log Aggregation
logger := strchain.NewSafe()

go logger.LineF("[%s] Service started", time.Now())
go logger.LineF("[%s] Database connected", time.Now())
go logger.LineF("[%s] Cache initialized", time.Now())

// All logs are safely aggregated — no external locking needed
Concurrent CSV Generation
csv := strchain.NewSafe()
csv.Line("ID,Name,Value")
var wg sync.WaitGroup

for i := 1; i <= 100; i++ {
    wg.Add(1)
    go func(id int) {
        defer wg.Done()
        csv.Join(",",
            fmt.Sprintf("%d", id),
            fmt.Sprintf("Item%d", id),
            fmt.Sprintf("%d", id*100),
        ).NewLine()
    }(i)
}

wg.Wait()
Safe Cloning for Branching
template := strchain.NewSafe()
template.Append("Dear ")

for _, name := range []string{"Alice", "Bob", "Charlie"} {
    go func(n string) {
        personalized := template.Clone() // Thread-safe clone
        personalized.Append(n).Append(",").NewLine()
        fmt.Println(personalized.Build())
    }(name)
}

⚡ Performance

Design Philosophy

The strchain package provides two implementations to avoid forcing a one-size-fits-all trade-off:

Implementation Overhead Use Case
StringWeaver Zero — direct strings.Builder wrapper Single-threaded, hot paths
SafeStringWeaver ~10–20ns/op — mutex lock/unlock per call Concurrent access

Both implementations produce zero allocations beyond the initial builder allocation — identical to strings.Builder.

Performance Tips
// ✅ Use StringWeaver for single-threaded code
sw := strchain.New()

// ✅ Pre-allocate capacity when the approximate size is known
sw := strchain.NewWithCapacity(4096)

// ✅ Reuse with Reset to avoid re-allocation
sw.Reset()

// ✅ Use SafeStringWeaver only when concurrent access is required
sw := strchain.NewSafe()

// ⚠️ Avoid calling Len() in tight loops with SafeStringWeaver — each call acquires a lock

🔒 Thread-Safety Details

StringWeaver

StringWeaver is NOT thread-safe. It is designed for single-goroutine use where maximum performance is required. Using it concurrently without external synchronization will cause data races.

SafeStringWeaver

SafeStringWeaver is thread-safe. All methods use internal mutex synchronization:

  • ✅ All Append operations
  • ✅ All formatting and punctuation methods
  • Len(), Cap(), String(), Build()
  • Reset(), Grow(), Clone()
  • Inspect() — locks during state read, unlocks before callback execution

Callback methods (When, Unless, Each) do not hold the lock during callback execution. The callback receives the builder instance and can safely call any method (each of which acquires its own lock individually).

Concurrent Patterns
// ✅ Pattern 1: Shared SafeStringWeaver
logger := strchain.NewSafe()
go logger.Line("A")
go logger.Line("B")

// ✅ Pattern 2: Clone for branching
template := strchain.NewSafe()
template.Append("Base: ")
go func() {
    branch := template.Clone()
    branch.Append("Branch 1")
}()

// ✅ Pattern 3: Separate instances per goroutine
go func() {
    local := strchain.New() // No mutex needed
    local.Append("Local work")
}()

🆚 Comparison

StringWeaver vs SafeStringWeaver
Feature StringWeaver SafeStringWeaver
Thread-Safe ❌ No ✅ Yes
Performance Baseline (zero overhead) ~10–20ns/op mutex cost
Allocations 0 0
Use Case Single goroutine, max perf Concurrent access
vs. strings.Builder
Feature StringWeaver SafeStringWeaver strings.Builder
Thread-Safe ❌ No ✅ Yes ❌ No
Fluent API ✅ Yes ✅ Yes ❌ No
Type Methods ✅ Full ✅ Full ⚠️ Limited
Performance ≈ Baseline ~10–20ns overhead Baseline
Allocations 0 0 0
vs. strings.Join / fmt.Sprintf
Feature Weaver strings.Join fmt.Sprintf
Zero Allocs ✅ Yes ❌ No ❌ No
Fluent API ✅ Yes ❌ No ❌ No
Flexibility ✅ High ⚠️ Limited ⚠️ Medium

🤝 Contributing

Contributions welcome! Please feel free to submit a Pull Request.

📄 License

MIT License — see LICENSE file for details.

🙏 Credits

Built with ❤️ on top of Go's excellent strings.Builder. Thread-safety powered by sync.Mutex.

Documentation

Overview

Package strchain provides a fluent, chainable string builder API built on top of Go's strings.Builder. It offers two implementations with identical APIs:

  • StringWeaver: A high-performance, non-thread-safe builder for single-goroutine usage. It wraps strings.Builder directly with zero overhead beyond the method call indirection.

  • SafeStringWeaver: A thread-safe builder protected by sync.Mutex, suitable for concurrent access from multiple goroutines. Each operation acquires a lock, adding approximately 10–20ns of overhead per call.

Both types implement the Weaver interface, which defines the full set of chainable methods. This allows writing functions that accept either implementation polymorphically.

Choosing Between StringWeaver and SafeStringWeaver

Use StringWeaver (via New, NewWithCapacity, or From) when:

  • The builder is confined to a single goroutine.
  • Maximum throughput is required (zero synchronization overhead).

Use SafeStringWeaver (via NewSafe, NewSafeWithCapacity, or SafeFrom) when:

  • Multiple goroutines write to the same builder concurrently.
  • Thread safety is required without external locking.

Fluent API

All chainable methods return the Weaver interface, enabling expressive method chains:

result := strchain.New().
    Append("SELECT ").
    Join(", ", "id", "name", "email").
    Append(" FROM users").
    Build()

Callback Methods

The StringWeaver.When, StringWeaver.Unless, and StringWeaver.Each methods accept callbacks with concrete receiver types. These methods are not part of the Weaver interface because their function signatures differ between implementations. They are available directly on each concrete type.

Polymorphism

Functions that build strings can accept Weaver to work with either implementation:

func buildGreeting(w strchain.Weaver, name string) string {
    return w.Append("Hello, ").Append(name).Append("!").Build()
}

// Single-threaded
buildGreeting(strchain.New(), "Alice")

// Thread-safe
buildGreeting(strchain.NewSafe(), "Bob")

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Chain

type Chain string

Chain is a lightweight fluent string wrapper that enables method chaining directly from a string value without needing to create a StringWeaver constructor.

Usage:

result := strchain.Chain("Hello").Space().Append("World").Upper().String()
// Output: "HELLO WORLD"

result := strchain.Chain("  trimmed  ").Trim().Quote().String()
// Output: "\"trimmed\""

func C

func C(s ...string) Chain

C is a shorthand alias for Chain.

Example:

result := strchain.C("Hello").Space().Append("World").String()

func Empty

func Empty() Chain

Empty creates an empty Chain for building strings from scratch.

Example:

result := strchain.Empty().Append("Built").Space().Append("from scratch").String()

func (Chain) Append

func (c Chain) Append(s string) Chain

Append adds a string to the end.

func (Chain) AppendBool

func (c Chain) AppendBool(b bool) Chain

AppendBool adds a boolean.

func (Chain) AppendByte

func (c Chain) AppendByte(b byte) Chain

AppendByte adds a single byte.

func (Chain) AppendBytes

func (c Chain) AppendBytes(b []byte) Chain

AppendBytes adds a byte slice.

func (Chain) AppendF

func (c Chain) AppendF(format string, args ...any) Chain

AppendF adds a formatted string (printf-style).

func (Chain) AppendFloat64

func (c Chain) AppendFloat64(f float64) Chain

AppendFloat64 adds a float64.

func (Chain) AppendIf

func (c Chain) AppendIf(condition bool, s string) Chain

AppendIf appends a string if the condition is true.

func (Chain) AppendIfF

func (c Chain) AppendIfF(condition bool, format string, args ...any) Chain

AppendIfF appends a formatted string if the condition is true.

func (Chain) AppendInt

func (c Chain) AppendInt(i int) Chain

AppendInt adds an integer.

func (Chain) AppendInt64

func (c Chain) AppendInt64(i int64) Chain

AppendInt64 adds an int64.

func (Chain) AppendRune

func (c Chain) AppendRune(r rune) Chain

AppendRune adds a single rune.

func (Chain) Arrow

func (c Chain) Arrow() Chain

Arrow adds an arrow (->).

func (Chain) Brace

func (c Chain) Brace() Chain

Brace wraps the string in curly braces.

func (Chain) Bracket

func (c Chain) Bracket() Chain

Bracket wraps the string in square brackets.

func (Chain) Bytes

func (c Chain) Bytes() []byte

Bytes returns the string as a byte slice.

func (Chain) Center

func (c Chain) Center(width int, pad string) Chain

Center centers the string within the specified width.

func (Chain) Colon

func (c Chain) Colon() Chain

Colon adds a colon.

func (Chain) Comma

func (c Chain) Comma() Chain

Comma adds a comma.

func (Chain) Contains

func (c Chain) Contains(substr string) bool

Contains returns true if the string contains substr.

func (Chain) Count

func (c Chain) Count(substr string) int

Count returns the number of non-overlapping occurrences of substr.

func (Chain) Dot

func (c Chain) Dot() Chain

Dot adds a period.

func (Chain) Equals

func (c Chain) Equals() Chain

Equals adds an equals sign.

func (Chain) FatArrow

func (c Chain) FatArrow() Chain

FatArrow adds a fat arrow (=>).

func (Chain) Filter

func (c Chain) Filter(fn func(rune) bool) Chain

Filter keeps only runes that satisfy the predicate.

func (Chain) HasPrefix

func (c Chain) HasPrefix(prefix string) bool

HasPrefix returns true if the string starts with prefix.

func (Chain) HasSuffix

func (c Chain) HasSuffix(suffix string) bool

HasSuffix returns true if the string ends with suffix.

func (Chain) IfEmpty

func (c Chain) IfEmpty(fallback string) Chain

IfEmpty returns the fallback if the string is empty.

func (Chain) IfNotEmpty

func (c Chain) IfNotEmpty(fn func(Chain) Chain) Chain

IfNotEmpty applies a transformation if the string is not empty.

func (Chain) Indent

func (c Chain) Indent(level int) Chain

Indent adds indentation (2 spaces per level) before the current text.

func (Chain) IndentLine

func (c Chain) IndentLine(level int) Chain

IndentLine adds indentation before the text and appends a newline.

func (Chain) Index

func (c Chain) Index(substr string) int

Index returns the index of the first occurrence of substr, or -1.

func (Chain) IsEmpty

func (c Chain) IsEmpty() bool

IsEmpty returns true if the string is empty.

func (Chain) IsNotEmpty

func (c Chain) IsNotEmpty() bool

IsNotEmpty returns true if the string is not empty.

func (Chain) Join

func (c Chain) Join(elements ...string) Chain

Join joins multiple strings using the current string as separator.

func (Chain) JoinSlice

func (c Chain) JoinSlice(elements []string) Chain

JoinSlice joins a slice of strings using the current string as separator.

func (Chain) Len

func (c Chain) Len() int

Len returns the length of the string.

func (Chain) Line

func (c Chain) Line(s string) Chain

Line adds a string followed by a newline.

func (Chain) LineF

func (c Chain) LineF(format string, args ...any) Chain

LineF adds a formatted string followed by a newline.

func (Chain) Lower

func (c Chain) Lower() Chain

Lower converts the string to lowercase.

func (Chain) Map

func (c Chain) Map(fn func(string) string) Chain

Map applies a transformation function to the string.

func (Chain) MapRunes

func (c Chain) MapRunes(fn func(rune) rune) Chain

MapRunes applies a function to each rune.

func (Chain) NewLine

func (c Chain) NewLine() Chain

NewLine adds a newline character.

func (Chain) NewLines

func (c Chain) NewLines(n int) Chain

NewLines adds n newline characters.

func (Chain) PadLeft

func (c Chain) PadLeft(width int, pad string) Chain

PadLeft pads the string on the left to reach the specified width.

func (Chain) PadRight

func (c Chain) PadRight(width int, pad string) Chain

PadRight pads the string on the right to reach the specified width.

func (Chain) Parenthesize

func (c Chain) Parenthesize() Chain

Parenthesize wraps the string in parentheses.

func (Chain) Prepend

func (c Chain) Prepend(s string) Chain

Prepend adds a string to the beginning.

func (Chain) PrependF

func (c Chain) PrependF(format string, args ...any) Chain

PrependF adds a formatted string to the beginning.

func (Chain) PrependIf

func (c Chain) PrependIf(condition bool, s string) Chain

PrependIf prepends a string if the condition is true.

func (Chain) Quote

func (c Chain) Quote() Chain

Quote wraps the string in double quotes.

func (Chain) Repeat

func (c Chain) Repeat(n int) Chain

Repeat repeats the string n times.

func (Chain) Replace

func (c Chain) Replace(old, new string) Chain

Replace replaces all occurrences of old with new.

func (Chain) ReplaceN

func (c Chain) ReplaceN(old, new string, n int) Chain

ReplaceN replaces the first n occurrences of old with new.

func (Chain) Reverse

func (c Chain) Reverse() Chain

Reverse reverses the string (rune-aware).

func (Chain) Runes

func (c Chain) Runes() []rune

Runes returns the string as a rune slice.

func (Chain) Semicolon

func (c Chain) Semicolon() Chain

Semicolon adds a semicolon.

func (Chain) SingleQuote

func (c Chain) SingleQuote() Chain

SingleQuote wraps the string in single quotes.

func (Chain) Space

func (c Chain) Space() Chain

Space adds a single space.

func (Chain) Spaces

func (c Chain) Spaces(n int) Chain

Spaces adds n spaces.

func (Chain) Split

func (c Chain) Split(sep string) []string

Split splits the string by separator and returns the parts.

func (Chain) SplitN

func (c Chain) SplitN(sep string, n int) []string

SplitN splits the string by separator into at most n parts.

func (Chain) String

func (c Chain) String() string

String returns the underlying string value.

func (Chain) Tab

func (c Chain) Tab() Chain

Tab adds a single tab.

func (Chain) Tabs

func (c Chain) Tabs(n int) Chain

Tabs adds n tabs.

func (Chain) Title

func (c Chain) Title() Chain

Title converts the string to title case.

func (Chain) ToSafeWeaver

func (c Chain) ToSafeWeaver() *SafeStringWeaver

ToSafeWeaver converts the Chain to a SafeStringWeaver for thread-safe operations.

func (Chain) ToWeaver

func (c Chain) ToWeaver() *StringWeaver

ToWeaver converts the Chain to a StringWeaver for more complex operations.

func (Chain) Trim

func (c Chain) Trim() Chain

Trim removes leading and trailing whitespace.

func (Chain) TrimChars

func (c Chain) TrimChars(cutset string) Chain

TrimChars removes leading and trailing characters in cutset.

func (Chain) TrimLeft

func (c Chain) TrimLeft(cutset string) Chain

TrimLeft removes leading characters in cutset.

func (Chain) TrimPrefix

func (c Chain) TrimPrefix(prefix string) Chain

TrimPrefix removes the specified prefix.

func (Chain) TrimRight

func (c Chain) TrimRight(cutset string) Chain

TrimRight removes trailing characters in cutset.

func (Chain) TrimSuffix

func (c Chain) TrimSuffix(suffix string) Chain

TrimSuffix removes the specified suffix.

func (Chain) Truncate

func (c Chain) Truncate(length int) Chain

Truncate truncates the string to the specified length.

func (Chain) TruncateWithSuffix

func (c Chain) TruncateWithSuffix(length int, suffix string) Chain

TruncateWithSuffix truncates and adds a suffix if truncated.

func (Chain) Unless

func (c Chain) Unless(condition bool, fn func(Chain) Chain) Chain

Unless applies a transformation function if the condition is false.

func (Chain) Upper

func (c Chain) Upper() Chain

Upper converts the string to uppercase.

func (Chain) When

func (c Chain) When(condition bool, fn func(Chain) Chain) Chain

When applies a transformation function if the condition is true.

func (Chain) Wrap

func (c Chain) Wrap(prefix, suffix string) Chain

Wrap wraps the current string with prefix and suffix.

type SafeStringWeaver

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

SafeStringWeaver wraps strings.Builder with a fluent API for chainable operations. This implementation is THREAD-SAFE and can be used concurrently by multiple goroutines. Each method acquires a mutex lock to ensure safe concurrent access.

For single-threaded usage where maximum performance is desired, use StringWeaver instead.

Example:

sw := strchain.NewSafe().Append("Hello").Space().Append("World")
fmt.Println(sw.Build()) // Output: Hello World

func NewSafe

func NewSafe() *SafeStringWeaver

NewSafe creates a new SafeStringWeaver instance.

Example:

sw := strchain.NewSafe()

func NewSafeWithCapacity

func NewSafeWithCapacity(capacity int) *SafeStringWeaver

NewSafeWithCapacity creates a new SafeStringWeaver with an initial capacity hint.

Example:

sw := strchain.NewSafeWithCapacity(1024)

func SafeFrom

func SafeFrom(s string) *SafeStringWeaver

SafeFrom creates a new SafeStringWeaver initialized with the given string.

Example:

sw := strchain.SafeFrom("Initial")

func SafeFromPtr

func SafeFromPtr(s *strings.Builder) *SafeStringWeaver

SafeFromPtr creates a new SafeStringWeaver initialized with the given strings.Builder pointer.

Example:

sw := strchain.SafeFromPtr(&myBuilder)

func (*SafeStringWeaver) Append

func (sw *SafeStringWeaver) Append(s string) Weaver

Append adds a string and returns the builder for chaining.

Example:

sw.Append("hello").Append(" world")

func (*SafeStringWeaver) AppendBool

func (sw *SafeStringWeaver) AppendBool(b bool) Weaver

AppendBool adds a boolean value and returns the builder.

Example:

sw.AppendBool(true)

func (*SafeStringWeaver) AppendByte

func (sw *SafeStringWeaver) AppendByte(b byte) Weaver

AppendByte adds a single byte and returns the builder.

Example:

sw.AppendByte('a')

func (*SafeStringWeaver) AppendBytes

func (sw *SafeStringWeaver) AppendBytes(b []byte) Weaver

AppendBytes adds a byte slice and returns the builder.

Example:

sw.AppendBytes([]byte("data"))

func (*SafeStringWeaver) AppendF

func (sw *SafeStringWeaver) AppendF(format string, args ...any) Weaver

AppendF adds a formatted string (printf-style) and returns the builder.

Example:

sw.AppendF("value: %d", 42)

func (*SafeStringWeaver) AppendFloat32

func (sw *SafeStringWeaver) AppendFloat32(f float32) Weaver

AppendFloat32 adds a float32 and returns the builder.

Example:

sw.AppendFloat32(3.14)

func (*SafeStringWeaver) AppendFloat64

func (sw *SafeStringWeaver) AppendFloat64(f float64) Weaver

AppendFloat64 adds a float64 and returns the builder.

Example:

sw.AppendFloat64(3.14159)

func (*SafeStringWeaver) AppendIf

func (sw *SafeStringWeaver) AppendIf(condition bool, s string) Weaver

AppendIf conditionally adds a string if the condition is true.

Example:

sw.AppendIf(isValid, " Validated")

func (*SafeStringWeaver) AppendIfF

func (sw *SafeStringWeaver) AppendIfF(condition bool, format string, args ...any) Weaver

AppendIfF conditionally adds a formatted string if the condition is true.

Example:

sw.AppendIfF(debugMode, "Debug: %s", msg)

func (*SafeStringWeaver) AppendInt

func (sw *SafeStringWeaver) AppendInt(i int) Weaver

AppendInt adds an integer and returns the builder.

Example:

sw.AppendInt(123)

func (*SafeStringWeaver) AppendInt8

func (sw *SafeStringWeaver) AppendInt8(i int8) Weaver

AppendInt8 adds an int8 and returns the builder.

Example:

sw.AppendInt8(8)

func (*SafeStringWeaver) AppendInt16

func (sw *SafeStringWeaver) AppendInt16(i int16) Weaver

AppendInt16 adds an int16 and returns the builder.

Example:

sw.AppendInt16(16)

func (*SafeStringWeaver) AppendInt32

func (sw *SafeStringWeaver) AppendInt32(i int32) Weaver

AppendInt32 adds an int32 and returns the builder.

Example:

sw.AppendInt32(32)

func (*SafeStringWeaver) AppendInt64

func (sw *SafeStringWeaver) AppendInt64(i int64) Weaver

AppendInt64 adds an int64 and returns the builder.

Example:

sw.AppendInt64(64)

func (*SafeStringWeaver) AppendRune

func (sw *SafeStringWeaver) AppendRune(r rune) Weaver

AppendRune adds a single rune and returns the builder.

Example:

sw.AppendRune('⌘')

func (*SafeStringWeaver) AppendUint

func (sw *SafeStringWeaver) AppendUint(i uint) Weaver

AppendUint adds a uint and returns the builder.

Example:

sw.AppendUint(123)

func (*SafeStringWeaver) AppendUint8

func (sw *SafeStringWeaver) AppendUint8(i uint8) Weaver

AppendUint8 adds a uint8 and returns the builder.

Example:

sw.AppendUint8(8)

func (*SafeStringWeaver) AppendUint16

func (sw *SafeStringWeaver) AppendUint16(i uint16) Weaver

AppendUint16 adds a uint16 and returns the builder.

Example:

sw.AppendUint16(16)

func (*SafeStringWeaver) AppendUint32

func (sw *SafeStringWeaver) AppendUint32(i uint32) Weaver

AppendUint32 adds a uint32 and returns the builder.

Example:

sw.AppendUint32(32)

func (*SafeStringWeaver) AppendUint64

func (sw *SafeStringWeaver) AppendUint64(i uint64) Weaver

AppendUint64 adds a uint64 and returns the builder.

Example:

sw.AppendUint64(64)

func (*SafeStringWeaver) AppendUintptr

func (sw *SafeStringWeaver) AppendUintptr(i uintptr) Weaver

AppendUintptr adds a uintptr and returns the builder.

Example:

sw.AppendUintptr(0xdeadbeef)

func (*SafeStringWeaver) Arrow

func (sw *SafeStringWeaver) Arrow() Weaver

Arrow adds an arrow (->) to the builder.

Example:

sw.Append("source").Arrow().Append("target")

func (*SafeStringWeaver) Bold added in v0.1.35

func (sw *SafeStringWeaver) Bold(s string) Weaver

Bold adds a string wrapped in double asterisks to the builder.

Example:

sw.Bold("bold text") // adds **bold text**

func (*SafeStringWeaver) Brace

func (sw *SafeStringWeaver) Brace(s string) Weaver

Brace wraps text in curly braces.

Example:

sw.Brace("struct definition") // adds {struct definition}

func (*SafeStringWeaver) Bracket

func (sw *SafeStringWeaver) Bracket(s string) Weaver

Bracket wraps text in square brackets.

Example:

sw.Bracket("index") // adds [index]

func (*SafeStringWeaver) Build

func (sw *SafeStringWeaver) Build() string

Build is an alias for String() for fluent API consistency.

Example:

result := sw.Append("data").Build()

func (*SafeStringWeaver) Builder

func (sw *SafeStringWeaver) Builder() *strings.Builder

Builder returns the underlying strings.Builder for advanced operations.

WARNING: This method bypasses ALL thread-safety guarantees of SafeStringWeaver. The mutex is NOT held while the caller uses the returned pointer. Any concurrent read or write through this pointer — including calling other SafeStringWeaver methods simultaneously — will cause a data race. Use this method only when the SafeStringWeaver is exclusively owned by a single goroutine at that point in time, or when you have external synchronization. For normal concurrent use, prefer the fluent methods which each acquire and release the lock atomically.

Example:

builder := sw.Builder()

func (*SafeStringWeaver) Bytes

func (sw *SafeStringWeaver) Bytes() []byte

Bytes returns the built string as a byte slice.

Example:

data := sw.Bytes()

func (*SafeStringWeaver) Cap

func (sw *SafeStringWeaver) Cap() int

Cap returns the current capacity of the builder.

Example:

capacity := sw.Cap()

func (*SafeStringWeaver) CarriageReturn added in v0.1.30

func (sw *SafeStringWeaver) CarriageReturn() Weaver

CarriageReturn adds a carriage return character and returns the builder.

Example:

sw.Append("Line 1").CarriageReturn().Append("Line 2")

func (*SafeStringWeaver) Clone

func (sw *SafeStringWeaver) Clone() Weaver

Clone creates a thread-safe copy of the current builder state.

Example:

newSw := sw.Clone()

func (*SafeStringWeaver) CodeBlock added in v0.1.35

func (sw *SafeStringWeaver) CodeBlock(language string, s Weaver) Weaver

CodeBlock adds a code block with the specified language and content.

Example:

sw.CodeBlock("go", sw.Append("fmt.Println(\"Hello, World!\")"))

func (*SafeStringWeaver) Colon

func (sw *SafeStringWeaver) Colon() Weaver

Colon adds a colon to the builder.

Example:

sw.Append("Label").Colon().Space().Append("Value")

func (*SafeStringWeaver) Comma

func (sw *SafeStringWeaver) Comma() Weaver

Comma adds a comma to the builder.

Example:

sw.Append("item1").Comma().Append("item2")

func (*SafeStringWeaver) CommaIfNotLast

func (sw *SafeStringWeaver) CommaIfNotLast(index, total int) Weaver

CommaIfNotLast adds a comma if the index is not the last item.

Example:

sw.CommaIfNotLast(i, len(items)) // adds "," if i < len(items)-1

func (*SafeStringWeaver) Dash added in v0.1.35

func (sw *SafeStringWeaver) Dash() Weaver

Dash adds a dash character and returns the builder.

Example:

sw.Append("Item 1").Dash().Append("Item 2")

func (*SafeStringWeaver) Dashes added in v0.1.35

func (sw *SafeStringWeaver) Dashes(n int) Weaver

Dashes adds n dash characters and returns the builder.

Example:

sw.Append("Item 1").Dashes(5).Append("Item 2")

func (*SafeStringWeaver) Dot

func (sw *SafeStringWeaver) Dot() Weaver

Dot adds a period to the builder.

Example:

sw.Append("End of sentence").Dot()

func (*SafeStringWeaver) Each

func (sw *SafeStringWeaver) Each(items []string, fn func(*SafeStringWeaver, string)) *SafeStringWeaver

Each iterates over a slice and applies a function for each element.

Example:

sw.Each([]string{"a", "b", "c"}, func(s *SafeStringWeaver, item string) {
    s.Append(item).Comma()
})

func (*SafeStringWeaver) EachCast

func (sw *SafeStringWeaver) EachCast(items []string, fn func(w Weaver, item string)) Weaver

EachCast executes a function for each item in the slice.

Example:

sw.EachCast(items, func(w Weaver, item string) {
	w.Append(item).Comma()
})

func (*SafeStringWeaver) EndBrace

func (sw *SafeStringWeaver) EndBrace() Weaver

EndBrace adds a closing brace.

Example:

sw.EndBrace() // adds '}'

func (*SafeStringWeaver) EndBracket

func (sw *SafeStringWeaver) EndBracket() Weaver

EndBracket adds a closing bracket.

Example:

sw.EndBracket() // adds ']'

func (*SafeStringWeaver) EndParenthesize

func (sw *SafeStringWeaver) EndParenthesize() Weaver

EndParenthesize adds a closing parenthesis.

Example:

sw.EndParenthesize() // adds ')'

func (*SafeStringWeaver) Equals

func (sw *SafeStringWeaver) Equals() Weaver

Equals adds an equals sign to the builder.

Example:

sw.Append("key").Equals().Append("value")

func (*SafeStringWeaver) FatArrow

func (sw *SafeStringWeaver) FatArrow() Weaver

FatArrow adds a fat arrow (=>) to the builder.

Example:

sw.Append("map").FatArrow().Append("result")

func (*SafeStringWeaver) Grow

func (sw *SafeStringWeaver) Grow(n int) Weaver

Grow grows the builder's capacity by n bytes.

Example:

sw.Grow(512)

func (*SafeStringWeaver) Indent

func (sw *SafeStringWeaver) Indent(level int, s string) Weaver

Indent adds indentation (2 spaces per level) before appending text.

Example:

sw.Indent(2, "Sub-item")

func (*SafeStringWeaver) IndentF

func (sw *SafeStringWeaver) IndentF(level int, format string, args ...any) Weaver

IndentF adds indentation (2 spaces per level) before appending a formatted string.

Example:

sw.IndentF(1, `"id": %q,`, "abc123")

func (*SafeStringWeaver) IndentLine

func (sw *SafeStringWeaver) IndentLine(level int, s string) Weaver

IndentLine adds indentation (2 spaces per level) before text and ends with a newline.

Example:

sw.IndentLine(1, "Point 1")

func (*SafeStringWeaver) IndentLineF

func (sw *SafeStringWeaver) IndentLineF(level int, format string, args ...any) Weaver

IndentLineF adds indentation (2 spaces per level) before a formatted string and ends with a newline.

Example:

sw.IndentLineF(1, `"id": %q,`, "abc123")

func (*SafeStringWeaver) IndentOnly

func (sw *SafeStringWeaver) IndentOnly(level int) Weaver

IndentOnly adds indentation (2 spaces per level) without appending text.

Example:

sw.IndentOnly(1) // adds '  '

func (*SafeStringWeaver) IndentOnlyLine

func (sw *SafeStringWeaver) IndentOnlyLine(level int) Weaver

IndentOnlyLine adds indentation (2 spaces per level) followed by a newline.

Example:

sw.IndentOnlyLine(1) // adds '  \n'

func (*SafeStringWeaver) InlineCode added in v0.1.35

func (sw *SafeStringWeaver) InlineCode(s string) Weaver

InlineCode adds a string wrapped in backticks to the builder.

Example:

sw.InlineCode("inline code") // adds `inline code`

func (*SafeStringWeaver) InlineCodeF added in v0.1.35

func (sw *SafeStringWeaver) InlineCodeF(format string, args ...any) Weaver

InlineCodeF adds a formatted string wrapped in backticks to the builder.

Example:

sw.InlineCodeF("inline %s", "code") // adds '`inline code`'

func (*SafeStringWeaver) Inspect

func (sw *SafeStringWeaver) Inspect(fn func(current string)) Weaver

Inspect executes a function with access to the current state without modification.

Example:

sw.Inspect(func(current string) {
    log.Printf("Current state: %s", current)
})

func (*SafeStringWeaver) IsEmpty added in v0.1.35

func (sw *SafeStringWeaver) IsEmpty() bool

IsEmpty checks if the builder is empty.

Example:

if sw.IsEmpty() {
    // Handle empty case
}

func (*SafeStringWeaver) IsNotEmpty added in v0.1.35

func (sw *SafeStringWeaver) IsNotEmpty() bool

IsNotEmpty checks if the builder is not empty.

Example:

if sw.IsNotEmpty() {
    // Handle non-empty case
}

func (*SafeStringWeaver) Italic added in v0.1.35

func (sw *SafeStringWeaver) Italic(s string) Weaver

Italic adds a string wrapped in single asterisks to the builder.

Example:

sw.Italic("italic text") // adds *italic text*

func (*SafeStringWeaver) JSONArrayEnd

func (sw *SafeStringWeaver) JSONArrayEnd() Weaver

JSONArrayEnd adds a closing square bracket for a JSON array.

Example:

sw.JSONArrayEnd() // adds "]"

func (*SafeStringWeaver) JSONArrayStart

func (sw *SafeStringWeaver) JSONArrayStart() Weaver

JSONArrayStart adds an opening square bracket for a JSON array.

Example:

sw.JSONArrayStart() // adds "["

func (*SafeStringWeaver) JSONFieldArrayEnd

func (sw *SafeStringWeaver) JSONFieldArrayEnd(level int) Weaver

JSONFieldArrayEnd adds an indented JSON array end.

Example:

sw.JSONFieldArrayEnd(1) // adds '  ]'

func (*SafeStringWeaver) JSONFieldArrayStart

func (sw *SafeStringWeaver) JSONFieldArrayStart(level int, key string) Weaver

JSONFieldArrayStart adds an indented JSON array start.

Example:

sw.JSONFieldArrayStart(1, "items") // adds '  "items": ['

func (*SafeStringWeaver) JSONFieldBool

func (sw *SafeStringWeaver) JSONFieldBool(level int, key string, value bool, addComma bool) Weaver

JSONFieldBool adds an indented JSON field with a bool value.

Example:

sw.JSONFieldBool(1, "age", 30, true) // adds '  "age": 30,\n'

func (*SafeStringWeaver) JSONFieldFloat32

func (sw *SafeStringWeaver) JSONFieldFloat32(level int, key string, value float32, addComma bool) Weaver

JSONFieldFloat32 adds an indented JSON field with a float32 value.

Example:

sw.JSONFieldFloat32(1, "age", 30, true) // adds '  "age": 30,\n'

func (*SafeStringWeaver) JSONFieldFloat64

func (sw *SafeStringWeaver) JSONFieldFloat64(level int, key string, value float64, addComma bool) Weaver

JSONFieldFloat64 adds an indented JSON field with a float64 value.

Example:

sw.JSONFieldFloat64(1, "age", 30, true) // adds '  "age": 30,\n'

func (*SafeStringWeaver) JSONFieldInt

func (sw *SafeStringWeaver) JSONFieldInt(level int, key string, value int, addComma bool) Weaver

JSONFieldInt adds an indented JSON field with an integer value.

Example:

sw.JSONFieldInt(1, "age", 30, true) // adds '  "age": 30,\n'

func (*SafeStringWeaver) JSONFieldInt8

func (sw *SafeStringWeaver) JSONFieldInt8(level int, key string, value int8, addComma bool) Weaver

JSONFieldInt8 adds an indented JSON field with an int8 value.

Example:

sw.JSONFieldInt8(1, "age", 30, true) // adds '  "age": 30,\n'

func (*SafeStringWeaver) JSONFieldInt16

func (sw *SafeStringWeaver) JSONFieldInt16(level int, key string, value int16, addComma bool) Weaver

JSONFieldInt16 adds an indented JSON field with an int16 value.

Example:

sw.JSONFieldInt16(1, "age", 30, true) // adds '  "age": 30,\n'

func (*SafeStringWeaver) JSONFieldInt32

func (sw *SafeStringWeaver) JSONFieldInt32(level int, key string, value int32, addComma bool) Weaver

JSONFieldInt32 adds an indented JSON field with an int32 value.

Example:

sw.JSONFieldInt32(1, "age", 30, true) // adds '  "age": 30,\n'

func (*SafeStringWeaver) JSONFieldInt64

func (sw *SafeStringWeaver) JSONFieldInt64(level int, key string, value int64, addComma bool) Weaver

JSONFieldInt64 adds an indented JSON field with an int64 value.

Example:

sw.JSONFieldInt64(1, "age", 30, true) // adds '  "age": 30,\n'

func (*SafeStringWeaver) JSONFieldString

func (sw *SafeStringWeaver) JSONFieldString(level int, key, value string, addComma bool) Weaver

JSONFieldString adds an indented JSON field (key: value) with optional comma and newline. The value is properly JSON-encoded (RFC 8259).

Example:

sw.JSONFieldString(1, "name", `"John"`, true) // adds '  "name": "John",\n'

func (*SafeStringWeaver) JSONFieldUint

func (sw *SafeStringWeaver) JSONFieldUint(level int, key string, value uint, addComma bool) Weaver

JSONFieldUint adds an indented JSON field with a uint value.

Example:

sw.JSONFieldUint(1, "age", 30, true) // adds '  "age": 30,\n'

func (*SafeStringWeaver) JSONFieldUint8

func (sw *SafeStringWeaver) JSONFieldUint8(level int, key string, value uint8, addComma bool) Weaver

JSONFieldUint8 adds an indented JSON field with a uint8 value.

Example:

sw.JSONFieldUint8(1, "age", 30, true) // adds '  "age": 30,\n'

func (*SafeStringWeaver) JSONFieldUint16

func (sw *SafeStringWeaver) JSONFieldUint16(level int, key string, value uint16, addComma bool) Weaver

JSONFieldUint16 adds an indented JSON field with a uint16 value.

Example:

sw.JSONFieldUint16(1, "age", 30, true) // adds '  "age": 30,\n'

func (*SafeStringWeaver) JSONFieldUint32

func (sw *SafeStringWeaver) JSONFieldUint32(level int, key string, value uint32, addComma bool) Weaver

JSONFieldUint32 adds an indented JSON field with a uint32 value.

Example:

sw.JSONFieldUint32(1, "age", 30, true) // adds '  "age": 30,\n'

func (*SafeStringWeaver) JSONFieldUint64

func (sw *SafeStringWeaver) JSONFieldUint64(level int, key string, value uint64, addComma bool) Weaver

JSONFieldUint64 adds an indented JSON field with a uint64 value.

Example:

sw.JSONFieldUint64(1, "age", 30, true) // adds '  "age": 30,\n'

func (*SafeStringWeaver) JSONKey

func (sw *SafeStringWeaver) JSONKey(key string) Weaver

JSONKey adds a quoted key followed by a colon and space.

Example:

sw.JSONKey("name") // adds "name":

func (*SafeStringWeaver) JSONKeyBool

func (sw *SafeStringWeaver) JSONKeyBool(key string, value bool) Weaver

JSONKeyBool adds a key-value pair where the value is a boolean.

Example:

sw.JSONKeyBool("active", true) // adds "active": true

func (*SafeStringWeaver) JSONKeyFloat

func (sw *SafeStringWeaver) JSONKeyFloat(key string, value float64) Weaver

JSONKeyFloat adds a key-value pair where the value is a float.

Example:

sw.JSONKeyFloat("price", 19.99) // adds "price": 19.99

func (*SafeStringWeaver) JSONKeyInt

func (sw *SafeStringWeaver) JSONKeyInt(key string, value int) Weaver

JSONKeyInt adds a key-value pair where the value is an integer.

Example:

sw.JSONKeyInt("age", 30) // adds "age": 30

func (*SafeStringWeaver) JSONKeyString

func (sw *SafeStringWeaver) JSONKeyString(key, value string) Weaver

JSONKeyString adds a key-value pair where the value is a string. The value is properly JSON-encoded (RFC 8259).

Example:

sw.JSONKeyString("name", "John") // adds "name": "John"

func (*SafeStringWeaver) JSONObjectEnd

func (sw *SafeStringWeaver) JSONObjectEnd() Weaver

JSONObjectEnd adds a closing curly brace for a JSON object.

Example:

sw.JSONObjectEnd() // adds "}"

func (*SafeStringWeaver) JSONObjectStart

func (sw *SafeStringWeaver) JSONObjectStart() Weaver

JSONObjectStart adds an opening curly brace for a JSON object.

Example:

sw.JSONObjectStart() // adds "{" (thread-safe)

func (*SafeStringWeaver) JSONString

func (sw *SafeStringWeaver) JSONString(s string) Weaver

JSONString adds a quoted and escaped string value. The output is proper JSON (RFC 8259) — control characters are encoded as \uXXXX sequences, not Go-specific escape sequences.

Example:

sw.JSONString("hello") // adds "hello"

func (*SafeStringWeaver) Join

func (sw *SafeStringWeaver) Join(sep string, elements ...string) Weaver

Join adds strings with a separator and returns the builder.

Example:

sw.Join(", ", "Apple", "Banana", "Cherry")

func (*SafeStringWeaver) Len

func (sw *SafeStringWeaver) Len() int

Len returns the current length of the built string.

Example:

length := sw.Len()

func (*SafeStringWeaver) Line

func (sw *SafeStringWeaver) Line(s string) Weaver

Line adds a string followed by a newline and returns the builder.

Example:

sw.Line("First Line").Line("Second Line")

func (*SafeStringWeaver) LineF

func (sw *SafeStringWeaver) LineF(format string, args ...any) Weaver

LineF adds a formatted string followed by a newline and returns the builder.

Example:

sw.LineF("User ID: %d", 123)

func (*SafeStringWeaver) NewLine

func (sw *SafeStringWeaver) NewLine() Weaver

NewLine adds a single newline character and returns the builder.

Example:

sw.Append("Line 1").NewLine().Append("Line 2")

func (*SafeStringWeaver) NewLines

func (sw *SafeStringWeaver) NewLines(n int) Weaver

NewLines adds n newline characters and returns the builder.

Example:

sw.Append("Paragraph 1").NewLines(2).Append("Paragraph 2")

func (*SafeStringWeaver) Parenthesize

func (sw *SafeStringWeaver) Parenthesize(s string) Weaver

Parenthesize wraps text in parentheses.

Example:

sw.Parenthesize("expression") // adds (expression)

func (*SafeStringWeaver) Pipe added in v0.1.35

func (sw *SafeStringWeaver) Pipe() Weaver

Pipe adds a pipe character and returns the builder.

Example:

sw.Append("Column 1").Pipe().Append("Column 2")

func (*SafeStringWeaver) Pipes added in v0.1.35

func (sw *SafeStringWeaver) Pipes(n int) Weaver

Pipes adds n pipe characters and returns the builder.

Example:

sw.Append("Column 1").Pipes(3).Append("Column 2")

func (*SafeStringWeaver) Quote

func (sw *SafeStringWeaver) Quote(s string) Weaver

Quote wraps text in double quotes.

Example:

sw.Quote("quoted string") // adds "quoted string"

func (*SafeStringWeaver) Repeat

func (sw *SafeStringWeaver) Repeat(s string, n int) Weaver

Repeat adds a string n times and returns the builder.

Example:

sw.Repeat("-", 10) // adds "----------"

func (*SafeStringWeaver) Reset

func (sw *SafeStringWeaver) Reset() Weaver

Reset clears the builder and returns it for reuse.

Example:

sw.Reset().Append("Fresh start")

func (*SafeStringWeaver) Semicolon

func (sw *SafeStringWeaver) Semicolon() Weaver

Semicolon adds a semicolon to the builder.

Example:

sw.Append("x = 1").Semicolon()

func (*SafeStringWeaver) SingleQuote

func (sw *SafeStringWeaver) SingleQuote(s string) Weaver

SingleQuote wraps text in single quotes.

Example:

sw.SingleQuote("char") // adds 'char'

func (*SafeStringWeaver) Space

func (sw *SafeStringWeaver) Space() Weaver

Space adds a single space character and returns the builder.

Example:

sw.Append("Hello").Space().Append("World")

func (*SafeStringWeaver) Spaces

func (sw *SafeStringWeaver) Spaces(n int) Weaver

Spaces adds n space characters and returns the builder.

Example:

sw.Append("Key:").Spaces(4).Append("Value")

func (*SafeStringWeaver) StartBrace

func (sw *SafeStringWeaver) StartBrace() Weaver

StartBrace adds an opening brace.

Example:

sw.StartBrace() // adds '{'

func (*SafeStringWeaver) StartBracket

func (sw *SafeStringWeaver) StartBracket() Weaver

StartBracket adds an opening bracket.

Example:

sw.StartBracket() // adds '['

func (*SafeStringWeaver) StartParenthesize

func (sw *SafeStringWeaver) StartParenthesize() Weaver

StartParenthesize adds an opening parenthesis.

Example:

sw.StartParenthesize() // adds '('

func (*SafeStringWeaver) Strikethrough added in v0.1.35

func (sw *SafeStringWeaver) Strikethrough(s string) Weaver

Strikethrough adds a string wrapped in double tildes to the builder.

Example:

sw.Strikethrough("strikethrough text") // adds ~~strikethrough text~~

func (*SafeStringWeaver) String

func (sw *SafeStringWeaver) String() string

String returns the final built string.

Example:

result := sw.String()

func (*SafeStringWeaver) Tab

func (sw *SafeStringWeaver) Tab() Weaver

Tab adds a single tab character and returns the builder.

Example:

sw.Append("Column1").Tab().Append("Column2")

func (*SafeStringWeaver) Tabs

func (sw *SafeStringWeaver) Tabs(n int) Weaver

Tabs adds n tab characters and returns the builder.

Example:

sw.Tabs(2).Append("Indented text")

func (*SafeStringWeaver) Underline added in v0.1.35

func (sw *SafeStringWeaver) Underline(s string) Weaver

Underline adds a string wrapped in <u> tags to the builder.

Example:

sw.Underline("underlined text") // adds <u>underlined text</u>

func (*SafeStringWeaver) Underscore added in v0.1.35

func (sw *SafeStringWeaver) Underscore() Weaver

Underscore adds an underscore character and returns the builder.

Example:

sw.Append("Item 1").Underscore().Append("Item 2")

func (*SafeStringWeaver) Underscores added in v0.1.35

func (sw *SafeStringWeaver) Underscores(n int) Weaver

Underscores adds n underscore characters and returns the builder.

Example:

sw.Append("Item 1").Underscores(5).Append("Item 2")

func (*SafeStringWeaver) Unless

func (sw *SafeStringWeaver) Unless(condition bool, fn func(*SafeStringWeaver)) *SafeStringWeaver

Unless executes a function on the builder if the condition is false.

Example:

sw.Unless(isMinified, func(s *SafeStringWeaver) {
    s.NewLine().Indent(1, "")
})

func (*SafeStringWeaver) UnlessCast

func (sw *SafeStringWeaver) UnlessCast(condition bool, fn func(w Weaver)) Weaver

UnlessCast executes a function with access to the current state without modification.

Example:

sw.UnlessCast(isHeader, func(w Weaver) {
	w.Append("Header: ")
})

func (*SafeStringWeaver) When

func (sw *SafeStringWeaver) When(condition bool, fn func(*SafeStringWeaver)) *SafeStringWeaver

When executes a function on the builder if the condition is true.

Example:

sw.When(isHeader, func(s *SafeStringWeaver) {
    s.Append("# ").Line(title)
})

func (*SafeStringWeaver) WhenCast

func (sw *SafeStringWeaver) WhenCast(condition bool, fn func(w Weaver)) Weaver

WhenCast executes a function with access to the current state without modification.

Example:

sw.WhenCast(isHeader, func(w Weaver) {
	w.Append("Header: ")
})

func (*SafeStringWeaver) Wrap

func (sw *SafeStringWeaver) Wrap(prefix, text, suffix string) Weaver

Wrap wraps text with a prefix and suffix.

Example:

sw.Wrap("**", "Bold text", "**")

type StringWeaver

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

StringWeaver wraps strings.Builder with a fluent API for chainable operations. This implementation is NOT thread-safe and should only be used from a single goroutine. For concurrent access, use SafeStringWeaver instead.

Example:

sw := strchain.New().Append("Hello").Space().Append("World")
fmt.Println(sw.String()) // Output: Hello World

func From

func From(s string) *StringWeaver

From creates a new StringWeaver initialized with the given string.

Example:

sw := strchain.From("Initial")

func FromPtr

func FromPtr(s *strings.Builder) *StringWeaver

FromPtr creates a new StringWeaver initialized with the given strings.Builder pointer.

Example:

sw := strchain.FromPtr(&myBuilder)

func New

func New() *StringWeaver

New creates a new StringWeaver instance.

Example:

sw := strchain.New()

func NewWithCapacity

func NewWithCapacity(capacity int) *StringWeaver

NewWithCapacity creates a new StringWeaver with an initial capacity hint.

Example:

sw := strchain.NewWithCapacity(1024)

func (*StringWeaver) Append

func (sw *StringWeaver) Append(s string) Weaver

Append adds a string and returns the builder for chaining.

Example:

sw.Append("hello").Append(" world")

func (*StringWeaver) AppendBool

func (sw *StringWeaver) AppendBool(b bool) Weaver

AppendBool adds a boolean value and returns the builder.

Example:

sw.AppendBool(true)

func (*StringWeaver) AppendByte

func (sw *StringWeaver) AppendByte(b byte) Weaver

AppendByte adds a single byte and returns the builder.

Example:

sw.AppendByte('a')

func (*StringWeaver) AppendBytes

func (sw *StringWeaver) AppendBytes(b []byte) Weaver

AppendBytes adds a byte slice and returns the builder.

Example:

sw.AppendBytes([]byte("data"))

func (*StringWeaver) AppendF

func (sw *StringWeaver) AppendF(format string, args ...any) Weaver

AppendF adds a formatted string (printf-style) and returns the builder.

Example:

sw.AppendF("value: %d", 42)

func (*StringWeaver) AppendFloat32

func (sw *StringWeaver) AppendFloat32(f float32) Weaver

AppendFloat32 adds a float32 and returns the builder.

Example:

sw.AppendFloat32(3.14)

func (*StringWeaver) AppendFloat64

func (sw *StringWeaver) AppendFloat64(f float64) Weaver

AppendFloat64 adds a float64 and returns the builder.

Example:

sw.AppendFloat64(3.14159)

func (*StringWeaver) AppendIf

func (sw *StringWeaver) AppendIf(condition bool, s string) Weaver

AppendIf conditionally adds a string if the condition is true.

Example:

sw.AppendIf(isValid, " Validated")

func (*StringWeaver) AppendIfF

func (sw *StringWeaver) AppendIfF(condition bool, format string, args ...any) Weaver

AppendIfF conditionally adds a formatted string if the condition is true.

Example:

sw.AppendIfF(debugMode, "Debug: %s", msg)

func (*StringWeaver) AppendInt

func (sw *StringWeaver) AppendInt(i int) Weaver

AppendInt adds an integer and returns the builder.

Example:

sw.AppendInt(123)

func (*StringWeaver) AppendInt8

func (sw *StringWeaver) AppendInt8(i int8) Weaver

AppendInt8 adds an int8 and returns the builder.

Example:

sw.AppendInt8(8)

func (*StringWeaver) AppendInt16

func (sw *StringWeaver) AppendInt16(i int16) Weaver

AppendInt16 adds an int16 and returns the builder.

Example:

sw.AppendInt16(16)

func (*StringWeaver) AppendInt32

func (sw *StringWeaver) AppendInt32(i int32) Weaver

AppendInt32 adds an int32 and returns the builder.

Example:

sw.AppendInt32(32)

func (*StringWeaver) AppendInt64

func (sw *StringWeaver) AppendInt64(i int64) Weaver

AppendInt64 adds an int64 and returns the builder.

Example:

sw.AppendInt64(64)

func (*StringWeaver) AppendRune

func (sw *StringWeaver) AppendRune(r rune) Weaver

AppendRune adds a single rune and returns the builder.

Example:

sw.AppendRune('⌘')

func (*StringWeaver) AppendUint

func (sw *StringWeaver) AppendUint(i uint) Weaver

AppendUint adds a uint and returns the builder.

Example:

sw.AppendUint(123)

func (*StringWeaver) AppendUint8

func (sw *StringWeaver) AppendUint8(i uint8) Weaver

AppendUint8 adds a uint8 and returns the builder.

Example:

sw.AppendUint8(8)

func (*StringWeaver) AppendUint16

func (sw *StringWeaver) AppendUint16(i uint16) Weaver

AppendUint16 adds a uint16 and returns the builder.

Example:

sw.AppendUint16(16)

func (*StringWeaver) AppendUint32

func (sw *StringWeaver) AppendUint32(i uint32) Weaver

AppendUint32 adds a uint32 and returns the builder.

Example:

sw.AppendUint32(32)

func (*StringWeaver) AppendUint64

func (sw *StringWeaver) AppendUint64(i uint64) Weaver

AppendUint64 adds a uint64 and returns the builder.

Example:

sw.AppendUint64(64)

func (*StringWeaver) AppendUintptr

func (sw *StringWeaver) AppendUintptr(i uintptr) Weaver

AppendUintptr adds a uintptr and returns the builder.

Example:

sw.AppendUintptr(0xdeadbeef)

func (*StringWeaver) Arrow

func (sw *StringWeaver) Arrow() Weaver

Arrow adds an arrow (->) to the builder.

Example:

sw.Append("source").Arrow().Append("target")

func (*StringWeaver) Bold added in v0.1.35

func (sw *StringWeaver) Bold(s string) Weaver

Bold adds a string wrapped in double asterisks for bold representation.

Example:

sw.Bold("Important") // adds "**Important**"

func (*StringWeaver) Brace

func (sw *StringWeaver) Brace(s string) Weaver

Brace wraps text in curly braces.

Example:

sw.Brace("struct definition") // adds {struct definition}

func (*StringWeaver) Bracket

func (sw *StringWeaver) Bracket(s string) Weaver

Bracket wraps text in square brackets.

Example:

sw.Bracket("index") // adds [index]

func (*StringWeaver) Build

func (sw *StringWeaver) Build() string

Build is an alias for String() for fluent API consistency.

Example:

result := sw.Append("data").Build()

func (*StringWeaver) Builder

func (sw *StringWeaver) Builder() *strings.Builder

Builder returns the underlying strings.Builder for advanced operations.

Example:

builder := sw.Builder()

func (*StringWeaver) Bytes

func (sw *StringWeaver) Bytes() []byte

Bytes returns the built string as a byte slice.

Example:

data := sw.Bytes()

func (*StringWeaver) Cap

func (sw *StringWeaver) Cap() int

Cap returns the current capacity of the builder.

Example:

capacity := sw.Cap()

func (*StringWeaver) CarriageReturn added in v0.1.30

func (sw *StringWeaver) CarriageReturn() Weaver

CarriageReturn adds a carriage return character and returns the builder.

Example:

sw.Append("Line 1").CarriageReturn().Append("Line 2")

func (*StringWeaver) Clone

func (sw *StringWeaver) Clone() Weaver

Clone creates an independent copy of the current builder state.

Example:

newSw := sw.Clone()

func (*StringWeaver) CodeBlock added in v0.1.35

func (sw *StringWeaver) CodeBlock(language string, s Weaver) Weaver

CodeBlock adds a code block with the specified language and content.

Example:

sw.CodeBlock("go", New().Append("fmt.Println(\"Hello, World!\")"))

func (*StringWeaver) Colon

func (sw *StringWeaver) Colon() Weaver

Colon adds a colon to the builder.

Example:

sw.Append("Label").Colon().Space().Append("Value")

func (*StringWeaver) Comma

func (sw *StringWeaver) Comma() Weaver

Comma adds a comma to the builder.

Example:

sw.Append("item1").Comma().Append("item2")

func (*StringWeaver) CommaIfNotLast

func (sw *StringWeaver) CommaIfNotLast(index, total int) Weaver

CommaIfNotLast adds a comma if the index is not the last item.

Example:

sw.CommaIfNotLast(i, len(items)) // adds "," if i < len(items)-1

func (*StringWeaver) Dash added in v0.1.35

func (sw *StringWeaver) Dash() Weaver

Dash adds a dash character and returns the builder.

Example:

sw.Append("Item1").Dash().Append("Item2")

func (*StringWeaver) Dashes added in v0.1.35

func (sw *StringWeaver) Dashes(n int) Weaver

Dashes adds n dash characters and returns the builder.

Example:

sw.Dashes(5) // adds "-----"

func (*StringWeaver) Dot

func (sw *StringWeaver) Dot() Weaver

Dot adds a period to the builder.

Example:

sw.Append("End of sentence").Dot()

func (*StringWeaver) Each

func (sw *StringWeaver) Each(items []string, fn func(*StringWeaver, string)) *StringWeaver

Each iterates over a slice and applies a function for each element.

Example:

sw.Each([]string{"a", "b", "c"}, func(s *StringWeaver, item string) {
    s.Append(item).Comma()
})

func (*StringWeaver) EachCast

func (sw *StringWeaver) EachCast(items []string, fn func(w Weaver, item string)) Weaver

EachCast executes a function for each item in the slice.

Example:

sw.EachCast(items, func(w Weaver, item string) {
	w.Append(item)
})

func (*StringWeaver) EndBrace

func (sw *StringWeaver) EndBrace() Weaver

EndBrace adds a closing brace.

Example:

sw.EndBrace() // adds '}'

func (*StringWeaver) EndBracket

func (sw *StringWeaver) EndBracket() Weaver

EndBracket adds a closing bracket.

Example:

sw.EndBracket() // adds ']'

func (*StringWeaver) EndParenthesize

func (sw *StringWeaver) EndParenthesize() Weaver

EndParenthesize adds a closing parenthesis.

Example:

sw.EndParenthesize() // adds ')'

func (*StringWeaver) Equals

func (sw *StringWeaver) Equals() Weaver

Equals adds an equals sign to the builder.

Example:

sw.Append("key").Equals().Append("value")

func (*StringWeaver) FatArrow

func (sw *StringWeaver) FatArrow() Weaver

FatArrow adds a fat arrow (=>) to the builder.

Example:

sw.Append("map").FatArrow().Append("result")

func (*StringWeaver) Grow

func (sw *StringWeaver) Grow(n int) Weaver

Grow grows the builder's capacity by n bytes.

Example:

sw.Grow(512)

func (*StringWeaver) Indent

func (sw *StringWeaver) Indent(level int, s string) Weaver

Indent adds indentation (2 spaces per level) before appending text.

Example:

sw.Indent(2, "Sub-item")

func (*StringWeaver) IndentF

func (sw *StringWeaver) IndentF(level int, format string, args ...any) Weaver

IndentF adds indentation (2 spaces per level) before appending a formatted string.

Example:

sw.IndentF(1, `"id": %q,`, "abc123")

func (*StringWeaver) IndentLine

func (sw *StringWeaver) IndentLine(level int, s string) Weaver

IndentLine adds indentation (2 spaces per level) before text and ends with a newline.

Example:

sw.IndentLine(1, "Point 1")

func (*StringWeaver) IndentLineF

func (sw *StringWeaver) IndentLineF(level int, format string, args ...any) Weaver

IndentLineF adds indentation (2 spaces per level) before a formatted string and ends with a newline.

Example:

sw.IndentLineF(1, `"id": %q,`, "abc123")

func (*StringWeaver) IndentOnly

func (sw *StringWeaver) IndentOnly(level int) Weaver

IndentOnly adds indentation (2 spaces per level) without appending text.

Example:

sw.IndentOnly(1) // adds '  '

func (*StringWeaver) IndentOnlyLine

func (sw *StringWeaver) IndentOnlyLine(level int) Weaver

IndentOnlyLine adds indentation (2 spaces per level) followed by a newline.

Example:

sw.IndentOnlyLine(1) // adds '  \n'

func (*StringWeaver) InlineCode added in v0.1.35

func (sw *StringWeaver) InlineCode(s string) Weaver

InlineCode adds a string wrapped in backticks for code representation.

Example:

sw.InlineCode("fmt.Println(\"Hello, World!\")") // adds `fmt.Println("Hello, World!")`

func (*StringWeaver) InlineCodeF added in v0.1.35

func (sw *StringWeaver) InlineCodeF(format string, args ...any) Weaver

InlineCodeF adds a formatted inline code (printf-style) to the builder.

Example:

sw.InlineCodeF("inline %s", "code") // adds '`inline code`'

func (*StringWeaver) Inspect

func (sw *StringWeaver) Inspect(fn func(current string)) Weaver

Inspect executes a function with access to the current state without modification.

Example:

sw.Inspect(func(current string) {
    log.Printf("Current state: %s", current)
})

func (*StringWeaver) IsEmpty added in v0.1.35

func (sw *StringWeaver) IsEmpty() bool

IsEmpty checks if the builder is empty.

Example:

if sw.IsEmpty() {
    fmt.Println("Builder is empty")
}

func (*StringWeaver) IsNotEmpty added in v0.1.35

func (sw *StringWeaver) IsNotEmpty() bool

IsNotEmpty checks if the builder is not empty.

Example:

if sw.IsNotEmpty() {
    fmt.Println("Builder has content")
}

func (*StringWeaver) Italic added in v0.1.35

func (sw *StringWeaver) Italic(s string) Weaver

Italic adds a string wrapped in single asterisks for italic representation.

Example:

sw.Italic("Emphasized") // adds "*Emphasized*"

func (*StringWeaver) JSONArrayEnd

func (sw *StringWeaver) JSONArrayEnd() Weaver

JSONArrayEnd adds a closing square bracket for a JSON array.

Example:

sw.JSONArrayEnd() // adds "]"

func (*StringWeaver) JSONArrayStart

func (sw *StringWeaver) JSONArrayStart() Weaver

JSONArrayStart adds an opening square bracket for a JSON array.

Example:

sw.JSONArrayStart() // adds "["

func (*StringWeaver) JSONFieldArrayEnd

func (sw *StringWeaver) JSONFieldArrayEnd(level int) Weaver

JSONFieldArrayEnd adds an indented JSON array end.

Example:

sw.JSONFieldArrayEnd(1) // adds '  ]'

func (*StringWeaver) JSONFieldArrayStart

func (sw *StringWeaver) JSONFieldArrayStart(level int, key string) Weaver

JSONFieldArrayStart adds an indented JSON array start.

Example:

sw.JSONFieldArrayStart(1, "items", true) // adds '  "items": ['

func (*StringWeaver) JSONFieldBool

func (sw *StringWeaver) JSONFieldBool(level int, key string, value bool, addComma bool) Weaver

JSONFieldBool adds an indented JSON field with a bool value.

Example:

sw.JSONFieldBool(1, "age", 30, true) // adds '  "age": 30,\n'

func (*StringWeaver) JSONFieldFloat32

func (sw *StringWeaver) JSONFieldFloat32(level int, key string, value float32, addComma bool) Weaver

JSONFieldFloat32 adds an indented JSON field with a float32 value.

Example:

sw.JSONFieldFloat32(1, "age", 30, true) // adds '  "age": 30,\n'

func (*StringWeaver) JSONFieldFloat64

func (sw *StringWeaver) JSONFieldFloat64(level int, key string, value float64, addComma bool) Weaver

JSONFieldFloat64 adds an indented JSON field with a float64 value.

Example:

sw.JSONFieldFloat64(1, "age", 30, true) // adds '  "age": 30,\n'

func (*StringWeaver) JSONFieldInt

func (sw *StringWeaver) JSONFieldInt(level int, key string, value int, addComma bool) Weaver

JSONFieldInt adds an indented JSON field with an integer value.

Example:

sw.JSONFieldInt(1, "age", 30, true) // adds '  "age": 30,\n'

func (*StringWeaver) JSONFieldInt8

func (sw *StringWeaver) JSONFieldInt8(level int, key string, value int8, addComma bool) Weaver

JSONFieldInt8 adds an indented JSON field with an int8 value.

Example:

sw.JSONFieldInt8(1, "age", 30, true) // adds '  "age": 30,\n'

func (*StringWeaver) JSONFieldInt16

func (sw *StringWeaver) JSONFieldInt16(level int, key string, value int16, addComma bool) Weaver

JSONFieldInt16 adds an indented JSON field with an int16 value.

Example:

sw.JSONFieldInt16(1, "age", 30, true) // adds '  "age": 30,\n'

func (*StringWeaver) JSONFieldInt32

func (sw *StringWeaver) JSONFieldInt32(level int, key string, value int32, addComma bool) Weaver

JSONFieldInt32 adds an indented JSON field with an int32 value.

Example:

sw.JSONFieldInt32(1, "age", 30, true) // adds '  "age": 30,\n'

func (*StringWeaver) JSONFieldInt64

func (sw *StringWeaver) JSONFieldInt64(level int, key string, value int64, addComma bool) Weaver

JSONFieldInt64 adds an indented JSON field with an int64 value.

Example:

sw.JSONFieldInt64(1, "age", 30, true) // adds '  "age": 30,\n'

func (*StringWeaver) JSONFieldString

func (sw *StringWeaver) JSONFieldString(level int, key, value string, addComma bool) Weaver

JSONFieldString adds an indented JSON field (key: value) with optional comma and newline. The value is properly JSON-encoded (RFC 8259).

Example:

sw.JSONFieldString(1, "name", `"John"`, true) // adds '  "name": "John",\n'

func (*StringWeaver) JSONFieldUint

func (sw *StringWeaver) JSONFieldUint(level int, key string, value uint, addComma bool) Weaver

JSONFieldUint adds an indented JSON field with a uint value.

Example:

sw.JSONFieldUint(1, "age", 30, true) // adds '  "age": 30,\n'

func (*StringWeaver) JSONFieldUint8

func (sw *StringWeaver) JSONFieldUint8(level int, key string, value uint8, addComma bool) Weaver

JSONFieldUint8 adds an indented JSON field with a uint8 value.

Example:

sw.JSONFieldUint8(1, "age", 30, true) // adds '  "age": 30,\n'

func (*StringWeaver) JSONFieldUint16

func (sw *StringWeaver) JSONFieldUint16(level int, key string, value uint16, addComma bool) Weaver

JSONFieldUint16 adds an indented JSON field with a uint16 value.

Example:

sw.JSONFieldUint16(1, "age", 30, true) // adds '  "age": 30,\n'

func (*StringWeaver) JSONFieldUint32

func (sw *StringWeaver) JSONFieldUint32(level int, key string, value uint32, addComma bool) Weaver

JSONFieldUint32 adds an indented JSON field with a uint32 value.

Example:

sw.JSONFieldUint32(1, "age", 30, true) // adds '  "age": 30,\n'

func (*StringWeaver) JSONFieldUint64

func (sw *StringWeaver) JSONFieldUint64(level int, key string, value uint64, addComma bool) Weaver

JSONFieldUint64 adds an indented JSON field with a uint64 value.

Example:

sw.JSONFieldUint64(1, "age", 30, true) // adds '  "age": 30,\n'

func (*StringWeaver) JSONKey

func (sw *StringWeaver) JSONKey(key string) Weaver

JSONKey adds a quoted key followed by a colon and space.

Example:

sw.JSONKey("name") // adds "name":

func (*StringWeaver) JSONKeyBool

func (sw *StringWeaver) JSONKeyBool(key string, value bool) Weaver

JSONKeyBool adds a key-value pair where the value is a boolean.

Example:

sw.JSONKeyBool("active", true) // adds "active": true

func (*StringWeaver) JSONKeyFloat

func (sw *StringWeaver) JSONKeyFloat(key string, value float64) Weaver

JSONKeyFloat adds a key-value pair where the value is a float.

Example:

sw.JSONKeyFloat("price", 19.99) // adds "price": 19.99

func (*StringWeaver) JSONKeyInt

func (sw *StringWeaver) JSONKeyInt(key string, value int) Weaver

JSONKeyInt adds a key-value pair where the value is an integer.

Example:

sw.JSONKeyInt("age", 30) // adds "age": 30

func (*StringWeaver) JSONKeyString

func (sw *StringWeaver) JSONKeyString(key, value string) Weaver

JSONKeyString adds a key-value pair where the value is a string. The value is properly JSON-encoded (RFC 8259).

Example:

sw.JSONKeyString("name", "John") // adds "name": "John"

func (*StringWeaver) JSONObjectEnd

func (sw *StringWeaver) JSONObjectEnd() Weaver

JSONObjectEnd adds a closing curly brace for a JSON object.

Example:

sw.JSONObjectEnd() // adds "}"

func (*StringWeaver) JSONObjectStart

func (sw *StringWeaver) JSONObjectStart() Weaver

JSONObjectStart adds an opening curly brace for a JSON object.

Example:

sw.JSONObjectStart() // adds "{"

func (*StringWeaver) JSONString

func (sw *StringWeaver) JSONString(s string) Weaver

JSONString adds a quoted and escaped string value. The output is proper JSON (RFC 8259) — control characters are encoded as \uXXXX sequences, not Go-specific escape sequences.

Example:

sw.JSONString("hello") // adds "hello"

func (*StringWeaver) Join

func (sw *StringWeaver) Join(sep string, elements ...string) Weaver

Join adds strings with a separator and returns the builder.

Example:

sw.Join(", ", "Apple", "Banana", "Cherry")

func (*StringWeaver) Len

func (sw *StringWeaver) Len() int

Len returns the current length of the built string.

Example:

length := sw.Len()

func (*StringWeaver) Line

func (sw *StringWeaver) Line(s string) Weaver

Line adds a string followed by a newline and returns the builder.

Example:

sw.Line("First Line").Line("Second Line")

func (*StringWeaver) LineF

func (sw *StringWeaver) LineF(format string, args ...any) Weaver

LineF adds a formatted string followed by a newline and returns the builder.

Example:

sw.LineF("User ID: %d", 123)

func (*StringWeaver) NewLine

func (sw *StringWeaver) NewLine() Weaver

NewLine adds a single newline character and returns the builder.

Example:

sw.Append("Line 1").NewLine().Append("Line 2")

func (*StringWeaver) NewLines

func (sw *StringWeaver) NewLines(n int) Weaver

NewLines adds n newline characters and returns the builder.

Example:

sw.Append("Paragraph 1").NewLines(2).Append("Paragraph 2")

func (*StringWeaver) Parenthesize

func (sw *StringWeaver) Parenthesize(s string) Weaver

Parenthesize wraps text in parentheses.

Example:

sw.Parenthesize("expression") // adds (expression)

func (*StringWeaver) Pipe added in v0.1.35

func (sw *StringWeaver) Pipe() Weaver

Pipe adds a pipe character and returns the builder.

Example:

sw.Append("Column1").Pipe().Append("Column2")

func (*StringWeaver) Pipes added in v0.1.35

func (sw *StringWeaver) Pipes(n int) Weaver

Pipes adds n pipe characters and returns the builder.

Example:

sw.Pipes(3) // adds "|||"

func (*StringWeaver) Quote

func (sw *StringWeaver) Quote(s string) Weaver

Quote wraps text in double quotes.

Example:

sw.Quote("quoted string") // adds "quoted string"

func (*StringWeaver) Repeat

func (sw *StringWeaver) Repeat(s string, n int) Weaver

Repeat adds a string n times and returns the builder.

Example:

sw.Repeat("-", 10) // adds "----------"

func (*StringWeaver) Reset

func (sw *StringWeaver) Reset() Weaver

Reset clears the builder and returns it for reuse.

Example:

sw.Reset().Append("Fresh start")

func (*StringWeaver) Semicolon

func (sw *StringWeaver) Semicolon() Weaver

Semicolon adds a semicolon to the builder.

Example:

sw.Append("x = 1").Semicolon()

func (*StringWeaver) SingleQuote

func (sw *StringWeaver) SingleQuote(s string) Weaver

SingleQuote wraps text in single quotes.

Example:

sw.SingleQuote("char") // adds 'char'

func (*StringWeaver) Space

func (sw *StringWeaver) Space() Weaver

Space adds a single space character and returns the builder.

Example:

sw.Append("Hello").Space().Append("World")

func (*StringWeaver) Spaces

func (sw *StringWeaver) Spaces(n int) Weaver

Spaces adds n space characters and returns the builder.

Example:

sw.Append("Key:").Spaces(4).Append("Value")

func (*StringWeaver) StartBrace

func (sw *StringWeaver) StartBrace() Weaver

StartBrace adds an opening brace.

Example:

sw.StartBrace() // adds '{'

func (*StringWeaver) StartBracket

func (sw *StringWeaver) StartBracket() Weaver

StartBracket adds an opening bracket.

Example:

sw.StartBracket() // adds '['

func (*StringWeaver) StartParenthesize

func (sw *StringWeaver) StartParenthesize() Weaver

StartParenthesize adds an opening parenthesis.

Example:

sw.StartParenthesize() // adds '('

func (*StringWeaver) Strikethrough added in v0.1.35

func (sw *StringWeaver) Strikethrough(s string) Weaver

Strikethrough adds a string wrapped in double tildes for strikethrough representation.

Example:

sw.Strikethrough("Obsolete") // adds "~~Obsolete~~"

func (*StringWeaver) String

func (sw *StringWeaver) String() string

String returns the final built string.

Example:

result := sw.String()

func (*StringWeaver) Tab

func (sw *StringWeaver) Tab() Weaver

Tab adds a single tab character and returns the builder.

Example:

sw.Append("Column1").Tab().Append("Column2")

func (*StringWeaver) Tabs

func (sw *StringWeaver) Tabs(n int) Weaver

Tabs adds n tab characters and returns the builder.

Example:

sw.Tabs(2).Append("Indented text")

func (*StringWeaver) Underline added in v0.1.35

func (sw *StringWeaver) Underline(s string) Weaver

Underline adds a string wrapped in <u> tags for underline representation.

Example:

sw.Underline("Highlighted") // adds "<u>Highlighted</u>"

func (*StringWeaver) Underscore added in v0.1.35

func (sw *StringWeaver) Underscore() Weaver

Underscore adds a single underscore character and returns the builder.

Example:

sw.Append("variable").Underscore().Append("name")

func (*StringWeaver) Underscores added in v0.1.35

func (sw *StringWeaver) Underscores(n int) Weaver

Underscores adds n underscore characters and returns the builder.

Example:

sw.Underscores(4) // adds "____"

func (*StringWeaver) Unless

func (sw *StringWeaver) Unless(condition bool, fn func(*StringWeaver)) *StringWeaver

Unless executes a function on the builder if the condition is false.

Example:

sw.Unless(isMinified, func(s *StringWeaver) {
    s.NewLine().Indent(1, "")
})

func (*StringWeaver) UnlessCast

func (sw *StringWeaver) UnlessCast(condition bool, fn func(w Weaver)) Weaver

UnlessCast executes a function with access to the current state without modification.

Example:

sw.UnlessCast(isHeader, func(w Weaver) {
	w.Append("Header: ")
})

func (*StringWeaver) When

func (sw *StringWeaver) When(condition bool, fn func(*StringWeaver)) *StringWeaver

When executes a function on the builder if the condition is true.

Example:

sw.When(isHeader, func(s *StringWeaver) {
    s.Append("# ").Line(title)
})

func (*StringWeaver) WhenCast

func (sw *StringWeaver) WhenCast(condition bool, fn func(w Weaver)) Weaver

WhenCast executes a function with access to the current state without modification.

Example:

sw.WhenCast(isHeader, func(w Weaver) {
	w.Append("Header: ")
})

func (*StringWeaver) Wrap

func (sw *StringWeaver) Wrap(prefix, text, suffix string) Weaver

Wrap wraps text with a prefix and suffix.

Example:

sw.Wrap("**", "Bold text", "**")

type Weaver

type Weaver interface {

	// Bytes returns the current content as a byte slice.
	Bytes() []byte

	// Append adds a string and returns the builder for chaining.
	Append(s string) Weaver

	// AppendF adds a formatted string (printf-style) and returns the builder.
	AppendF(format string, args ...any) Weaver

	// AppendByte adds a single byte and returns the builder.
	AppendByte(b byte) Weaver

	// AppendRune adds a single rune and returns the builder.
	AppendRune(r rune) Weaver

	// AppendBytes adds a byte slice and returns the builder.
	AppendBytes(b []byte) Weaver

	// AppendInt adds an integer and returns the builder.
	AppendInt(i int) Weaver

	// AppendInt8 adds an int8 and returns the builder.
	AppendInt8(i int8) Weaver

	// AppendInt16 adds an int16 and returns the builder.
	AppendInt16(i int16) Weaver

	// AppendInt32 adds an int32 and returns the builder.
	AppendInt32(i int32) Weaver

	// AppendInt64 adds an int64 and returns the builder.
	AppendInt64(i int64) Weaver

	// AppendUint adds a uint and returns the builder.
	AppendUint(i uint) Weaver

	// AppendUint8 adds a uint8 and returns the builder.
	AppendUint8(i uint8) Weaver

	// AppendUint16 adds a uint16 and returns the builder.
	AppendUint16(i uint16) Weaver

	// AppendUint32 adds a uint32 and returns the builder.
	AppendUint32(i uint32) Weaver

	// AppendUint64 adds a uint64 and returns the builder.
	AppendUint64(i uint64) Weaver

	// AppendUintptr adds a uintptr and returns the builder.
	AppendUintptr(i uintptr) Weaver

	// AppendFloat32 adds a float32 and returns the builder.
	AppendFloat32(f float32) Weaver

	// AppendFloat64 adds a float64 and returns the builder.
	AppendFloat64(f float64) Weaver

	// AppendBool adds a boolean value and returns the builder.
	AppendBool(b bool) Weaver

	// Space adds a single space character and returns the builder.
	Space() Weaver

	// Spaces adds n space characters and returns the builder.
	Spaces(n int) Weaver

	// Tab adds a single tab character and returns the builder.
	Tab() Weaver

	// Tabs adds n tab characters and returns the builder.
	Tabs(n int) Weaver

	// NewLine adds a single newline character and returns the builder.
	NewLine() Weaver

	// NewLines adds n newline characters and returns the builder.
	NewLines(n int) Weaver

	// Line adds a string followed by a newline and returns the builder.
	Line(s string) Weaver

	// LineF adds a formatted string followed by a newline and returns the builder.
	LineF(format string, args ...any) Weaver

	// Repeat adds a string n times and returns the builder.
	Repeat(s string, n int) Weaver

	// Join adds strings with a separator and returns the builder.
	Join(sep string, elements ...string) Weaver

	// AppendIf conditionally adds a string if the condition is true.
	AppendIf(condition bool, s string) Weaver

	// AppendIfF conditionally adds a formatted string if the condition is true.
	AppendIfF(condition bool, format string, args ...any) Weaver

	// Indent adds indentation (2 spaces per level) before appending text.
	Indent(level int, s string) Weaver

	// IndentLine adds indentation (2 spaces per level) before text and ends with a newline.
	IndentLine(level int, s string) Weaver

	// Wrap wraps text with a prefix and suffix.
	Wrap(prefix, text, suffix string) Weaver

	// Quote wraps text in double quotes.
	Quote(s string) Weaver

	// SingleQuote wraps text in single quotes.
	SingleQuote(s string) Weaver

	// Parenthesize wraps text in parentheses.
	Parenthesize(s string) Weaver

	// Bracket wraps text in square brackets.
	Bracket(s string) Weaver

	// Brace wraps text in curly braces.
	Brace(s string) Weaver

	// Comma adds a comma to the builder.
	Comma() Weaver

	// Dot adds a period to the builder.
	Dot() Weaver

	// Colon adds a colon to the builder.
	Colon() Weaver

	// Semicolon adds a semicolon to the builder.
	Semicolon() Weaver

	// Equals adds an equals sign to the builder.
	Equals() Weaver

	// Arrow adds an arrow (->) to the builder.
	Arrow() Weaver

	// FatArrow adds a fat arrow (=>) to the builder.
	FatArrow() Weaver

	// Grow grows the builder's capacity by n bytes.
	Grow(n int) Weaver

	// Reset clears the builder and returns it for reuse.
	Reset() Weaver

	// Len returns the current length of the built string.
	Len() int

	// Cap returns the current capacity of the builder.
	Cap() int

	// String returns the final built string.
	String() string

	// Build is an alias for String() for fluent API consistency.
	Build() string

	// Clone creates an independent copy of the current builder state.
	Clone() Weaver

	// Inspect executes a function with access to the current state without modification.
	Inspect(fn func(current string)) Weaver

	// Builder returns the underlying strings.Builder for advanced operations.
	Builder() *strings.Builder

	// IndentF adds indentation (2 spaces per level) before appending a formatted string.
	IndentF(level int, format string, args ...any) Weaver

	// IndentLineF adds indentation (2 spaces per level) before a formatted string and ends with a newline.
	IndentLineF(level int, format string, args ...any) Weaver

	// JSONObjectStart adds an opening curly brace for a JSON object.
	JSONObjectStart() Weaver

	// JSONObjectEnd adds a closing curly brace for a JSON object.
	JSONObjectEnd() Weaver

	// JSONArrayStart adds an opening square bracket for a JSON array.
	JSONArrayStart() Weaver

	// JSONArrayEnd adds a closing square bracket for a JSON array.
	JSONArrayEnd() Weaver

	// JSONString adds a quoted and escaped string value.
	JSONString(s string) Weaver

	// JSONKey adds a quoted key followed by a colon and space.
	JSONKey(key string) Weaver

	// JSONKeyString adds a key-value pair where the value is a string.
	JSONKeyString(key, value string) Weaver

	// JSONKeyInt adds a key-value pair where the value is an integer.
	JSONKeyInt(key string, value int) Weaver

	// JSONKeyBool adds a key-value pair where the value is a boolean.
	JSONKeyBool(key string, value bool) Weaver

	// JSONKeyFloat adds a key-value pair where the value is a float.
	JSONKeyFloat(key string, value float64) Weaver

	// JSONFieldString adds an indented JSON field (key: value) with optional comma and newline.
	JSONFieldString(level int, key, value string, addComma bool) Weaver

	// JSONFieldInt adds an indented JSON field with an integer value.
	JSONFieldInt(level int, key string, value int, addComma bool) Weaver

	// JSONFieldInt8 adds an indented JSON field with an int8 value.
	JSONFieldInt8(level int, key string, value int8, addComma bool) Weaver

	// JSONFieldInt16 adds an indented JSON field with an int16 value.
	JSONFieldInt16(level int, key string, value int16, addComma bool) Weaver

	// JSONFieldInt32 adds an indented JSON field with an int32 value.
	JSONFieldInt32(level int, key string, value int32, addComma bool) Weaver

	// JSONFieldInt64 adds an indented JSON field with an int64 value.
	JSONFieldInt64(level int, key string, value int64, addComma bool) Weaver

	// JSONFieldUint adds an indented JSON field with a uint value.
	JSONFieldUint(level int, key string, value uint, addComma bool) Weaver

	// JSONFieldUint8 adds an indented JSON field with a uint8 value.
	JSONFieldUint8(level int, key string, value uint8, addComma bool) Weaver

	// JSONFieldUint16 adds an indented JSON field with a uint16 value.
	JSONFieldUint16(level int, key string, value uint16, addComma bool) Weaver

	// JSONFieldUint32 adds an indented JSON field with a uint32 value.
	JSONFieldUint32(level int, key string, value uint32, addComma bool) Weaver

	// JSONFieldUint64 adds an indented JSON field with a uint64 value.
	JSONFieldUint64(level int, key string, value uint64, addComma bool) Weaver

	// JSONFieldFloat32 adds an indented JSON field with a float32 value.
	JSONFieldFloat32(level int, key string, value float32, addComma bool) Weaver

	// JSONFieldFloat64 adds an indented JSON field with a float64 value.
	JSONFieldFloat64(level int, key string, value float64, addComma bool) Weaver

	// JSONFieldBool adds an indented JSON field with a bool value.
	JSONFieldBool(level int, key string, value bool, addComma bool) Weaver

	// CommaIfNotLast adds a comma if the index is not the last item.
	CommaIfNotLast(index, total int) Weaver

	// WhenCast executes a function with access to the current state without modification.
	WhenCast(condition bool, fn func(w Weaver)) Weaver

	// UnlessCast executes a function with access to the current state without modification.
	UnlessCast(condition bool, fn func(w Weaver)) Weaver

	// EachCast executes a function for each item in the slice.
	EachCast(items []string, fn func(w Weaver, item string)) Weaver

	// JSONFieldArrayStart adds an indented JSON array start.
	//
	// Example:
	//
	//	sw.JSONFieldArrayStart(1, "items") // adds '  "items": ['
	JSONFieldArrayStart(level int, key string) Weaver

	// JSONFieldArrayEnd adds an indented JSON array end.
	//
	// Example:
	//
	//	sw.JSONFieldArrayEnd(1) // adds '  ]'
	JSONFieldArrayEnd(level int) Weaver

	// StartParenthesize adds an opening parenthesis.
	//
	// Example:
	//
	//	sw.StartParenthesize() // adds '('
	StartParenthesize() Weaver

	// EndParenthesize adds a closing parenthesis.
	//
	// Example:
	//
	//	sw.EndParenthesize() // adds ')'
	EndParenthesize() Weaver

	// StartBracket adds an opening bracket.
	//
	// Example:
	//
	//	sw.StartBracket() // adds '['
	StartBracket() Weaver

	// EndBracket adds a closing bracket.
	//
	// Example:
	//
	//	sw.EndBracket() // adds ']'
	EndBracket() Weaver

	// StartBrace adds an opening curly brace.
	//
	// Example:
	//
	//	sw.StartBrace() // adds '{'
	StartBrace() Weaver

	// EndBrace adds a closing curly brace.
	//
	// Example:
	//
	//	sw.EndBrace() // adds '}'
	EndBrace() Weaver

	// IndentOnly adds indentation (2 spaces per level) without appending text.
	//
	// Example:
	//
	//	sw.IndentOnly(1) // adds '  '
	IndentOnly(level int) Weaver

	// IndentOnlyLine adds indentation (2 spaces per level) followed by a newline.
	//
	// Example:
	//
	//	sw.IndentOnlyLine(1) // adds '  \n'
	IndentOnlyLine(level int) Weaver

	// CarriageReturn adds a carriage return character and returns the builder.
	//
	// Example:
	//
	//	sw.CarriageReturn() // adds '\r'
	CarriageReturn() Weaver

	// Pipe adds a pipe character and returns the builder.
	//
	// Example:
	//
	//	sw.Pipe() // adds '|'
	Pipe() Weaver

	// Pipes adds n pipe characters and returns the builder.
	//
	// Example:
	//
	//	sw.Pipes(3) // adds '|||'
	Pipes(n int) Weaver

	// Dash adds a '-' character and returns the builder.
	//
	// Example:
	//
	//	sw.Dash() // adds '-'
	Dash() Weaver

	// Dashes adds n '-' characters and returns the builder.
	//
	// Example:
	//
	//	sw.Dashes(3) // adds '---'
	Dashes(n int) Weaver

	// Underscore adds a '_' character and returns the builder.
	//
	// Example:
	//
	//	sw.Underscore() // adds '_'
	Underscore() Weaver

	// Underscores adds n '_' characters and returns the builder.
	//
	// Example:
	//
	//	sw.Underscores(3) // adds '___'
	Underscores(n int) Weaver

	// CodeBlock adds a code block with optional language specifier.
	//
	// Example:
	//
	// 	sw.CodeBlock("go", "fmt.Println(\"Hello, World!\")") // adds '“`go\nfmt.Println("Hello, World!")\n“`'
	CodeBlock(language string, s Weaver) Weaver

	// IsEmpty checks if the builder is empty (length is zero).
	//
	// Example:
	//
	// 	if sw.IsEmpty() {
	// 		fmt.Println("The builder is empty.")
	// 	}
	IsEmpty() bool

	// IsNotEmpty checks if the builder is not empty (length is greater than zero).
	//
	// Example:
	//
	// 	if sw.IsNotEmpty() {
	// 		fmt.Println("The builder has content.")
	// 	}
	IsNotEmpty() bool

	// InlineCode adds inline code formatting to the given string and returns the builder.
	//
	// Example:
	//
	//	sw.InlineCode("inline code") // adds '`inline code`'
	InlineCode(s string) Weaver

	// InlineCodeF adds formatted inline code (printf-style) to the builder.
	//
	// Example:
	//
	//	sw.InlineCodeF("inline %s", "code") // adds '`inline code`'
	InlineCodeF(format string, args ...any) Weaver

	// Bold adds bold formatting to the given string and returns the builder.
	//
	// Example:
	//
	//	sw.Bold("important") // adds '**important**'
	Bold(s string) Weaver

	// Italic adds italic formatting to the given string and returns the builder.
	//
	// Example:
	//
	//	sw.Italic("emphasis") // adds '*emphasis*'
	Italic(s string) Weaver

	// Strikethrough adds strikethrough formatting to the given string and returns the builder.
	//
	// Example:
	//
	//	sw.Strikethrough("obsolete") // adds '~~obsolete~~'
	Strikethrough(s string) Weaver

	// Underline adds underline formatting to the given string and returns the builder.
	//
	// Example:
	//
	//	sw.Underline("highlight") // adds '<u>highlight</u>'
	Underline(s string) Weaver
}

Weaver defines the common interface for fluent string builder operations. Both StringWeaver (non-thread-safe, maximum performance) and SafeStringWeaver (thread-safe with mutex synchronization) implement this interface.

Use Weaver when you need polymorphism — for example, a function that accepts either a StringWeaver or a SafeStringWeaver as a parameter.

Methods that accept callback functions with concrete receiver types (When, Unless, Each) are not included in this interface because their function parameter types differ between StringWeaver and SafeStringWeaver. These methods are available only on the concrete types.

Example:

var w strchain.Weaver = strchain.New()
result := w.Append("Hello").Space().Append("World").Build()

var sw strchain.Weaver = strchain.NewSafe()
result = sw.Append("Hello").Space().Append("World").Build()

Jump to

Keyboard shortcuts

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