### Install ZaString Package Source: https://github.com/corentings/zastring/blob/main/README.md This command adds the ZaString NuGet package to your .NET project, making its functionalities available for use. ```bash dotnet add package ZaString ``` -------------------------------- ### Quick Start: Building Strings with ZaSpanStringBuilder Source: https://github.com/corentings/zastring/blob/main/README.md Demonstrates the basic usage of ZaSpanStringBuilder to create a string using a stack-allocated buffer and a fluent API. It shows appending various data types and accessing the result as a ReadOnlySpan without heap allocation. ```csharp using ZaString.Core; using ZaString.Extensions; // Create a stack-allocated buffer Span buffer = stackalloc char[100]; var builder = ZaSpanStringBuilder.Create(buffer); // Build strings with fluent API builder.Append("Hello, ") .Append("World!") .Append(" Number: ") .Append(42) .Append(" Pi: ") .Append(Math.PI, "F2"); // Access result as span (zero allocation) var result = builder.AsSpan(); Console.WriteLine(result); // "Hello, World! Number: 42 Pi: 3.14" ``` -------------------------------- ### Zero-Allocation String Interpolation with ZaString in C# Source: https://context7.com/corentings/zastring/llms.txt Demonstrates the use of ZaString's custom interpolated string handlers for zero-allocation string interpolation in C#. This allows developers to build strings using the familiar `$` syntax without incurring heap allocations, enhancing performance. The example also shows how to clear and reuse the builder. ```csharp using ZaString.Core; using ZaString.Extensions; Span buffer = stackalloc char[200]; var builder = ZaSpanStringBuilder.Create(buffer); var name = "Alice"; var age = 30; var balance = 1234.56; // Zero-allocation interpolated strings builder.Append($"User: {name}, Age: {age}, Balance: {balance:C}"); Console.WriteLine(builder.AsSpan().ToString()); // Output: "User: Alice, Age: 30, Balance: $1,234.56" // Clear and reuse buffer builder.Clear(); builder.AppendLine($"Transaction: {balance:F2}"); Console.WriteLine(builder.AsSpan().ToString()); // Output: "Transaction: 1234.56\n" ``` -------------------------------- ### Escape Helpers for Special Characters Source: https://github.com/corentings/zastring/blob/main/README.md Provides examples of using ZaString's built-in escape helpers for JSON, HTML, URL, and CSV encoding to safely include special characters within strings. ```csharp // JSON escaping builder.AppendJsonEscaped("Line1\nLine2\t\"Quote\""); // HTML escaping builder.AppendHtmlEscaped(""); // URL encoding builder.AppendUrlEncoded("Hello World!"); // CSV escaping builder.AppendCsvEscaped("Value,with,commas"); ``` -------------------------------- ### ZaString Buffer Manipulation Methods Source: https://context7.com/corentings/zastring/llms.txt Demonstrates methods for managing the builder's internal buffer, including clearing, resizing, and modifying content. It showcases `Append`, `Clear`, `RemoveLast`, `SetLength`, indexer access, and `EnsureEndsWith` for efficient string construction with zero allocations when using stack-allocated buffers. ```csharp using ZaString.Core; using ZaString.Extensions; Span buffer = stackalloc char[100]; var builder = ZaSpanStringBuilder.Create(buffer); // Build initial content builder.Append("Hello, World!"); Console.WriteLine($"Length: {builder.Length}"); // 13 // Clear buffer for reuse (zero allocation) builder.Clear(); Console.WriteLine($"After clear: {builder.Length}"); // 0 // Build new content in same buffer builder.Append("New content"); // Remove last N characters builder.RemoveLast(4); // Remove "tent" Console.WriteLine(builder.AsSpan().ToString()); // "New con" // Set exact length (truncate) builder.SetLength(3); Console.WriteLine(builder.AsSpan().ToString()); // "New" // Character indexer access builder.Append(" Test"); builder[0] = 'O'; // Change 'N' to 'O' Console.WriteLine(builder.AsSpan().ToString()); // "Oew Test" // EnsureEndsWith - only appends if not already present builder.EnsureEndsWith('!'); builder.EnsureEndsWith('!'); // Does nothing, already ends with '!' Console.WriteLine(builder.AsSpan().ToString()); // "Oew Test!" ``` -------------------------------- ### Build URL Paths with ZaString Source: https://context7.com/corentings/zastring/llms.txt Constructs URL paths with automatic separator handling using ZaSpanStringBuilder. It correctly manages slashes between segments and can append query parameters. This functionality requires ZaString.Core and ZaString.Extensions. ```csharp using ZaString.Core; using ZaString.Extensions; Span buffer = stackalloc char[200]; var builder = ZaSpanStringBuilder.Create(buffer); // Build URL path with automatic separator management builder.AppendPathSegment("api") .AppendPathSegment("/v1/") // Leading/trailing slashes handled .AppendPathSegment("users") .AppendPathSegment("123"); Console.WriteLine(builder.AsSpan().ToString()); // Output: api/v1/users/123 // Build complete URL with query parameters builder.Clear(); builder.Append("https://api.example.com") .AppendPathSegment("search") .AppendQueryParam("q", "search term", isFirst: true) .AppendQueryParam("page", "1") .AppendQueryParam("limit", "10"); Console.WriteLine(builder.AsSpan().ToString()); // Output: https://api.example.com/search?q=search%20term&page=1&limit=10 ``` -------------------------------- ### Use Pooled String Builder with ZaString Source: https://context7.com/corentings/zastring/llms.txt Creates a growable string builder with automatic buffer management using ZaPooledStringBuilder. This is ideal for scenarios requiring dynamic string construction and improves performance by reusing buffers from a pool. The ZaString.Core namespace is necessary. ```csharp using ZaString.Core; // Rent a pooled builder with initial capacity using var builder = ZaPooledStringBuilder.Rent(128); // Append operations (automatically grows if needed) builder.Append("This is a longer string that may grow ") .Append("beyond the initial capacity. ") .Append("The builder will automatically ") .Append("rent larger buffers from the pool as needed."); // Access as span or string Console.WriteLine(builder.AsSpan().ToString()); Console.WriteLine(builder.ToString()); // Buffer is automatically returned to pool when disposed ``` -------------------------------- ### URL Building with Path Segments and Query Parameters Source: https://github.com/corentings/zastring/blob/main/README.md Illustrates how to construct URLs using ZaString's `AppendPathSegment` and `AppendQueryParam` methods. This approach helps in building well-formed URLs programmatically. ```csharp builder.AppendPathSegment("api") .AppendPathSegment("v1") .AppendPathSegment("users") .AppendQueryParam("q", "search term", isFirst: true) .AppendQueryParam("page", "1"); // Result: "api/v1/users?q=search%20term&page=1" ``` -------------------------------- ### String Interpolation with ZaString Source: https://github.com/corentings/zastring/blob/main/README.md Illustrates how to use string interpolation with ZaString's builder by appending a formatted string literal. This integrates seamlessly with existing builder patterns. ```csharp var name = "Alice"; var age = 30; var pi = Math.PI; builder.Append($"User: {name}, Age: {age}, Pi: {pi:F2}"); ``` -------------------------------- ### Safe Appending with TryAppend in ZaString Source: https://context7.com/corentings/zastring/llms.txt Provides non-throwing variants for appending strings and formatted values to a string builder. `TryAppend` returns `false` if the buffer capacity is insufficient, preventing exceptions and allowing for graceful error handling. It's crucial when dealing with unpredictable input sizes or fixed-size buffers. ```csharp using ZaString.Core; using ZaString.Extensions; Span smallBuffer = stackalloc char[10]; var builder = ZaSpanStringBuilder.Create(smallBuffer); // TryAppend returns false when buffer is too small if (builder.TryAppend("Hello, World!")) { Console.WriteLine("Success"); } else { Console.WriteLine("Buffer too small"); // This will execute } // Check remaining space and try again Span bigBuffer = stackalloc char[100]; builder = ZaSpanStringBuilder.Create(bigBuffer); if (builder.TryAppend("Hello") && builder.TryAppend(", ") && builder.TryAppend("World!")) { Console.WriteLine(builder.AsSpan().ToString()); // "Hello, World!" } // TryAppend with formatted values if (builder.TryAppend(" Number: ") && builder.TryAppend(42, "N0")) { Console.WriteLine(builder.AsSpan().ToString()); // "Hello, World! Number: 42" } ``` -------------------------------- ### Number Formatting Options in ZaString Source: https://github.com/corentings/zastring/blob/main/README.md Shows various ways to format numbers using ZaString's `Append` method with standard .NET format strings, including currency, number with separators, and percentage formats. ```csharp builder.Append("Currency: ") .Append(1234.56, "C") // "$1,234.56" .Append(", Number: ") .Append(12345, "N0") // "12,345" .Append(", Percentage: ") .Append(0.85, "P2"); // "85.00%" ``` -------------------------------- ### Run Performance Benchmarks Source: https://github.com/corentings/zastring/blob/main/README.md Commands to execute the comprehensive test suite and performance benchmarks for ZaString. The benchmarks use BenchmarkDotNet 0.15.2 on .NET 8.0.19 environment to measure execution time and memory allocations across various string operations. ```bash # Run comprehensive test suite dotnet test # Run performance benchmarks cd tests/ZaString.Benchmarks dotnet run -c Release ``` -------------------------------- ### Safe Appending with TryAppend Methods Source: https://github.com/corentings/zastring/blob/main/README.md Demonstrates the use of `TryAppend` methods in ZaString, which provide a non-throwing way to append strings. These methods return `true` on success and `false` if the buffer is too small, allowing for graceful error handling. ```csharp Span smallBuffer = stackalloc char[10]; var builder = ZaSpanStringBuilder.Create(smallBuffer); if (builder.TryAppend("Hello, World!")) { Console.WriteLine("Successfully appended"); } else { Console.WriteLine("Buffer too small"); } ``` -------------------------------- ### Joining Collections with ZaString Source: https://context7.com/corentings/zastring/llms.txt Provides functionality to join elements of collections (like arrays) with a specified separator, similar to `string.Join()`. It supports custom formatting for numeric types and handles null elements gracefully by treating them as empty strings. This method leverages `ZaSpanStringBuilder` for efficient in-place string construction. ```csharp using ZaString.Core; using ZaString.Extensions; Span buffer = stackalloc char[200]; var builder = ZaSpanStringBuilder.Create(buffer); // Join string array (null treated as empty) string[] fruits = { "apple", "banana", null, "cherry" }; builder.AppendJoin(", ".AsSpan(), fruits); Console.WriteLine(builder.AsSpan().ToString()); // Output: "apple, banana, , cherry" // Join numeric array with formatting builder.Clear(); double[] prices = { 1.5, 2.75, 3.99 }; builder.Append("Prices: ") .AppendJoin(', '.AsSpan(), prices, format: "F2"); Console.WriteLine(builder.AsSpan().ToString()); // Output: "Prices: 1.50, 2.75, 3.99" ``` -------------------------------- ### Basic String Building with ZaSpanStringBuilder Source: https://github.com/corentings/zastring/blob/main/README.md Demonstrates traditional StringBuilder approach versus ZaSpanStringBuilder using stack-allocated buffers. The ZaString approach eliminates memory allocations while improving performance by approximately 21% (115.2 ns vs 146.1 ns). Uses fluent API for method chaining and provides direct Span access without allocation. ```csharp // Traditional approach - 146.1 ns, 480 B allocated var sb = new StringBuilder(); sb.Append("Name: ").Append("John").Append(", Age: ").Append(25); var result = sb.ToString(); // ZaString approach - 115.2 ns, 0 B allocated Span buffer = stackalloc char[50]; var builder = ZaSpanStringBuilder.Create(buffer); builder.Append("Name: ").Append("John").Append(", Age: ").Append(25); var result = builder.AsSpan(); // Zero allocation ``` -------------------------------- ### ZaString String and UTF-8 Conversions Source: https://context7.com/corentings/zastring/llms.txt Explains how to convert the content of the `ZaSpanStringBuilder` into various formats, including `ReadOnlySpan`, `string`, UTF-8 encoded byte arrays, and raw byte representations. It highlights methods like `AsSpan`, `ToString`, `ToUtf8Array`, `TryCopyToUtf8`, and `AsRawBytes` for different allocation strategies. ```csharp using System.Text; using ZaString.Core; using ZaString.Extensions; Span buffer = stackalloc char[100]; var builder = ZaSpanStringBuilder.Create(buffer); builder.Append("Hello, World!"); // As ReadOnlySpan (zero allocation) ReadOnlySpan span = builder.AsSpan(); // As string (allocates) string str = builder.ToString(); // As UTF-8 bytes (allocates array) byte[] utf8Array = builder.ToUtf8Array(); Console.WriteLine($"UTF-8 bytes: {utf8Array.Length}"); // Try copy to UTF-8 buffer (zero allocation) Span utf8Buffer = stackalloc byte[100]; if (builder.TryCopyToUtf8(utf8Buffer, out int bytesWritten)) { Console.WriteLine($"UTF-8 copied: {bytesWritten} bytes"); Console.WriteLine(Encoding.UTF8.GetString(utf8Buffer[..bytesWritten])); } // As raw UTF-16 bytes (zero allocation view) ReadOnlySpan rawBytes = builder.AsRawBytes(); Console.WriteLine($"Raw UTF-16 bytes: {rawBytes.Length}"); // To byte array (allocates) byte[] byteArray = builder.ToByteArray(); ``` -------------------------------- ### Append Numbers with Formatting using ZaString in C# Source: https://context7.com/corentings/zastring/llms.txt Illustrates formatting and appending numeric types to a ZaSpanStringBuilder using standard .NET format strings. It covers currency, number, percentage, and fixed-point formatting, including culture-specific formatting for internationalization. This enables precise control over numeric output without heap allocations. ```csharp using System.Globalization; using ZaString.Core; using ZaString.Extensions; Span buffer = stackalloc char[150]; var builder = ZaSpanStringBuilder.Create(buffer); // Standard numeric formatting (uses InvariantCulture by default) builder.Append("Currency: ") .Append(1234.56, "C") // "$1,234.56" .Append(", Number: ") .Append(12345, "N0") // "12,345" .Append(", Percentage: ") .Append(0.85, "P2") // "85.00%" .Append(", Fixed: ") .Append(Math.PI, "F2"); // "3.14" Console.WriteLine(builder.AsSpan().ToString()); // Culture-specific formatting Span frenchBuffer = stackalloc char[100]; var frenchBuilder = ZaSpanStringBuilder.Create(frenchBuffer); var frCulture = new CultureInfo("fr-FR"); frenchBuilder.Append("Prix: ") .Append(1234.56, "C", frCulture); // "Prix: 1 234,56 €" Console.WriteLine(frenchBuilder.AsSpan().ToString()); ``` -------------------------------- ### ZaPooledStringBuilder for Heap-Allocated Strings Source: https://github.com/corentings/zastring/blob/main/README.md Shows how to use ZaPooledStringBuilder for scenarios requiring heap allocation. The `Rent` method allocates a buffer, and the `ToString` method retrieves the string. The buffer is automatically returned to the pool upon disposal. ```csharp using var builder = ZaPooledStringBuilder.Rent(128); builder.Append("Pooled string building") .Append(" with automatic cleanup"); var result = builder.ToString(); // Buffer automatically returned to pool when disposed ``` -------------------------------- ### Create Zero-Allocation Stack-Based String Builder in C# Source: https://context7.com/corentings/zastring/llms.txt Demonstrates how to create and use ZaSpanStringBuilder for zero-allocation string building on the stack. It shows appending various data types and accessing the result as a ReadOnlySpan. This method is ideal for performance-critical scenarios where memory allocations must be avoided. ```csharp using ZaString.Core; using ZaString.Extensions; // Create a stack-allocated buffer and builder Span buffer = stackalloc char[100]; var builder = ZaSpanStringBuilder.Create(buffer); // Build string with fluent API builder.Append("Hello, ") .Append("World!") .Append(" Number: ") .Append(42); // Access result as ReadOnlySpan (zero allocation) ReadOnlySpan result = builder.AsSpan(); Console.WriteLine(result.ToString()); // "Hello, World! Number: 42" // Get length and capacity information Console.WriteLine($"Length: {builder.Length}"); // Length: 28 Console.WriteLine($"Capacity: {builder.Capacity}"); // Capacity: 100 Console.WriteLine($"Remaining: {builder.RemainingSpan.Length}"); // Remaining: 72 ``` -------------------------------- ### ZaString Unsafe Pointer Operations Source: https://context7.com/corentings/zastring/llms.txt Details how to use unsafe pointer operations with `ZaSpanStringBuilder` for direct memory access and interop with native code. It shows creating a builder from a pointer, obtaining raw character and byte pointers, and generating null-terminated UTF-8 output using `GetCharPointer`, `GetBytePointer`, and `TryToUtf8NullTerminated`. ```csharp using ZaString.Core; using ZaString.Extensions; unsafe { // Create builder from pointer char* ptr = stackalloc char[100]; var builder = ZaSpanStringBuilder.Create(ptr, 100); builder.Append("Hello from pointer!"); // Get pointer to written content char* charPtr = builder.GetCharPointer(); byte* bytePtr = builder.GetBytePointer(); Console.WriteLine($"Char pointer: {(IntPtr)charPtr}"); Console.WriteLine($"Byte pointer: {(IntPtr)bytePtr}"); // UTF-8 null-terminated output for C interop byte* utf8Buffer = stackalloc byte[200]; if (builder.TryToUtf8NullTerminated(utf8Buffer, 200, out int bytesWritten)) { Console.WriteLine($"UTF-8 null-terminated: {bytesWritten} bytes"); } } ``` -------------------------------- ### ZaString Composite String Formatting Source: https://context7.com/corentings/zastring/llms.txt Illustrates how to use `AppendFormat` with a `ZaSpanStringBuilder` to achieve zero-allocation string formatting similar to `string.Format`. It covers standard composite formatting and culture-specific formatting using `CultureInfo`. ```csharp using System.Globalization; using ZaString.Core; using ZaString.Extensions; Span buffer = stackalloc char[200]; var builder = ZaSpanStringBuilder.Create(buffer); var name = "Alice"; var age = 30; var balance = 1234.56; // AppendFormat with composite formatting builder.AppendFormat("User: {0}, Age: {1}, Balance: {2:C}", name, age, balance); Console.WriteLine(builder.AsSpan().ToString()); // Output: User: Alice, Age: 30, Balance: $1,234.56 // With culture-specific formatting builder.Clear(); var fr = new CultureInfo("fr-FR"); builder.AppendFormat(fr, "Utilisateur: {0}, Âge: {1}, Solde: {2:C}", name, age, balance); Console.WriteLine(builder.AsSpan().ToString()); // Output: Utilisateur: Alice, Âge: 30, Solde: 1 234,56 € ``` -------------------------------- ### Culture-Specific Number Formatting Source: https://github.com/corentings/zastring/blob/main/README.md Demonstrates how to apply culture-specific formatting to numbers using ZaString by providing a `CultureInfo` object to the `Append` method. ```csharp var fr = new CultureInfo("fr-FR"); builder.Append(1234.56, "C", fr); // "1 234,56 €" ``` -------------------------------- ### URL Percent Encode Strings with ZaString Source: https://context7.com/corentings/zastring/llms.txt Encodes strings for safe use in URLs using percent-encoding with ZaSpanStringBuilder. It handles special characters by replacing them with their percent-encoded equivalents. The library ZaString.Core and ZaString.Extensions are required. Includes a safe variant for encoding. ```csharp using ZaString.Core; using ZaString.Extensions; Span buffer = stackalloc char[200]; var builder = ZaSpanStringBuilder.Create(buffer); string searchQuery = "Hello World!"; string tag = "c#"; // URL encode strings builder.Append("search=") .AppendUrlEncoded(searchQuery) .Append("&tag=") .AppendUrlEncoded(tag); Console.WriteLine(builder.AsSpan().ToString()); // Output: search=Hello%20World%21&tag=c%23 // Safe variant builder.Clear(); if (builder.TryAppendUrlEncoded(searchQuery)) { Console.WriteLine($"Encoded: {builder.AsSpan().ToString()}"); } ``` -------------------------------- ### ZaSpanStringBuilder Core Component Usage Source: https://github.com/corentings/zastring/blob/main/README.md Illustrates the core functionality of ZaSpanStringBuilder, showing how to create a builder with a character span and append various data types. The resulting string can be accessed as a ReadOnlySpan. ```csharp Span buffer = stackalloc char[64]; var builder = ZaSpanStringBuilder.Create(buffer); builder.Append("User: ") .Append("John Doe") .Append(", Age: ") .Append(25) .Append(", Active: ") .Append(true); // Access as ReadOnlySpan (zero allocation) var userInfo = builder.AsSpan(); ``` -------------------------------- ### Repeating Characters with ZaString Source: https://context7.com/corentings/zastring/llms.txt Efficiently appends a specified character multiple times to a string builder. Includes both a standard `AppendRepeat` and a safe `TryAppendRepeat` variant that checks for buffer capacity. This is useful for creating separators, padding, or other repetitive string patterns. ```csharp using ZaString.Core; using ZaString.Extensions; Span buffer = stackalloc char[100]; var builder = ZaSpanStringBuilder.Create(buffer); // Append separator lines builder.AppendRepeat('-', 20) .AppendLine() .Append("Title") .AppendLine() .AppendRepeat('-', 20); Console.WriteLine(builder.AsSpan().ToString()); // Output: // -------------------- // Title // -------------------- // Safe variant with TryAppendRepeat builder.Clear(); if (builder.TryAppendRepeat('*', 50)) { Console.WriteLine("Appended"); } ``` -------------------------------- ### Append DateTime with Formatting using ZaString in C# Source: https://context7.com/corentings/zastring/llms.txt Shows how to format and append DateTime values to a ZaSpanStringBuilder using various standard and custom format strings. This allows for flexible and efficient representation of date and time information directly on the stack, suitable for performance-sensitive applications. ```csharp using ZaString.Core; using ZaString.Extensions; Span buffer = stackalloc char[100]; var builder = ZaSpanStringBuilder.Create(buffer); var now = new DateTime(2025, 11, 20, 14, 30, 45); // Standard DateTime formatting builder.Append("Date: ") .Append(now, "yyyy-MM-dd") // "2025-11-20" .Append(" Time: ") .Append(now, "HH:mm:ss") // "14:30:45" .Append(" ISO: ") .Append(now, "O"); // "2025-11-20T14:30:45.0000000" Console.WriteLine(builder.AsSpan().ToString()); ``` -------------------------------- ### Conditional Appending with AppendIf Source: https://github.com/corentings/zastring/blob/main/README.md Shows how to conditionally append a string based on a boolean condition using the `AppendIf` extension method. This is useful for building dynamic strings. ```csharp var isActive = true; builder.Append("Status: ") .AppendIf(isActive, "Active", "Inactive"); ``` -------------------------------- ### Write UTF-8 Bytes with ZaString Source: https://context7.com/corentings/zastring/llms.txt Writes UTF-8 encoded bytes directly to a stack-allocated buffer using ZaUtf8SpanWriter. This method is efficient for low-level string encoding and supports various data types and encodings like Hex and Base64. It requires ZaString.Core, ZaString.Extensions, and System.Text. ```csharp using System.Text; using ZaString.Core; using ZaString.Extensions; Span buffer = stackalloc byte[256]; var writer = ZaUtf8SpanWriter.Create(buffer); // Write UTF-8 bytes writer.Append("Hello, ") .Append("UTF-8 World!") .Append(" Number: ") .Append(123) .Append(" Pi: ") .Append(3.14159, "F2"); // Access written bytes ReadOnlySpan utf8Bytes = writer.AsSpan(); Console.WriteLine($"Written {writer.Length} bytes"); Console.WriteLine(Encoding.UTF8.GetString(utf8Bytes)); // Output: Hello, UTF-8 World! Number: 123 Pi: 3.14 // Hex and Base64 encoding writer.Clear(); byte[] data = { 0x01, 0x02, 0x03, 0xFF }; writer.Append("Hex: ") .AppendHex(data, uppercase: true) .Append(", Base64: ") .AppendBase64(data); Console.WriteLine(Encoding.UTF8.GetString(writer.AsSpan())); // Output: Hex: 010203FF, Base64: AQIID/w= ``` -------------------------------- ### Conditional Appending with ZaString Source: https://context7.com/corentings/zastring/llms.txt Appends content to a string builder based on boolean conditions without interrupting the fluent interface. This method is useful for building strings dynamically where certain parts should only be included if specific criteria are met. It utilizes the ZaSpanStringBuilder and ZaString.Extensions. ```csharp using ZaString.Core; using ZaString.Extensions; Span buffer = stackalloc char[100]; var builder = ZaSpanStringBuilder.Create(buffer); bool isActive = true; bool isPremium = false; int score = 85; // Conditional appending with multiple conditions builder.Append("Status: ") .AppendIf(isActive, "Active") .AppendIf(!isActive, "Inactive") .Append(", Tier: ") .AppendIf(isPremium, "Premium") .AppendIf(!isPremium, "Standard") .AppendIf(score > 80, ", High Score!"); Console.WriteLine(builder.AsSpan().ToString()); // Output: "Status: Active, Tier: Standard, High Score!" ``` -------------------------------- ### ZaUtf8SpanWriter for UTF-8 Byte Operations Source: https://github.com/corentings/zastring/blob/main/README.md Demonstrates the use of ZaUtf8SpanWriter for writing UTF-8 encoded data directly to a byte span. It allows appending strings and numbers as UTF-8 bytes and accessing the result as a byte span. ```csharp Span buffer = stackalloc byte[256]; var writer = ZaUtf8SpanWriter.Create(buffer); writer.Append("Hello, UTF-8 World!") .Append(" Number: ") .Append(123); var utf8Bytes = writer.AsSpan(); ``` -------------------------------- ### HTML Entity Escaping with ZaString Source: https://context7.com/corentings/zastring/llms.txt Escapes special HTML characters (like `<`, `>`, `&`) into their corresponding HTML entities (`<`, `>`, `&`) to prevent cross-site scripting (XSS) attacks and ensure correct rendering. This functionality is provided by `AppendHtmlEscaped` and its safe counterpart, `TryAppendHtmlEscaped`, which also validates buffer space. ```csharp using ZaString.Core; using ZaString.Extensions; Span buffer = stackalloc char[256]; var builder = ZaSpanStringBuilder.Create(buffer); string htmlInput = ""; string message = "You & I > them"; // Escape HTML content builder.Append("
") .AppendHtmlEscaped(htmlInput) .Append("

