From bc1fc17b2135d1b6525731a6a71220cb384a35f1 Mon Sep 17 00:00:00 2001 From: Sergio Pedri Date: Tue, 26 Sep 2023 18:45:49 +0200 Subject: [PATCH] Add new WriteByteArrayInitializationExpressions API --- .../Helpers/SyntaxFormattingHelper.cs | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/src/ComputeSharp.SourceGeneration.Hlsl/Helpers/SyntaxFormattingHelper.cs b/src/ComputeSharp.SourceGeneration.Hlsl/Helpers/SyntaxFormattingHelper.cs index da489b18..da5256a7 100644 --- a/src/ComputeSharp.SourceGeneration.Hlsl/Helpers/SyntaxFormattingHelper.cs +++ b/src/ComputeSharp.SourceGeneration.Hlsl/Helpers/SyntaxFormattingHelper.cs @@ -30,6 +30,58 @@ internal static class SyntaxFormattingHelper "0xF0", "0xF1", "0xF2", "0xF3", "0xF4", "0xF5", "0xF6", "0xF7", "0xF8", "0xF9", "0xFA", "0xFB", "0xFC", "0xFD", "0xFE", "0xFF" }; + /// + /// Writes a formatted expression to initialize a with a given content. + /// + /// The input byte content to serialize. + /// The instance to write the expressions to. + /// + /// This function will write raw byte initialization expressions, such as: + /// [1, 2, 3, 4, 5] => 0x01, 0x02, 0x03, 0x04, 0x05. + /// + public static void WriteByteArrayInitializationExpressions(ReadOnlySpan bytecode, IndentedTextWriter writer) + { + if (bytecode.Length == 0) + { + return; + } + + // Calculate the buffer size: + // - 4 characters per item (eg. "0x00") + // - 2 characters between each pair of items (ie. ", ") + int length = (bytecode.Length * 4) + ((bytecode.Length - 1) * 2); + + // Reserve the space and get a span into the writer buffer + Span span = writer.Advance(length); + + // Cache the value expressions to avoid accessing the static fields multiple times + ReadOnlySpan expressions = FormattedBytes.AsSpan(); + + // First write the first item (which has no leading separator) + expressions[0].AsSpan().CopyTo(span); + + // Special case: stop early if there's only one element + if (bytecode.Length == 1) + { + return; + } + + // Advance the span to right past the item we've already written. + // This is so that each new item can assume it's starting from 0. + span = span.Slice(4); + + // Loop over all remaining items, and add the separator and encoded value. + // Then slice the remaining span so following items can repeat the same. + foreach (byte b in bytecode.Slice(1)) + { + span[0] = ','; + span[1] = ' '; + expressions[b].AsSpan().CopyTo(span.Slice(2)); + + span = span.Slice(6); + } + } + /// /// Creates a formatted expression to initialize a with a given content. ///