diff --git a/packages/GameCult.Thing.Contract/Command.cs b/packages/GameCult.Thing.Contract/Command.cs index 8b217a5..dbeff22 100644 --- a/packages/GameCult.Thing.Contract/Command.cs +++ b/packages/GameCult.Thing.Contract/Command.cs @@ -113,7 +113,7 @@ public sealed class RecordPayload public RecordPayload(string schema, ReadOnlyMemory bytes) { Schema = ThingDomain.Present(schema, "Schema"); - Bytes = bytes.ToArray(); + Bytes = ThingDomain.Present(bytes, "Bytes").ToArray(); } } diff --git a/packages/GameCult.Thing.Contract/Domain.cs b/packages/GameCult.Thing.Contract/Domain.cs index ca23b16..0239cfe 100644 --- a/packages/GameCult.Thing.Contract/Domain.cs +++ b/packages/GameCult.Thing.Contract/Domain.cs @@ -49,6 +49,15 @@ public static class ThingDomain public static T Present(T? value, string slot) where T : class => value ?? throw new ThingDomainException(slot, "present"); + /// + /// A required byte slot. A null on the wire decodes to a default view with no backing store, so a view that is + /// empty and backed by nothing is refused as nil; an empty array is a present, empty payload. + /// + public static ReadOnlyMemory Present(ReadOnlyMemory value, string slot) => + value.IsEmpty && !System.Runtime.InteropServices.MemoryMarshal.TryGetArray(value, out _) + ? throw new ThingDomainException(slot, "present") + : value; + /// /// A required list slot: a read-only copy, so the caller's list cannot change the value afterwards. A null list or /// a null item is refused naming the slot. diff --git a/tests/GameCult.Thing.Contract.Tests/ReadOnlyListTests.cs b/tests/GameCult.Thing.Contract.Tests/ReadOnlyListTests.cs index 2637197..0d8a69f 100644 --- a/tests/GameCult.Thing.Contract.Tests/ReadOnlyListTests.cs +++ b/tests/GameCult.Thing.Contract.Tests/ReadOnlyListTests.cs @@ -163,4 +163,17 @@ public sealed class ReadOnlyListTests Assert.That(slice.Bytes.ToArray(), Is.EqualTo(new byte[] { 5, 6 })); Assert.That(System.Runtime.InteropServices.MemoryMarshal.TryGetArray(payload.Bytes, out var segment) && ReferenceEquals(segment.Array, buffer), Is.False); } + + [Test] + public void ANilPayloadIsRefusedAndAnEmptyOneIsKeptThroughTheWire() + { + var error = Assert.Throws(() => new RecordPayload("s", default))!; + Assert.That(error.Domain, Is.EqualTo("Bytes")); + Assert.That(error.Bound, Is.EqualTo("present")); + + var empty = new CommandInvocation("i", "k", 1, "go", new RecordPayload("s", Array.Empty()), new List(), "c", "t", null); + var decoded = (CommandInvocation)Wire.Read(typeof(CommandInvocation), Wire.Write(empty)); + Assert.That(decoded.Payload.Bytes.IsEmpty, Is.True); + Assert.That(Wire.Write(decoded), Is.EqualTo(Wire.Write(empty))); + } }