{"record":{"id":"a710199ae10922ee","repo":"XINCGer/Unity3DTraining","slug":"did-not-write-as-much-data-as-expected","errorCode":null,"errorMessage":"Did not write as much data as expected.","messagePattern":"Did not write as much data as expected\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"NetWorkAndResources/Socket_Protobuff/Assets/Plugins/Google.Protobuf/CodedOutputStream.cs","lineNumber":736,"sourceCode":"        public void Flush()\n        {\n            if (output != null)\n            {\n                RefreshBuffer();\n            }\n        }\n\n        /// <summary>\n        /// Verifies that SpaceLeft returns zero. It's common to create a byte array\n        /// that is exactly big enough to hold a message, then write to it with\n        /// a CodedOutputStream. Calling CheckNoSpaceLeft after writing verifies that\n        /// the message was actually as big as expected, which can help bugs.\n        /// </summary>\n        public void CheckNoSpaceLeft()\n        {\n            if (SpaceLeft != 0)\n            {\n                throw new InvalidOperationException(\"Did not write as much data as expected.\");\n            }\n        }\n\n        /// <summary>\n        /// If writing to a flat array, returns the space left in the array. Otherwise,\n        /// throws an InvalidOperationException.\n        /// </summary>\n        public int SpaceLeft\n        {\n            get\n            {\n                if (output == null)\n                {\n                    return limit - position;\n                }\n                else\n                {\n                    throw new InvalidOperationException(","sourceCodeStart":718,"sourceCodeEnd":754,"githubUrl":"https://github.com/XINCGer/Unity3DTraining/blob/016f98412ea5e11756b286736f479b66ab6216d5/NetWorkAndResources/Socket_Protobuff/Assets/Plugins/Google.Protobuf/CodedOutputStream.cs#L718-L754","documentation":"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.","triggerScenarios":"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.","commonSituations":"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).","solutions":["Recalculate the buffer size with msg.CalculateSize() immediately before serializing the same, unmodified instance.","Resize/trim the buffer: if SpaceLeft > 0 after writing, slice the buffer to position via SpaceLeft or use Buffer.BlockCopy to the exact size.","Only call CheckNoSpaceLeft() when the buffer was sized exactly from the same message state.","Prefer message.ToByteArray(), which sizes the array internally and never leaves slack."],"exampleFix":"// before\nvar buf = new byte[1024];\nvar cos = new CodedOutputStream(buf);\nmsg.WriteTo(cos);\ncos.CheckNoSpaceLeft(); // throws: 1024 - written bytes remain\n// after\nvar buf = new byte[msg.CalculateSize()];\nvar cos = new CodedOutputStream(buf);\nmsg.WriteTo(cos);\ncos.CheckNoSpaceLeft(); // now exact","handlingStrategy":"validation","validationCode":"var expected = msg.CalculateSize();\nvar cos = new CodedOutputStream(new byte[expected]);\nmsg.WriteTo(cos);\nif (cos.SpaceLeft != 0) throw new InvalidOperationException($\"Wrote {expected - cos.SpaceLeft} of {expected} bytes\");","typeGuard":"bool WroteExactly(int expectedBytes, CodedOutputStream cos) => cos.SpaceLeft == 0 && expectedBytes > 0;","tryCatchPattern":"try { cos.CheckNoSpaceLeft(); } catch (InvalidOperationException ex) { logger.LogError(ex, \"Size estimate != written bytes; message mutated between CalculateSize and WriteTo?\"); }","preventionTips":["Call CalculateSize() and WriteTo() on the same, unmodified message instance.","Use ToByteArray() to eliminate size/actual mismatches entirely.","Don't call CheckNoSpaceLeft() on stream-backed writers or buffers with intentional slack."],"tags":["protobuf","buffer","serialization"],"backgroundTag":"internal-invariant-violation","analyzedSha":"016f98412ea5e11756b286736f479b66ab6216d5","analyzedAt":"2026-09-12T01:08:58.711Z","contentChangedAt":"2026-09-12T01:08:58.711Z","schemaVersion":2},"datasetVersion":"2026-09-16T09:17:16.951Z"}