### Getting Started with ZString Source: https://github.com/cysharp/zstring/blob/master/README.md Instructions on how to install and start using ZString in .NET Core and Unity projects. ```APIDOC ## Getting Started with ZString ### Installation For .NET Core projects, install the ZString package via NuGet: ```powershell PM> Install-Package ZString ``` For Unity projects, download the `ZString.Unity.unitypackage` from the [releases](https://github.com/Cysharp/ZString/releases) page. ### Basic Usage Example ```csharp using Cysharp.Text; // namespace async void Example(int x, int y, int z) { // Concatenate values _ = ZString.Concat(x, y, z); // Use numeric format strings _ = ZString.Format("x:{0}, y:{1:000}, z:{2:P}", x, y, z); // Join elements with a separator _ = ZString.Join(',', x, y, z); // For Unity, direct write to TextMeshPro to avoid string allocation // tmp.SetTextFormat("Position: {0}, {1}, {2}", x, y, z); // Create a StringBuilder for efficient string building using(var sb = ZString.CreateStringBuilder()) { sb.Append("foo"); sb.AppendLine(42); sb.AppendFormat("{0} {1:.###}", "bar", 123.456789); // Build the final string var str = sb.ToString(); // For Unity, direct write to TextMeshPro // tmp.SetText(sb); // Write to a destination buffer // sb.TryCopyTo(dest, out var written); } // Prepare a format string for reuse var prepared = ZString.PrepareUtf16("x:{0}, y:{1:000}"); _ = prepared.Format(10, 20); // Using C# 8.0 'using' declarations for Utf8 StringBuilder using var sb2 = ZString.CreateUtf8StringBuilder(); sb2.AppendFormat("foo:{0} bar:{1}", x, y); // Directly write to stream or destination to avoid allocation // await sb2.WriteToAsync(stream); // sb2.CopyTo(bufferWritter); // sb2.TryCopyTo(dest, out var written); } ``` ``` -------------------------------- ### Unity Installation Source: https://github.com/cysharp/zstring/blob/master/README.md Instructions for installing ZString in a Unity project. ```APIDOC ## Unity Installation ### Description Instructions for installing ZString in a Unity project using UPM or an asset package. ### Installation Methods 1. **UPM Git URL Package**: `https://github.com/Cysharp/ZString.git?path=src/ZString.Unity/Assets/Scripts/ZString` To specify a target version, append the release tag like `#2.4.0`. 2. **Asset Package**: Download `ZString...*.unitypackage` from the [ZString/releases](https://github.com/Cysharp/ZString/releases) page. ### Minimum Unity Version - 2021.3 ### Dependencies - **System.Runtime.CompilerServices.Unsafe**: Included with the unitypackage. For git references, you need to add it separately (e.g., extract DLL from unitypackage or download from NuGet). ``` -------------------------------- ### UTF-8 Guid Formatting Example Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-configuration.md Demonstrates standard GUID formats for UTF-8. ```csharp {0:D} ``` -------------------------------- ### UTF-16 Guid Formatting Example Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-configuration.md Shows standard .NET Guid format specifiers. ```csharp sb.AppendFormat("{0:B}", guid) ``` -------------------------------- ### Custom Formatter Implementation Example Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-configuration.md Example of a good custom formatter implementation for a struct type. Register this method at startup. ```csharp public class Point { public int X { get; set; } public int Y { get; set; } public static bool TryFormat( Point value, Span destination, out int charsWritten, ReadOnlySpan format) { var text = $"({value.X}, {value.Y})"; charsWritten = text.Length; return text.AsSpan().TryCopyTo(destination); } } // Register at startup Utf16ValueStringBuilder.RegisterTryFormat(Point.TryFormat); ``` -------------------------------- ### UTF-16 Alignment Formatting Example Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-configuration.md Illustrates standard .NET alignment formatting for numbers. ```csharp sb.AppendFormat("{0,5}", 42) ``` -------------------------------- ### Utf8PreparedFormat Example Methods Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-types.md Illustrates the Format and FormatTo methods for Utf8PreparedFormat with two type parameters, operating on IBufferWriter. ```csharp public sealed partial class Utf8PreparedFormat { public string Format(T1 arg1, T2 arg2) { ... } public void FormatTo(ref TBufferWriter sb, T1 arg1, T2 arg2) where TBufferWriter : IBufferWriter { ... } } ``` -------------------------------- ### Get Original Format String Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-core-api.md Retrieves the original format string used for preparation. ```csharp public string FormatString { get; } ``` -------------------------------- ### ZString Basic Usage Example Source: https://github.com/cysharp/zstring/blob/master/README.md Demonstrates various ZString methods for string concatenation, formatting, joining, and building strings with StringBuilder. Includes Unity-specific TextMeshPro integration and C# 8.0 using declarations for Utf8 StringBuilder. ```csharp using Cysharp.Text; // namespace async void Example(int x, int y, int z) { // same as x + y + z _ = ZString.Concat(x, y, z); // also can use numeric format strings _ = ZString.Format("x:{0}, y:{1:000}, z:{2:P}",x, y, z); _ = ZString.Join(',', x, y, z); // for Unity, direct write(avoid string allocation completely) to TextMeshPro tmp.SetTextFormat("Position: {0}, {1}, {2}", x, y, z); // create StringBuilder using(var sb = ZString.CreateStringBuilder()) { sb.Append("foo"); sb.AppendLine(42); sb.AppendFormat("{0} {1:.###}", "bar", 123.456789); // and build final string var str = sb.ToString(); // for Unity, direct write to TextMeshPro tmp.SetText(sb); // write to destination buffer sb.TryCopyTo(dest, out var written); } // prepare format, return value should store to field(like RegexOptions.Compile) var prepared = ZString.PrepareUtf16("x:{0}, y:{1:000}"); _ = prepared.Format(10, 20); // C# 8.0, Using declarations // create Utf8 StringBuilder that build Utf8 directly to avoid encoding using var sb2 = ZString.CreateUtf8StringBuilder(); sb2.AppendFormat("foo:{0} bar:{1}", x, y); // directly write to steam or dest to avoid allocation await sb2.WriteToAsync(stream); sb2.CopyTo(bufferWritter); sb2.TryCopyTo(dest, out var written); } ``` -------------------------------- ### UTF-16 DateTime Formatting Example Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-configuration.md Illustrates standard .NET DateTime format specifiers. ```csharp sb.AppendFormat("{0:yyyy-MM-dd}", now) ``` -------------------------------- ### Utf16PreparedFormat Usage Example Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-types.md Demonstrates the usage pattern for Utf16PreparedFormat, showing how to pre-parse a format string for efficient single-argument UTF-16 formatting. ```csharp var fmt = ZString.PrepareUtf16("Value: {0:D3}"); var s1 = fmt.Format(10); // "Value: 010" var s2 = fmt.Format(42); // "Value: 042" (no re-parsing) ``` -------------------------------- ### UTF-16 Integer Formatting Example Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-configuration.md Demonstrates standard .NET integer format specifiers like 'D' for zero-padding. ```csharp sb.AppendFormat("{0:D3}", 42) ``` -------------------------------- ### UTF-8 DateTime Formatting Example Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-configuration.md Notes limited format support for UTF-8 DateTime. ```csharp {0:G} ``` -------------------------------- ### UTF-8 TimeSpan Formatting Example Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-configuration.md Shows compact format specifier for UTF-8 TimeSpan. ```csharp {0:c} ``` -------------------------------- ### UTF-8 Integer Formatting Example Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-configuration.md Shows UTF-8 integer format specifiers like 'D2' for zero-padding. ```csharp {0:D2} ``` -------------------------------- ### UTF-8 Float Formatting Example Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-configuration.md Illustrates UTF-8 float format specifiers like 'F2' for decimal places. ```csharp {0:F2} ``` -------------------------------- ### Generic Concat and Format Examples Source: https://github.com/cysharp/zstring/blob/master/_autodocs/README.md Demonstrates the use of ZString's generic methods for concatenating and formatting values, supporting up to 16 type parameters to avoid boxing. ```csharp ZString.Concat(int) // T1 ZString.Concat(int, string) // T1, T2 ZString.Format(string, int, string, bool) // T1, T2, T3 // ... up to T16 ``` -------------------------------- ### UTF-16 Float Formatting Example Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-configuration.md Shows standard .NET float format specifiers like 'F' for decimal places. ```csharp sb.AppendFormat("{0:F2}", 3.14) ``` -------------------------------- ### Registering Custom UTF-8 Formatter Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-configuration.md Example of registering a custom formatter for a 'Position' type with UTF-8. ```csharp Utf8ValueStringBuilder.RegisterTryFormat( (pos, dest, out written, format) => { var text = $"({pos.X},{pos.Y})"; written = Encoding.UTF8.GetByteCount(text); if (dest.Length < written) return false; written = Encoding.UTF8.GetBytes(text, dest); return true; }); ``` -------------------------------- ### Registering Custom UTF-16 Formatter Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-configuration.md Example of registering a custom formatter for a 'Position' type with UTF-16. ```csharp Utf16ValueStringBuilder.RegisterTryFormat( (pos, dest, out written, format) => { var text = $"({pos.X},{pos.Y})"; written = text.Length; return text.AsSpan().TryCopyTo(dest); }); ``` -------------------------------- ### UTF-16 TimeSpan Formatting Example Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-configuration.md Demonstrates standard .NET TimeSpan format specifiers, including escaping colons. ```csharp sb.AppendFormat("{0:hh\:mm\:ss}", span) ``` -------------------------------- ### Get Estimated Minimum Size Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-core-api.md Provides the estimated minimum UTF-8 byte buffer size required for the formatted string. ```csharp public int MinSize { get; } ``` -------------------------------- ### NestedStringBuilderCreationException Example Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-types.md Illustrates an invalid scenario where a non-nestable builder is created while another is active. Fix by using 'notNested: false' or ensuring proper disposal. ```csharp // NG: Nested usage of notNested: true using var sb1 = ZString.CreateStringBuilder(notNested: true); { using var sb2 = ZString.CreateStringBuilder(notNested: true); // Throws! } ``` -------------------------------- ### Utf8ValueStringBuilder.Length Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-core-api.md Gets the number of bytes currently written to the Utf8ValueStringBuilder buffer. ```APIDOC ## Length ### Description The number of bytes written to the buffer. ### Method `int` (get-only property) ### Source `src/ZString/Utf8ValueStringBuilder.cs:52` ``` -------------------------------- ### Utf16ValueStringBuilder.Remove Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-core-api.md Removes characters from the Utf16ValueStringBuilder starting at a specified index for a given length. ```APIDOC ## Remove(int startIndex, int length) ### Description Removes characters from the builder. ### Method `void` ### Parameters #### Path Parameters - **startIndex** (int) - Yes - Start position. - **length** (int) - Yes - Number of characters to remove. ### Throws - `ArgumentOutOfRangeException` - If parameters are invalid. ### Source `src/ZString/Utf16ValueStringBuilder.cs:515-546` ``` -------------------------------- ### Prepared Format Usage Source: https://github.com/cysharp/zstring/blob/master/_autodocs/README.md Shows how to pre-parse a format string once and reuse it multiple times for efficiency, avoiding repeated parsing overhead. ```csharp // Parse once at startup or cache var prepared = ZString.PrepareUtf16("Value: {0:D3}"); // Use many times without parsing for (int i = 0; i < 1000; i++) Console.WriteLine(prepared.Format(i)); ``` -------------------------------- ### Utf16ValueStringBuilder.Length Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-core-api.md Gets the number of characters currently written to the Utf16ValueStringBuilder's buffer. ```APIDOC ## Length ### Description The number of characters written to the buffer. ### Method `Length` (property) ### Returns `int` ``` -------------------------------- ### Disposing Builders to Return Buffers Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-configuration.md Illustrates the best practice of using 'using' to ensure builders are disposed and their buffers returned to the pool. ```csharp using var sb = ZString.CreateStringBuilder(); // ... // Dispose() called automatically, buffer returned to pool ``` -------------------------------- ### Prepared Formatting for Loops Source: https://github.com/cysharp/zstring/blob/master/_autodocs/README.md Utilize ZString.PrepareUtf16 for performance-critical loops. Pre-compiling the format string reduces overhead when formatting the same pattern repeatedly. ```csharp var fmt = ZString.PrepareUtf16("({0},{1})"); for (int i = 0; i < 100; i++) Console.WriteLine(fmt.Format(i, i*2)); ``` -------------------------------- ### Renting Buffers from ArrayPool Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-configuration.md Shows how to rent buffers from the shared ArrayPool for UTF-16 and UTF-8 string builders. ```csharp // UTF-16: Rent up to 32KB from shared pool var utf16Buffer = ArrayPool.Shared.Rent(32768); // UTF-8: Rent up to 64KB from shared pool var utf8Buffer = ArrayPool.Shared.Rent(65536); ``` -------------------------------- ### Allocation-Free Logging with Prepared Formats Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-advanced-patterns.md Use ZString's prepared formats for high-frequency logging to avoid string allocations. This pattern is suitable for production logging and works with any log sink. ```csharp public class ZStringLogger { private static readonly Utf16PreparedFormat ErrorFormat = ZString.PrepareUtf16("ERROR: {0} (Code: {1})"); private static readonly Utf8PreparedFormat PerformanceFormat = ZString.PrepareUtf8("{0} completed in {1:F3}s ({2} items)"); public void LogError(string message, int errorCode) { var text = ErrorFormat.Format(message, errorCode); Console.WriteLine(text); } public void LogPerformance(string operation, double elapsedSeconds, int itemCount) { var text = PerformanceFormat.Format(operation, elapsedSeconds, itemCount); Console.WriteLine(text); } // For complex logging messages public void LogRequest(string method, string path, int statusCode, double duration) { using var sb = ZString.CreateStringBuilder(); sb.Append("["); sb.Append(DateTime.Now.ToString("HH:mm:ss.fff")); sb.Append("] "); sb.Append(method); sb.Append(" "); sb.Append(path); sb.Append(" -> "); sb.Append(statusCode); sb.Append(" ("); sb.Append(duration); sb.AppendLine("ms)"); Console.Write(sb.AsSpan()); } } // Usage var logger = new ZStringLogger(); logger.LogError("Connection timeout", 408); logger.LogPerformance("Data processing", 1.234, 5000); ``` -------------------------------- ### Thread-Static Builder for Fast Path Source: https://github.com/cysharp/zstring/blob/master/_autodocs/README.md Illustrates using ZString's thread-static buffer for fast path operations, which avoids allocations but has constraints on nesting and usage. ```csharp // Fast: Uses thread-static, no allocation using var sb = ZString.CreateStringBuilder(notNested: true); sb.Append("quick"); return sb.ToString(); ``` -------------------------------- ### Get Utf8 Buffer as ArraySegment Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-core-api.md Returns the written UTF-8 buffer as an array segment of bytes. ```csharp public ArraySegment AsArraySegment() ``` -------------------------------- ### Get Utf8 Buffer as ReadOnlyMemory Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-core-api.md Returns the written UTF-8 buffer as read-only memory of bytes. ```csharp public ReadOnlyMemory AsMemory() ``` -------------------------------- ### Get Utf8 Buffer as ReadOnlySpan Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-core-api.md Returns the written UTF-8 buffer as a read-only span of bytes. ```csharp public ReadOnlySpan AsSpan() ``` -------------------------------- ### Utf16PreparedFormat Class Structure Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-types.md Illustrates the structure of a multi-parameter Utf16PreparedFormat class, specifically for three arguments, showing its Format and FormatTo methods. ```csharp public sealed partial class Utf16PreparedFormat { public string Format(T1 arg1, T2 arg2, T3 arg3) { ... } public void FormatTo(ref TBufferWriter sb, T1 arg1, T2 arg2, T3 arg3) where TBufferWriter : IBufferWriter { ... } } ``` -------------------------------- ### Get Utf8 Buffer Length Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-core-api.md Retrieves the number of bytes currently written to the UTF-8 buffer. ```csharp public int Length { get; } ``` -------------------------------- ### Fast Formatting with notNested: true Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-configuration.md Demonstrates using 'notNested: true' for short-lived, hot-path formatting to utilize a thread-static buffer and avoid ArrayPool allocation. ```csharp // Use for short-lived, hot-path formatting public string FormatQuickly(int value) { // Fast: Uses thread-static buffer, no ArrayPool allocation using var sb = ZString.CreateStringBuilder(notNested: true); sb.Append("Value: "); sb.Append(value); return sb.ToString(); } ``` -------------------------------- ### Use Prepared Formats for Repeated Formatting Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-configuration.md Pre-parse format strings using ZString.PrepareUtf16 to avoid re-parsing on each formatting operation, improving performance for repeated formatting tasks. ```csharp // Once: Pre-parse the format string static readonly Utf16PreparedFormat CoordinateFormat = ZString.PrepareUtf16("({0},{1})"); // Many times: Format without re-parsing for (int i = 0; i < 1000; i++) { var text = CoordinateFormat.Format(i, i * 2); // No format string parsing per iteration } ``` -------------------------------- ### Utf16PreparedFormat Methods Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-core-api.md Details the methods for formatting strings using pre-parsed templates for efficiency. ```APIDOC ## Format(T1 arg1, ..., T16 arg16) ### Description Formats the string with the given arguments, reusing the pre-parsed template. ### Method `public string Format(T1 arg1, T2 arg2)` ### Parameters * **arg1-argN** (T1-TN) - Required - Format arguments. ### Response * **string** ### Example ```csharp var prepared = ZString.PrepareUtf16("x:{0}, y:{1:000}"); var result1 = prepared.Format(10, 20); var result2 = prepared.Format(30, 40); ``` ### Source `src/ZString/PreparedFormat.cs` ## FormatTo(ref TBufferWriter sb, T1 arg1, ..., T16 arg16) ### Description Formats directly to a buffer writer without allocating an intermediate string. ### Method `public void FormatTo(ref TBufferWriter sb, T1 arg1, T2 arg2) where TBufferWriter : IBufferWriter` ### Parameters * **sb** (TBufferWriter) - Required - Target buffer writer (passed by reference). * **arg1-argN** (T1-TN) - Required - Format arguments. ### Response * None (void) ### Example ```csharp var prepared = ZString.PrepareUtf16("Value: {0:D3}"); var sb = ZString.CreateStringBuilder(); prepared.FormatTo(ref sb, 42); ``` ### Source `src/ZString/PreparedFormat.cs` ``` -------------------------------- ### ZString Factory Methods Source: https://github.com/cysharp/zstring/blob/master/_autodocs/README.md Provides methods for creating string builders and prepared format instances. ```APIDOC ## ZString Factory Methods ### Description Factory methods for creating string builders and prepared format instances. ### Methods - `ZString.CreateStringBuilder()`: Creates a new string builder instance. - `ZString.PrepareUtf16()`: Creates a prepared format instance for UTF-16 strings. ### Usage - Use `ZString.CreateStringBuilder()` to start building strings without allocations. - Use `ZString.PrepareUtf16()` for optimizing repeated formatting operations. ``` -------------------------------- ### Optimize repeated formatting Source: https://github.com/cysharp/zstring/blob/master/_autodocs/README.md Cache prepared format templates using PrepareUtf16() for scenarios with repeated formatting. This optimizes performance by pre-parsing format strings. ```csharp PrepareUtf16(); ``` -------------------------------- ### Get Written Buffer as ArraySegment Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-core-api.md Returns the written buffer as an array segment. Provides array-like access to the buffer content. ```csharp public ArraySegment AsArraySegment() ``` -------------------------------- ### Enabling Nullable Formatting Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-configuration.md Shows how to enable nullable formatting for specific types like DateTime and int. ```csharp Utf16ValueStringBuilder.EnableNullableFormat(); Utf16ValueStringBuilder.EnableNullableFormat(); ``` -------------------------------- ### Get Written Buffer as ReadOnlyMemory Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-core-api.md Returns the written buffer as read-only memory. Suitable for scenarios requiring memory-based access. ```csharp public ReadOnlyMemory AsMemory() ``` -------------------------------- ### Get Written Buffer as ReadOnlySpan Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-core-api.md Returns the written buffer as a read-only span. Useful for inspecting or passing the content without copying. ```csharp public ReadOnlySpan AsSpan() ``` ```csharp var sb = ZString.CreateStringBuilder(); sb.Append("Hello"); var span = sb.AsSpan(); ``` -------------------------------- ### Format String with PreparedTemplate (UTF-16) Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-core-api.md Formats a string using a pre-parsed template for UTF-16 output. This method is efficient for repeated formatting with the same format string and arguments. ```csharp public string Format(T1 arg1, T2 arg2) ``` ```csharp var prepared = ZString.PrepareUtf16("x:{0}, y:{1:000}"); var result1 = prepared.Format(10, 20); var result2 = prepared.Format(30, 40); ``` -------------------------------- ### Remove Characters from Utf16ValueStringBuilder Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-core-api.md Removes a specified number of characters from the builder starting at a given index. Ensure parameters are valid to avoid exceptions. ```csharp public void Remove(int startIndex, int length) ``` -------------------------------- ### Non-Nestable Fast Path with Fallback Formatting Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-advanced-patterns.md Optimize string formatting using a thread-static buffer for a fast path, with a fallback to a nestable method for edge cases. Avoids exceptions on nested calls. ```csharp public class FormattingService { private static readonly ThreadLocal InFormatting = new(); public string Format(string format, T1 arg1, T2 arg2) { // Try fast path if (!InFormatting.Value) { InFormatting.Value = true; try { return FormatFast(format, arg1, arg2); } finally { InFormatting.Value = false; } } // Fallback for nested calls return FormatSafe(format, arg1, arg2); } private string FormatFast(string format, T1 arg1, T2 arg2) { // Use thread-static buffer (faster) using var sb = ZString.CreateStringBuilder(notNested: true); sb.AppendFormat(format, arg1, arg2); return sb.ToString(); } private string FormatSafe(string format, T1 arg1, T2 arg2) { // Use ArrayPool (nestable) using var sb = ZString.CreateStringBuilder(notNested: false); sb.AppendFormat(format, arg1, arg2); return sb.ToString(); } } ``` -------------------------------- ### SetTextFormat(this TMP_Text text, string format, T0 arg0, ..., T15 arg15) Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-core-api.md Sets TextMeshPro text with formatted output (up to 16 arguments) without intermediate string allocation, optimized for Unity. ```APIDOC ## SetTextFormat(this TMP_Text text, string format, T0 arg0, ..., T15 arg15) ### Description Sets TextMeshPro text with formatted output, up to 16 arguments, without intermediate string allocation. ### Method `public static void SetTextFormat(this TMP_Text text, string format, T0 arg0)` ### Parameters #### TextMeshPro Component - **text** (TMP_Text) - Required - Description: TextMeshPro component. #### Format String - **format** (string) - Required - Description: Format string. #### Format Arguments - **arg0-arg15** (T0-T15) - Required - Description: Format arguments. ### Returns `void` ### Example ```csharp textMeshPro.SetTextFormat("Position: {0}, {1}, {2}", x, y, z); ``` ``` -------------------------------- ### Use TextMeshPro in Unity Source: https://github.com/cysharp/zstring/blob/master/_autodocs/README.md Integrate ZString with Unity's TextMeshPro using the SetTextFormat() extension method. This allows for allocation-free text updates in Unity UI. ```csharp SetTextFormat(); ``` -------------------------------- ### TextMeshProExtensions Class (Unity only) Source: https://github.com/cysharp/zstring/blob/master/README.md Extension methods for TextMeshPro to improve performance by avoiding string allocations. ```APIDOC ## TextMeshProExtensions Class (Unity only) ### Description Extension methods for TextMeshPro to set text directly from ZString builders or formatted strings, avoiding intermediate string allocations. ### Methods - **SetText(Utf16ValueStringBuilder)**: Sets the inner buffer directly to TextMeshPro to avoid string allocation. - **SetTextFormat(string, T1,..,T16)**: Sets formatted string without string allocation. ``` -------------------------------- ### Trigger Builder Use After Disposal Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-errors.md Example code that triggers a NullReferenceException or incorrect behavior by attempting to use a string builder after its Dispose() method has been called. ```csharp var sb = ZString.CreateStringBuilder(); sb.Append("hello"); sb.Dispose(); // NG: This will likely throw NullReferenceException sb.Append(" world"); // sb.buffer is now null var result = sb.ToString(); ``` -------------------------------- ### Utf16PreparedFormat Class Source: https://github.com/cysharp/zstring/blob/master/README.md Provides methods for pre-formatting strings with multiple arguments. ```APIDOC ## Utf16PreparedFormat Class ### Description Provides methods for pre-formatting strings with multiple arguments, optimized for UTF-16. ### Methods - **Format**: Replaces one or more format items in a string with the string representation of some specified values. - **FormatTo(ref TBufferWriter, T1,..,T16)**: Replaces one or more format items in a string with the string representation of some specified values, writing to a buffer writer. ``` -------------------------------- ### Create a string builder Source: https://github.com/cysharp/zstring/blob/master/_autodocs/README.md Use ZString.CreateStringBuilder() to create a new string builder instance. This is the factory method for obtaining a builder. ```csharp var sb = ZString.CreateStringBuilder(); ``` -------------------------------- ### Prepare UTF-8 Format String Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-core-api.md Pre-parses a UTF-8 format string for repeated use. Returns a reusable prepared UTF-8 format object. ```csharp public static Utf8PreparedFormat PrepareUtf8(string format) ``` -------------------------------- ### Prepare UTF-16 Format String Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-core-api.md Pre-parses a format string for UTF-16 output to avoid repeated parsing on each format call. Returns a prepared format object that can be reused. ```csharp public static Utf16PreparedFormat PrepareUtf16(string format) ``` ```csharp var prepared = ZString.PrepareUtf16("x:{0}, y:{1:000}"); var result1 = prepared.Format(10, 20); var result2 = prepared.Format(30, 40); // No re-parsing on second call ``` -------------------------------- ### Define ZSTRING_TEXTMESHPRO_SUPPORT Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-configuration.md Add ZSTRING_TEXTMESHPRO_SUPPORT to your Scripting Define Symbols in Project Settings to enable TextMeshPro extensions. ```text ZSTRING_TEXTMESHPRO_SUPPORT ``` -------------------------------- ### TextMeshPro Integration Source: https://github.com/cysharp/zstring/blob/master/_autodocs/README.md Extension methods for integrating ZString with Unity's TextMeshPro. ```APIDOC ## TextMeshPro Extensions ### Description Provides extension methods for efficiently setting text on Unity's TextMeshPro components using ZString. ### Methods - `TextMeshProExtensions.SetText()`: Sets the text of a TextMeshPro component using a ZString builder. - `TextMeshProExtensions.SetTextFormat()`: Sets the text of a TextMeshPro component using formatted arguments. ### Usage - Integrate ZString with TextMeshPro to achieve zero-allocation text updates in Unity. - Use `SetTextFormat` for dynamic text content with arguments. ``` -------------------------------- ### Initialize Utf16ValueStringBuilder Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-core-api.md Initializes a new UTF-16 string builder. Choose disposeImmediately based on nesting and performance needs. ```csharp public Utf16ValueStringBuilder(bool disposeImmediately) ``` -------------------------------- ### Compare String Concatenation Methods Source: https://github.com/cysharp/zstring/blob/master/README.md Compares the performance and allocation characteristics of different string concatenation and formatting methods in C#, including standard string concatenation, ZString.Concat, string.Format, and StringBuilder. ```C# "x:" + x + " y:" + y + " z:" + z ``` ```C# ZString.Concat("x:", x, " y:", y, " z:", z) ``` ```C# string.Format("x:{0} y:{1} z:{2}", x, y, z) ``` ```C# ZString.Format("x:{0} y:{1} z:{2}", x, y, z) ``` ```C# new StringBuilder(), Append(), .ToString() ``` ```C# ZString.CreateStringBuilder(), Append(), .ToString() ``` -------------------------------- ### Utf8PreparedFormat Class Source: https://github.com/cysharp/zstring/blob/master/README.md Provides methods for pre-formatting strings with multiple arguments, optimized for UTF-8. ```APIDOC ## Utf8PreparedFormat Class ### Description Provides methods for pre-formatting strings with multiple arguments, optimized for UTF-8. ### Methods - **Format**: Replaces one or more format items in a string with the string representation of some specified values. - **FormatTo(ref TBufferWriter, T1,..,T16)**: Replaces one or more format items in a string with the string representation of some specified values, writing to a buffer writer. ``` -------------------------------- ### ZStringWriter Constructors Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-core-api.md Provides constructors for the ZStringWriter class, allowing initialization with default or custom format providers. ```APIDOC ## ZStringWriter() ### Description Creates a writer using the current culture as format provider. ### Method `public ZStringWriter()` ### Parameters * None ### Response * None ### Source `src/ZString/ZStringWriter.cs:25-27` ## ZStringWriter(IFormatProvider formatProvider) ### Description Creates a writer with a specific format provider. ### Method `public ZStringWriter(IFormatProvider formatProvider)` ### Parameters * **formatProvider** (IFormatProvider) - Required - Format provider for number/date formatting. ### Response * None ### Source `src/ZString/ZStringWriter.cs:32-36` ``` -------------------------------- ### MinSize Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-core-api.md Estimates the minimum UTF-8 byte buffer size required for the formatted string. ```APIDOC ## MinSize ### Description Estimates the minimum UTF-8 byte buffer size needed for formatting. ### Returns `int` - The estimated minimum UTF-8 byte buffer size. ``` -------------------------------- ### Format String with Single Argument Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-core-api.md Formats a template string using a single argument and returns the result as a UTF-8 decoded string. ```csharp public string Format(T1 arg1) ``` -------------------------------- ### ZString Reference Source: https://github.com/cysharp/zstring/blob/master/README.md Detailed reference for the static ZString class and its associated structs. ```APIDOC ## ZString Static Class Reference **`static class ZString`** | Method Signature | Returns | Description | |---|---|---| | `CreateStringBuilder()` | `Utf16ValueStringBuilder` | Creates a `Utf16ValueStringBuilder` for efficient string building. | `CreateStringBuilder(bool notNested)` | `Utf16ValueStringBuilder` | Creates a `Utf16ValueStringBuilder`. If `notNested` is true, uses a thread-static buffer for potentially faster performance, but the buffer must be returned immediately. | `CreateUtf8StringBuilder()` | `Utf8ValueStringBuilder` | Creates a `Utf8ValueStringBuilder` for building `Span` directly. | `CreateUtf8StringBuilder(bool notNested)` | `Utf8ValueStringBuilder` | Creates a `Utf8ValueStringBuilder`. If `notNested` is true, uses a thread-static buffer for potentially faster performance, but the buffer must be returned immediately. | `Join(char separator, T[] values)`
`Join(string separator, T[] values)`
`Join(char separator, IEnumerable values)`
`Join(string separator, IEnumerable values)` | `string` | Concatenates the elements of an array or enumerable, using the specified separator between each element. | `PrepareUtf16(string format)` | `Utf16PreparedFormat` | Prepares a UTF-16 format string for reuse, avoiding repeated parsing of the template. | `PrepareUtf8(string format)` | `Utf8PreparedFormat` | Prepares a UTF-8 format string for reuse, avoiding repeated parsing of the template. | `Concat(T1 value1,..,T16 value16)` | `string` | Concatenates the string representations of the specified values. | `Format(string format, T1 value1,..,T16 value16)` | `string` | Replaces one or more format items in a string with the string representations of the specified values. | `Utf8Format(IBufferWriter writer, T1 value1,..,T16 value16)` | `void` | Writes the formatted string directly to an `IBufferWriter`. ## Utf16ValueStringBuilder Struct Reference **`struct Utf16ValueStringBuilder : IBufferWriter, IDisposable`** | Method Signature | Returns | Description | |---|---|---| | `Length` | `int` | Gets the length of the written buffer. | `AsSpan()` | `ReadOnlySpan` | Gets the written buffer data as a read-only span of characters. | `AsMemory()` | `ReadOnlyMemory` | Gets the written buffer data as a read-only memory of characters. | `AsArraySegment()` | `ArraySegment` | Gets the written buffer data as an array segment. | `Dispose()` | `void` | Returns the inner buffer to the pool. | `Append(T value)` | `void` | Appends the string representation of a specified value to this instance. | `Append(T value, string format)` | `void` | Appends the string representation of a specified value with numeric format strings to this instance. | `AppendJoin(char separator, T[] values)`
`AppendJoin(string separator, T[] values)`
`AppendJoin(char separator, IEnumerable values)`
`AppendJoin(string separator, IEnumerable values)` | `void` | Concatenates and appends the elements of an array or enumerable, using the specified separator between each element. | `AppendLine()` | `void` | Appends the default line terminator to the end of this instance. | `AppendLine(T value)` | `void` | Appends the string representation of a specified value followed by the default line terminator to the end of this instance. | `AppendLine(T value, string format)` | `void` | Appends the string representation of a specified value with numeric format strings followed by the default line terminator to the end of this instance. | `AppendFormat(string format, T1 value1,..,T16 value16)` | `void` | Appends the string returned by processing a composite format string, where each format item is replaced by the string representation of the corresponding argument. ``` -------------------------------- ### Format String to BufferWriter (UTF-16) Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-core-api.md Formats a string directly to a buffer writer using a pre-parsed template for UTF-16 output, avoiding intermediate string allocations. The buffer writer is passed by reference. ```csharp public void FormatTo(ref TBufferWriter sb, T1 arg1, T2 arg2) where TBufferWriter : IBufferWriter ``` ```csharp var prepared = ZString.PrepareUtf16("Value: {0:D3}"); var sb = ZString.CreateStringBuilder(); prepared.FormatTo(ref sb, 42); ``` -------------------------------- ### Format(T1 arg1, ..., T16 arg16) Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-core-api.md Formats the template string with provided arguments, returning a UTF-8 decoded string. ```APIDOC ## Format(T1 arg1, ..., T16 arg16) ### Description Formats the template, returning a UTF-8 string (decoded from internal UTF-8 buffer). ### Method `public string Format(T1 arg1)` ### Parameters #### Format Arguments - **arg1-argN** (T1-TN) - Required - Description: Format arguments. ### Returns `string` - The formatted string. ``` -------------------------------- ### Unity TextMeshPro Zero-Allocation UI Updates Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-advanced-patterns.md Integrate ZString with Unity's TextMeshPro for real-time UI updates without string allocations. This is suitable for performance-critical applications like games, especially on mobile platforms. ```csharp #if ZSTRING_TEXTMESHPRO_SUPPORT using UnityEngine; using TMPro; using Cysharp.Text; public class GameUI : MonoBehaviour { [SerializeField] private TextMeshProUGUI healthText; [SerializeField] private TextMeshProUGUI scoreText; [SerializeField] private TextMeshProUGUI timerText; private int health = 100; private int score = 0; private float elapsedSeconds = 0f; void Update() { elapsedSeconds += Time.deltaTime; // Zero-allocation UI updates using prepared formats UpdateHealthDisplay(); UpdateScoreDisplay(); UpdateTimerDisplay(); } private void UpdateHealthDisplay() { // Method 1: Direct format with SetTextFormat healthText.SetTextFormat("Health: {0}/100", health); } private void UpdateScoreDisplay() { // Method 2: Using prepared format for repeated calls var prepared = ZString.PrepareUtf16("Score: {0:D6}"); scoreText.SetText(prepared.Format(score)); } private void UpdateTimerDisplay() { // Method 3: Using StringBuilder for complex formatting using var sb = ZString.CreateStringBuilder(); var minutes = (int)(elapsedSeconds / 60); var seconds = (int)(elapsedSeconds % 60); var milliseconds = (int)((elapsedSeconds * 1000) % 1000); sb.AppendFormat("{0:D2}:{1:D2}.{2:D3}", minutes, seconds, milliseconds); timerText.SetText(sb); } public void TakeDamage(int amount) { health -= amount; UpdateHealthDisplay(); // No allocation } public void AddScore(int points) { score += points; UpdateScoreDisplay(); // No allocation } } #endif ``` -------------------------------- ### Utf16PreparedFormat through Utf16PreparedFormat Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-types.md Pre-parsed UTF-16 format templates supporting 2 through 16 type parameters. Each class provides methods for formatting with multiple arguments efficiently. ```APIDOC ## Classes Utf16PreparedFormat through Utf16PreparedFormat ### Description Pre-parsed UTF-16 format templates supporting 2 through 16 type parameters. Each class follows the same structure as `Utf16PreparedFormat` but with additional type parameters. ### Purpose Optimizes formatting by pre-parsing the format string for multiple arguments. ### Each Class Includes - Constructor: `(string format)` - Property: `FormatString`, `MinSize` - Methods: `Format(T1 arg1, T2 arg2, ...)`, `FormatTo(ref TBufferWriter sb, ...)` ### Example (T3) ```csharp public sealed partial class Utf16PreparedFormat { public string Format(T1 arg1, T2 arg2, T3 arg3) { ... } public void FormatTo(ref TBufferWriter sb, T1 arg1, T2 arg2, T3 arg3) where TBufferWriter : IBufferWriter { ... } } ``` ``` -------------------------------- ### PrepareUtf16 Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-core-api.md Pre-parses a format string for efficient, repeated use with UTF-16 strings. Returns a prepared format object that avoids re-parsing on subsequent calls. ```APIDOC ## PrepareUtf16(string format) ### Description Pre-parses a format string to avoid repeated parsing on each format call. Returns a prepared format object that can be reused. ### Method `PrepareUtf16` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **format** (string) - Required - Format string to prepare. ### Returns `Utf16PreparedFormat` - A reusable prepared format object. ### Example ```csharp var prepared = ZString.PrepareUtf16("x:{0}, y:{1:000}"); var result1 = prepared.Format(10, 20); var result2 = prepared.Format(30, 40); // No re-parsing on second call ``` ``` -------------------------------- ### Register and Use Custom Type Formatter (UTF-16) Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-advanced-patterns.md Registers a custom TryFormat method for a struct type to enable efficient, allocation-free formatting with ZString. Avoids boxing and ToString() calls. ```csharp public struct Vector3 { public float X, Y, Z; public Vector3(float x, float y, float z) { X = x; Y = y; Z = z; } // Implement TryFormat method matching the delegate signature public static bool TryFormat( Vector3 value, Span destination, out int charsWritten, ReadOnlySpan format) { // Format as "(X, Y, Z)" var text = $"({value.X:F2}, {value.Y:F2}, {value.Z:F2})"; charsWritten = text.Length; return text.AsSpan().TryCopyTo(destination); } } // Application startup class Program { static Program() { // Register once Utf16ValueStringBuilder.RegisterTryFormat(Vector3.TryFormat); // For UTF-8 formatting Utf8ValueStringBuilder.RegisterTryFormat( (value, dest, out written, format) => { var text = $"({value.X:F2}, {value.Y:F2}, {value.Z:F2})"; written = text.Length; return text.AsSpan().TryCopyTo(dest); }); } static void Main() { var pos = new Vector3(1.5f, 2.5f, 3.5f); using var sb = ZString.CreateStringBuilder(); sb.Append("Position: "); sb.Append(pos); // Uses registered formatter Console.WriteLine(sb.ToString()); // "Position: (1.50, 2.50, 3.50)" } } ``` -------------------------------- ### Utf16PreparedFormat Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-types.md Represents a pre-parsed format template for single-argument UTF-16 formatting. It allows for efficient repeated formatting without re-parsing the format string. ```APIDOC ## Class Utf16PreparedFormat ### Description Pre-parsed format template for single-argument UTF-16 formatting. Allows for efficient repeated formatting without re-parsing the format string. ### Purpose Optimizes formatting by pre-parsing the format string for a single argument. ### Type Parameters - `T1`: Type of the single format argument. ### Properties - `FormatString`: Original format string - `MinSize`: Estimated minimum buffer capacity ### Methods - `Format(T1 arg1)`: Returns formatted string - `FormatTo(ref TBufferWriter sb, T1 arg1)`: Formats to buffer writer ### Usage Pattern ```csharp var fmt = ZString.PrepareUtf16("Value: {0:D3}"); var s1 = fmt.Format(10); // "Value: 010" var s2 = fmt.Format(42); // "Value: 042" (no re-parsing) ``` ``` -------------------------------- ### Format(string format, T1 arg1, T2 arg2) Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-core-api.md Formats a string with two arguments. ```APIDOC ## Format(string format, T1 arg1, T2 arg2) ### Description Formats a string with two arguments. ### Method Not applicable (static method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **format** (string) - Required - Format string. - **arg1** (T1) - Required - First argument. - **arg2** (T2) - Required - Second argument. ### Response #### Success Response - **string** - The formatted result. ### Example ```csharp var result = ZString.Format("x:{0}, y:{1:000}", 10, 5); // Result: "x:10, y:005" ``` ``` -------------------------------- ### CreateStringBuilder() Source: https://github.com/cysharp/zstring/blob/master/_autodocs/zstring-core-api.md Creates a new UTF-16 string builder using an ArrayPool-rented buffer. The builder must be disposed to return the buffer to the pool. ```APIDOC ## CreateStringBuilder() ### Description Creates a new UTF-16 string builder using ArrayPool-rented buffer. The builder must be disposed to return the buffer to the pool. ### Method `static Utf16ValueStringBuilder CreateStringBuilder()` ### Returns `Utf16ValueStringBuilder` - An initialized builder ready for UTF-16 text. ### Example ```csharp using var sb = ZString.CreateStringBuilder(); sb.Append("Hello"); sb.Append(' '); sb.Append("World"); var result = sb.ToString(); ``` ```