|
| 1 | +namespace CStructSharp.Generators.Tests; |
| 2 | + |
| 3 | +using System; |
| 4 | +using Microsoft.CodeAnalysis.CSharp; |
| 5 | + |
| 6 | +/// <summary>Checks that signed-byte arrays compile and retain their values across supported compiler hosts.</summary> |
| 7 | +[TestClass] |
| 8 | +public class CompilerCompatibilityTests |
| 9 | +{ |
| 10 | + /// <summary>Compiles fixed and counted arrays, then checks signed values and exact serialized bytes.</summary> |
| 11 | + /// <param name="languageVersion">The consumer language version, independent of the generator's build language.</param> |
| 12 | + [TestMethod] |
| 13 | + [DataRow(LanguageVersion.CSharp12)] |
| 14 | +#if MODERN_ROSLYN |
| 15 | + [DataRow(LanguageVersion.CSharp14)] |
| 16 | +#endif |
| 17 | + public void SignedByteArrays_CompileAndRoundTrip(LanguageVersion languageVersion) |
| 18 | + { |
| 19 | + const string Source = """ |
| 20 | + using CStructSharp; |
| 21 | + namespace Compatibility; |
| 22 | + [CStructLayout("struct root { int8 fixedValues[4]; uint8 count; int8 countedValues[count]; };", Root = "root")] |
| 23 | + public static partial class Packet |
| 24 | + { |
| 25 | + /// <summary>Checks decoding and returns the encoded bytes for an exact round trip.</summary> |
| 26 | + public static byte[] Probe(byte[] bytes) |
| 27 | + { |
| 28 | + var value = Parse(bytes); |
| 29 | + if (value.FixedValues[0] != -128 || value.FixedValues[1] != -1 || |
| 30 | + value.FixedValues[2] != 0 || value.FixedValues[3] != 127 || |
| 31 | + value.CountedValues.Length != value.Count) |
| 32 | + throw new System.InvalidOperationException("Incorrect fixed array or count."); |
| 33 | + for (int i = 0; i < value.CountedValues.Length; i++) |
| 34 | + if (value.CountedValues[i] != value.FixedValues[i]) |
| 35 | + throw new System.InvalidOperationException("Incorrect counted array."); |
| 36 | + return Serialize(value); |
| 37 | + } |
| 38 | + } |
| 39 | + """; |
| 40 | + Type packet = GeneratorRunner.Run(Source, languageVersion: languageVersion).AssertClean().Load().GetType("Compatibility.Packet")!; |
| 41 | + byte[][] inputs = [[128, 255, 0, 127, 4, 128, 255, 0, 127], [128, 255, 0, 127, 0]]; |
| 42 | + foreach (byte[] input in inputs) |
| 43 | + { |
| 44 | + byte[] output = (byte[])packet.GetMethod("Probe")!.Invoke(null, [input])!; |
| 45 | + CollectionAssert.AreEqual(input, output); |
| 46 | + } |
| 47 | + } |
| 48 | +} |
0 commit comments