") .AppendHtmlEscaped(message) .Append("

"); Console.WriteLine(builder.AsSpan().ToString()); // Output:
<script>alert('xss')</script>

You & I > them

// Safe variant builder.Clear(); if (builder.TryAppendHtmlEscaped(htmlInput)) { Console.WriteLine($"Safe HTML: {builder.AsSpan().ToString()}"); } ``` -------------------------------- ### JSON String Escaping with ZaString Source: https://context7.com/corentings/zastring/llms.txt Escapes strings to ensure they are safely representable within a JSON document. This includes handling special characters like newlines, tabs, and quotes by preceding them with backslashes. It offers both a standard `AppendJsonEscaped` and a safe `TryAppendJsonEscaped` variant that checks buffer capacity. ```csharp using ZaString.Core; using ZaString.Extensions; Span buffer = stackalloc char[256]; var builder = ZaSpanStringBuilder.Create(buffer); string userInput = "Line1\nLine2\t\"Quote\""; string name = "Alice \"A\""; // Build JSON object with escaped strings builder.Append("{\"name\":\"") .AppendJsonEscaped(name) .Append("\",\"message\":\"") .AppendJsonEscaped(userInput) .Append("\"}"); Console.WriteLine(builder.AsSpan().ToString()); // Output: {"name":"Alice \"A\"","message":"Line1\nLine2\t\"Quote\""} // Safe variant with TryAppendJsonEscaped builder.Clear(); if (builder.TryAppendJsonEscaped(userInput)) { Console.WriteLine($"Escaped: {builder.AsSpan().ToString()}"); } ``` -------------------------------- ### Escape CSV Fields with ZaString Source: https://context7.com/corentings/zastring/llms.txt Escapes CSV fields by adding quotes and doubling internal quotes using ZaSpanStringBuilder. This ensures proper formatting for CSV data, handling commas and quotes within fields. It requires the ZaString.Core and ZaString.Extensions namespaces. ```csharp using ZaString.Core; using ZaString.Extensions; Span buffer = stackalloc char[200]; var builder = ZaSpanStringBuilder.Create(buffer); // CSV fields that need escaping string[] fields = { "Simple", "Has,Comma", "Has\"Quote\"", " Leading Space", "Trailing Space " }; // Build CSV row for (int i = 0; i < fields.Length; i++) { if (i > 0) builder.Append(','); builder.AppendCsvEscaped(fields[i]); } Console.WriteLine(builder.AsSpan().ToString()); // Output: Simple,"Has,Comma","Has\"\"Quote\"\""," Leading Space","Trailing Space " ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.