internal void Write(byte[] list, BinaryObject obj, ref int index) { list[index] = (byte)obj.Type; index++; var keyLenBytes = BitConverter.GetBytes(obj.Key.Length); Array.Copy(keyLenBytes, 0, list, index, keyLenBytes.Length); index += keyLenBytes.Length; var keyBytes = Encoding.UTF8.GetBytes(obj.Key); Array.Copy(keyBytes, 0, list, index, keyBytes.Length); index += keyBytes.Length; if (obj.Type != BinaryObject.BinaryTypes.Object) { int objLength = obj.ValueLength; var dataLenBytes = BitConverter.GetBytes(objLength); Array.Copy(dataLenBytes, 0, list, index, dataLenBytes.Length); index += dataLenBytes.Length; if (obj.Type != BinaryObject.BinaryTypes.ByteArray) { var dataBytes = Encoding.UTF8.GetBytes(obj.Value); Array.Copy(dataBytes, 0, list, index, dataBytes.Length); index += dataBytes.Length; } else { Array.Copy(obj.Raw, 0, list, index, obj.Raw.Length); index += obj.Raw.Length; } } else { int objLength = obj.ValueLength; var objLenBytes = BitConverter.GetBytes(objLength); Array.Copy(objLenBytes, 0, list, index, objLenBytes.Length); index += objLenBytes.Length; if (objLength > 0) { for (int i = 0; i < obj.Count; i++) Write(list, obj[i], ref index); } } }
internal int Read(BinaryObject currentObject, byte[] bytes, int index) { int offset = 0; byte type = bytes[index]; offset += 1; int keyLength = BitConverter.ToInt32(bytes, index + offset); offset += 4; string key = Encoding.UTF8.GetString(bytes, index + offset, keyLength); offset += keyLength; int valLength = BitConverter.ToInt32(bytes, index + offset); offset += 4 + valLength; BinaryObject obj = null; if (type == (byte)BinaryObject.BinaryTypes.Object) { obj = new BinaryObject(key); int innerIndex = index + offset - valLength; while (innerIndex < index + offset) innerIndex += Read(obj, bytes, innerIndex); } else { if (type != (byte)BinaryFormatter.BinaryObject.BinaryTypes.ByteArray) { string val = Encoding.UTF8.GetString(bytes, index + offset - valLength, valLength); obj = new BinaryObject(key, val); } else { byte[] val = new byte[valLength]; Array.Copy(bytes, index + offset - valLength, val, 0, val.Length); obj = new BinaryObject(key, val); } } if (currentObject == null) _items.Add(obj); else currentObject.Add(obj); return offset; }