public virtual byte[] Serialize(Message message)
 {
     var writer = new DatagramWriter();
     writer.Write(Message.Version, Message.VersionBits);
     writer.Write((int) message.Type, Message.TypeBits);
     writer.Write(message.OptionCount, Message.OptionCountBits);
     writer.Write((int) message.Code, Message.CodeBits);
     writer.Write(message.Id, Message.IdBits);
     writer.WriteBytes(GetOptions(message.Options));
     writer.WriteBytes(message.Payload);
     return writer.GetBytes();
 }
        private static byte[] GetOptions(IEnumerable<Option> options)
        {
            var writer = new DatagramWriter();
            var lastOptionNumber = 0;

            foreach (var option in options) {
                var delta = (int) option.Number - lastOptionNumber;
                var length = option.Value.Length;

                if (length <= Message.MaxOptionLengthBase) {
                    writer.Write(delta, Message.OptionDeltaBits);
                    writer.Write(length, Message.OptionLengthBits);
                }
                else {
                    const int baseLength = Message.MaxOptionLengthBase + 1;
                    writer.Write(delta, Message.OptionDeltaBits);
                    writer.Write(baseLength, Message.OptionLengthBits);
                    writer.Write(length - baseLength, Message.OptionLengthExtendedBits);
                }

                writer.WriteBytes(option.Value);
                lastOptionNumber = (int) option.Number;
            }

            return writer.GetBytes();
        }