title: Handling dynamic-sized structs from byte sequence
body: <p>I'm dealing with packet parsing from network stream. The sending side is already implemented, and i'm only implementing client-side, so data should be parsed as-is. Previously all packets were const-sized, so I did it this way:</p>
  <pre><code>[StructLayout(LayoutKind.Sequential, Pack = 1)]
  public unsafe ref struct MyConstSizedStruct
  {
      //example structure
      public uint Data1;
      public byte Data2;
      public fixed byte Version[6];
  }
  </code></pre>
  <p>So the size of this is 4 + 1 + 6 = 11. Now I receive data to buffer and point it to a structure.</p>
  <pre><code>public unsafe void HandleMyConstSizedStruct(ushort length, byte[] data)
  {
      MyConstSizedStruct pkt;
      fixed (byte* ptr = &amp;data[0])
          pkt = *(MyConstSizedStruct*)ptr;
      //dealing with data
  }
  </code></pre>
  <p>At this point everything was ok, but now I got something more complicated:</p>
  <pre><code>[StructLayout(LayoutKind.Sequential, Pack = 1)]
  public unsafe struct MyDynamicSizedStruct
  {
      public uint Data1;
      public uint Data2;
      //here we have null-terminated utf-8 string of unknown length
      public char* User;
      public uint Data3;
      public uint Data4;
      public byte Data5;
      public byte[] RestOfData;
  }
  </code></pre>
  <p>So the problem is: now the packet is dynamically-sized, the size is received as a prefix ushort from network, but simple casting doesn't work because:</p>
  <ol>
  <li>Null-terminated string</li>
  <li>byte[] is considered a managed type, so now struct is considered as managed also, so I can't cast it</li>
  </ol>
  <p>So is there a nice way to interpret such structure, or I should deal with BinaryReader for this particular case?</p>
  <p><strong>Edit:</strong> some ideas:</p>
  <ol>
  <li>The offset of <code>char*</code> is always 8, so we can calculate the length of char buffer as indexof zero-byte, starting at 8.</li>
  <li>Somehow replace <code>char*</code> with <code>Span&lt;char&gt;</code> to set a length of this buffer in a struct? Or shift Data3 by calculated offset possible with some pointer assigning?</li>
  <li>After setting the correct padding of char buffer, reading byte[] array shouldn't be a problem, since we know the total size, we can do <code>totalsize - 17 /*size of all DataX*/ - /*char size*/</code> to get byte[] size</li>
  </ol>