XINCGer/Unity3DTraining · error · InvalidOperationException

Did not write as much data as expected.

Error message

Did not write as much data as expected.

What it means

CheckNoSpaceLeft() is a debugging/validation aid: after writing into a fixed buffer, it verifies that every byte was consumed (SpaceLeft == 0). If bytes remain, the written size did not match the buffer size, indicating the size estimate and actual write diverged, so InvalidOperationException is thrown.

Solutions

  1. Recalculate the buffer size with msg.CalculateSize() immediately before serializing the same, unmodified instance.
  2. Resize/trim the buffer: if SpaceLeft > 0 after writing, slice the buffer to position via SpaceLeft or use Buffer.BlockCopy to the exact size.
  3. Only call CheckNoSpaceLeft() when the buffer was sized exactly from the same message state.
  4. Prefer message.ToByteArray(), which sizes the array internally and never leaves slack.

Example fix

// before
var buf = new byte[1024];
var cos = new CodedOutputStream(buf);
msg.WriteTo(cos);
cos.CheckNoSpaceLeft(); // throws: 1024 - written bytes remain
// after
var buf = new byte[msg.CalculateSize()];
var cos = new CodedOutputStream(buf);
msg.WriteTo(cos);
cos.CheckNoSpaceLeft(); // now exact
Defensive patterns

Strategy: validation

Validate before calling

var expected = msg.CalculateSize();
var cos = new CodedOutputStream(new byte[expected]);
msg.WriteTo(cos);
if (cos.SpaceLeft != 0) throw new InvalidOperationException($"Wrote {expected - cos.SpaceLeft} of {expected} bytes");

Type guard

bool WroteExactly(int expectedBytes, CodedOutputStream cos) => cos.SpaceLeft == 0 && expectedBytes > 0;

Try / catch

try { cos.CheckNoSpaceLeft(); } catch (InvalidOperationException ex) { logger.LogError(ex, "Size estimate != written bytes; message mutated between CalculateSize and WriteTo?"); }

Prevention

When it happens

Trigger: Calling CheckNoSpaceLeft() on a CodedOutputStream backed by a byte[] that was sized larger than the message actually written — e.g. buffer allocated from CalculateSize() but fields modified in between, or the buffer pre-sized to a fixed capacity.

Common situations: Buffer pooling where a previous larger message's buffer is reused for a smaller message; computing size with one message instance and serializing a mutated copy; calling CheckNoSpaceLeft() on a stream-backed writer (unsupported use).

Understand the failure class

Background: "This is a bug, please report it": internal invariant violations, unreachable panics, and SNH errors explained — this error's family across 47 libraries.

Related errors


AI-assisted analysis of XINCGer/Unity3DTraining@016f98412e (2026-09-12). Data as JSON: /api/errors/a710199ae10922ee. Report an issue: GitHub.

Appendix: source

Thrown at NetWorkAndResources/Socket_Protobuff/Assets/Plugins/Google.Protobuf/CodedOutputStream.cs:736

        public void Flush()
        {
            if (output != null)
            {
                RefreshBuffer();
            }
        }

        /// <summary>
        /// Verifies that SpaceLeft returns zero. It's common to create a byte array
        /// that is exactly big enough to hold a message, then write to it with
        /// a CodedOutputStream. Calling CheckNoSpaceLeft after writing verifies that
        /// the message was actually as big as expected, which can help bugs.
        /// </summary>
        public void CheckNoSpaceLeft()
        {
            if (SpaceLeft != 0)
            {
                throw new InvalidOperationException("Did not write as much data as expected.");
            }
        }

        /// <summary>
        /// If writing to a flat array, returns the space left in the array. Otherwise,
        /// throws an InvalidOperationException.
        /// </summary>
        public int SpaceLeft
        {
            get
            {
                if (output == null)
                {
                    return limit - position;
                }
                else
                {
                    throw new InvalidOperationException(

View on GitHub (pinned to 016f98412e)