public ReadOnlyMemory<byte> SetKey(IKeyFormatter formatter, string key) { #if DEBUG Debug.Assert(!didKey, "Key can only be set once"); Debug.Assert(!didBody, "Key must be set before accessing the body"); didKey = true; #endif AllocateExtras(); var start = bodyBuilder.Mark(); var preKey = bodyBuilder.Length; Debug.Assert(preKey == extra.Length, "unexpected data was written between extra & key"); formatter.Serialize(bodyBuilder, key); var end = bodyBuilder.Mark(); var tmpLength = bodyBuilder.Length - preKey; if (tmpLength > Protocol.MaxKeyLength) throw new ArgumentException($"Key is too long; was {tmpLength}, maximum is {Protocol.MaxKeyLength}"); keyLength = (ushort)tmpLength; var seq = bodyBuilder.Slice(start, end); if (seq.IsSingleSegment) { Debug.Assert(seq.First.Length == keyLength); return seq.First; } return seq.ToArray(); }