/// <summary> /// Write a nullable long as variable size array. The smaller the value, the less byte will be needed. /// </summary> public static int WriteVNInt(this Stream ins, long?nl) { int count = 0; if (nl.HasValue) { var l = nl.Value; bool isNeg = l < 0; if (isNeg) { l = ~l; } var ul = unchecked ((ulong)l); bool first = true; do { byte part; if (first) { first = false; part = (byte)(ul & 0x1F); part |= 0x40; if (isNeg) { part |= 0x20; } ul = ul >> 5; } else { part = (byte)(ul & 0x7F); ul = ul >> 7; } if (ul > 0) { part |= 0x80; } ins?.WriteByte(part); count++; }while (ul > 0); } else { ins?.WriteByte(0); count++; } return(count); }
public override void WriteByte(byte value) { lock (this) { BaseStream?.WriteByte(value); Buffer.WriteByte(value); } }
public static void Write(Stream stream, byte type, Stream exportStream) { stream.WriteByte(type); stream.Write(NetworkConverter.GetBytes((int)exportStream.Length), 0, 4); byte[] buffer = null; try { buffer = _bufferManager.TakeBuffer(1024 * 4); int length = 0; while ((length = exportStream.Read(buffer, 0, buffer.Length)) > 0) { stream.Write(buffer, 0, length); } } finally { if (buffer != null) { _bufferManager.ReturnBuffer(buffer); } } }
public void EndMessage(Stream stream) { SDebug.Assert(message != RemoteMessage.Invalid); // Write message header stream.WriteByte((byte)message); uint len = (uint)packet.Length; stream.WriteByte((byte)(len & 0xFF)); stream.WriteByte((byte)((len >> 8) & 0xFF)); stream.WriteByte((byte)((len >> 16) & 0xFF)); stream.WriteByte((byte)((len >> 24) & 0xFF)); // Write the message packet.Position = 0; Utils.CopyToStream(packet, stream, buffer, (int)packet.Length); message = RemoteMessage.Invalid; }
public static bool WriteBeyondEndTest(Stream s) { Console.WriteLine("Write Beyond End test on "+s.GetType().Name); FileStream fs = s as FileStream; if (fs != null) Console.WriteLine("FileStream type is: "+(fs.IsAsync ? "asynchronous" : "synchronous")); long origLength = s.Length; byte[] bytes = new byte[10]; for(int i=0; i<bytes.Length; i++) bytes[i] = (byte) i; int spanPastEnd = 5; s.Seek(spanPastEnd, SeekOrigin.End); if (s.Position != s.Length + spanPastEnd) throw new Exception("Position is incorrect! Seek(5, SeekOrigin.End) should leave us at s.Length + spanPastEnd ("+(s.Length + spanPastEnd)+"), but got: "+s.Position); Console.WriteLine("Original Length: "+origLength); s.Write(bytes, 0, bytes.Length); long pos = s.Position; if (pos != origLength + spanPastEnd + bytes.Length) throw new Exception(String.Format("After asynchronously writing beyond end of the stream, position is now incorrect! origLength: {0} pos: {1}", origLength, pos)); if (s.Length != origLength + spanPastEnd + bytes.Length) throw new Exception(String.Format("After asynchronously writing beyond end of the stream, Length is now incorrect! origLength: {0} pos: {1}", origLength, pos)); WritePastEndHelper(s, bytes, origLength, spanPastEnd, false); origLength = s.Length; s.Position = s.Length + spanPastEnd; s.WriteByte(0x42); long expected = origLength + spanPastEnd + 1; if (s.Position != expected) { iCountErrors++ ; throw new Exception("After WriteByte, Position was wrong! got: "+s.Position+" expected: "+expected); } if (s.Length != expected) { iCountErrors++ ; throw new Exception("After WriteByte, Length was wrong! got: "+s.Length+" expected: "+expected); } origLength = s.Length; s.Position = s.Length + spanPastEnd; IAsyncResult ar = s.BeginWrite(bytes, 0, bytes.Length, null, null); s.EndWrite(ar); pos = s.Position; if (pos != origLength + spanPastEnd + bytes.Length) { iCountErrors++ ; throw new Exception(String.Format("After writing beyond end of the stream, position is now incorrect! origLength: {0} pos: {1}", origLength, pos)); } if (s.Length != origLength + spanPastEnd + bytes.Length) { iCountErrors++; throw new Exception(String.Format("After writing beyond end of the stream, Length is now incorrect! origLength: {0} pos: {1}", origLength, pos)); } WritePastEndHelper(s, bytes, origLength, spanPastEnd, true); return true; }
/// <summary> /// Write a nullable long as variable size array. The smaller the value, the less byte will be needed. /// </summary> public static int WriteVNUInt(this Stream ins, ulong?nul) { int count = 0; if (nul.HasValue) { var ul = nul.Value; bool first = true; do { byte part; if (first) { first = false; part = (byte)(ul & 0x3F); part |= 0x40; ul = ul >> 6; } else { part = (byte)(ul & 0x7F); ul = ul >> 7; } if (ul > 0) { part |= 0x80; } ins?.WriteByte(part); count++; }while (ul > 0); } else { ins?.WriteByte(0); count++; } return(count); }
public static void ByteTest(Stream s) { Console.WriteLine(" (01) ByteTest on "+s.GetType( ).Name); int size = 0x25000; int r; for(int i=0;i<size;i++) s.WriteByte((byte)i); s.Position=0; for(int i=0;i<size;i++) { r=s.ReadByte( ); if(r!=i%256) throw new Exception("Didn't get the correct value for i at: " +i+" expected: "+(i%256)+" got: "+r); } }
public static void SpanTest(Stream s) { Console.WriteLine(" (02) SpanTest on "+s.GetType( ).Name); // If a read request spans across two buffers, make sure we get the data // back in one read request, since it would be silly to not do so. This // caught a bug in BufferedStream, which was missing a case to handle the // second read request. // Here's a legend. The space is at the 8K buffer boundary. // /-------------------|------- -------|------------------\ // First for loop Read(bytes) Second for loop int max; int r; byte[] bytes; int numBytes; const int bufferSize = 8*(1<<10); for(int i=0;i<bufferSize*2;i++) s.WriteByte((byte)(i % 256)); s.Position=0; max = bufferSize-(bufferSize>>2); for(int i=0;i<max;i++) { r=s.ReadByte( ); if(r!=i%256) throw new Exception("Didn't get the correct value for i at: " +i+" expected: "+(i%256)+" got: "+r); } bytes = new byte[bufferSize>>1]; numBytes=s.Read(bytes,0,bytes.Length); if (numBytes!=bytes.Length) throw new Exception("While reading into a byte[] spanning a buffer starting at position " +max+", didn't get the right number of bytes! asked for: " +bytes.Length+" got: "+numBytes); for(int i=0;i<bytes.Length;i++) { if(bytes[i]!=((i+max)%256)) throw new Exception("When reading in an array that spans across two buffers, "+ "got an incorrect value at index: "+i+ " expected: "+((i+max)%256)+" got: "+bytes[i]); } // Read rest of data for(int i=0;i<max;i++) { r=s.ReadByte( ); if(r!=(i+max+bytes.Length)%256) throw new Exception("While reading the last part of the buffer, " +"didn't get the correct value for i at: "+i +" expected: "+((i+max+bytes.Length)%256)+" got: "+r); } }
/// <summary> /// Write ulong as variable size array. The smaller the value, the less byte will be needed. /// </summary> public static int WriteVUInt(this Stream ins, ulong ul) { int count = 0; do { var part = (byte)(ul & 0x7F); if (ul > 0x7F) { part |= 0x80; } ul = ul >> 7; ins?.WriteByte(part); count++; }while (ul > 0); return(count); }
public CompressedOutputStream(Stream baseStream, CompressionType compressionType) { _baseStream = baseStream; _compressionType = compressionType; _baseStream.WriteByte((byte)_compressionType); switch (_compressionType) { case CompressionType.NONE: _compressor = _baseStream; break; case CompressionType.LZF: _compressor = new LzfOutputStream(_baseStream); break; case CompressionType.BZIP2: _compressor = new BZip2OutputStream(_baseStream); break; } }
/// <summary> /// Write long as variable size array. The smaller the value, the less byte will be needed. /// </summary> public static int WriteVInt(this Stream ins, long l) { bool isNeg = l < 0; if (isNeg) { l = ~l; } var ul = unchecked ((ulong)l); int count = 0; bool first = true; do { byte part; if (first) { first = false; part = (byte)(ul & 0x3F); if (isNeg) { part |= 0x40; } ul = ul >> 6; } else { part = (byte)(ul & 0x7F); ul = ul >> 7; } if (ul > 0) { part |= 0x80; } ins?.WriteByte(part); count++; }while (ul > 0); return(count); }
public static void Write(Stream stream, byte type, string value) { Encoding encoding = _threadLocalEncoding.Value; byte[] buffer = null; try { buffer = _bufferManager.TakeBuffer(encoding.GetMaxByteCount(value.Length)); var length = encoding.GetBytes(value, 0, value.Length, buffer, 0); stream.WriteByte(type); stream.Write(NetworkConverter.GetBytes(length), 0, 4); stream.Write(buffer, 0, length); } finally { if (buffer != null) { _bufferManager.ReturnBuffer(buffer); } } }
public override void SendMessage(byte data, string deviceId) { if (outStream == null) { try { outStream = btSocket.OutputStream; } catch { throw new CantOpenStream(); } } try { outStream?.WriteByte(data); } catch { throw new CantWriteData(); } }
/// <summary>Serialize the instance into the stream</summary> internal static void Serialize(Stream stream, LocalFeatures instance) { instance.BeforeSerialize(); BinaryWriter bw = new BinaryWriter(stream); // Key for field: 1, Varint stream.WriteByte(8); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt64(stream,(ulong)instance.Uptime.Ticks); // Key for field: 2, Varint stream.WriteByte(16); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt64(stream,(ulong)instance.DueDate.Ticks); // Key for field: 3, Fixed64 stream.WriteByte(25); bw.Write(instance.Amount); if (instance.Denial != null) { // Key for field: 4, LengthDelimited stream.WriteByte(34); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(instance.Denial)); } if (instance.Secret != null) { // Key for field: 5, LengthDelimited stream.WriteByte(42); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(instance.Secret)); } if (instance.Internal != null) { // Key for field: 6, LengthDelimited stream.WriteByte(50); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(instance.Internal)); } if (instance.PR != null) { // Key for field: 7, LengthDelimited stream.WriteByte(58); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(instance.PR)); } if (instance.TestingReadOnly != null) { // Key for field: 8, LengthDelimited stream.WriteByte(66); using (var ms8 = new MemoryStream()) { Mine.MyMessageV1.Serialize(ms8, instance.TestingReadOnly); // Length delimited byte array uint ms8Length = (uint)ms8.Length; global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, ms8Length); stream.Write(ms8.GetBuffer(), 0, (int)ms8Length); } } if (instance.MyInterface == null) throw new ArgumentNullException("MyInterface", "Required by proto specification."); // Key for field: 9, LengthDelimited stream.WriteByte(74); using (var ms9 = new MemoryStream()) { LocalFeatureTest.InterfaceTestSerializer.Serialize(ms9, instance.MyInterface); // Length delimited byte array uint ms9Length = (uint)ms9.Length; global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, ms9Length); stream.Write(ms9.GetBuffer(), 0, (int)ms9Length); } // Key for field: 10, LengthDelimited stream.WriteByte(82); using (var ms10 = new MemoryStream()) { LocalFeatureTest.StructTest.Serialize(ms10, instance.MyStruct); // Length delimited byte array uint ms10Length = (uint)ms10.Length; global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, ms10Length); stream.Write(ms10.GetBuffer(), 0, (int)ms10Length); } // Key for field: 11, LengthDelimited stream.WriteByte(90); using (var ms11 = new MemoryStream()) { TestB.ExternalStructSerializer.Serialize(ms11, instance.MyExtStruct); // Length delimited byte array uint ms11Length = (uint)ms11.Length; global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, ms11Length); stream.Write(ms11.GetBuffer(), 0, (int)ms11Length); } if (instance.MyExtClass != null) { // Key for field: 12, LengthDelimited stream.WriteByte(98); using (var ms12 = new MemoryStream()) { TestB.ExternalClassSerializer.Serialize(ms12, instance.MyExtClass); // Length delimited byte array uint ms12Length = (uint)ms12.Length; global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, ms12Length); stream.Write(ms12.GetBuffer(), 0, (int)ms12Length); } } // Key for field: 13, Varint stream.WriteByte(104); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt64(stream,(ulong)instance.MyEnum); }
/// <summary>Serialize the instance into the stream</summary> public static void Serialize(Stream stream, UninterpretedOption instance) { BinaryWriter bw = new BinaryWriter(stream); if (instance.Name != null) { foreach (var i2 in instance.Name) { // Key for field: 2, LengthDelimited stream.WriteByte(18); using (var ms2 = new MemoryStream()) { Google.protobuf.UninterpretedOption.NamePart.Serialize(ms2, i2); // Length delimited byte array uint ms2Length = (uint)ms2.Length; global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, ms2Length); stream.Write(ms2.GetBuffer(), 0, (int)ms2Length); } } } if (instance.IdentifierValue != null) { // Key for field: 3, LengthDelimited stream.WriteByte(26); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(instance.IdentifierValue)); } // Key for field: 4, Varint stream.WriteByte(32); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt64(stream, instance.PositiveIntValue); // Key for field: 5, Varint stream.WriteByte(40); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt64(stream,(ulong)instance.NegativeIntValue); // Key for field: 6, Fixed64 stream.WriteByte(49); bw.Write(instance.DoubleValue); if (instance.StringValue != null) { // Key for field: 7, LengthDelimited stream.WriteByte(58); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, instance.StringValue); } if (instance.AggregateValue != null) { // Key for field: 8, LengthDelimited stream.WriteByte(66); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(instance.AggregateValue)); } }
/// <summary>Serialize the instance into the stream</summary> public static void Serialize(Stream stream, SourceCodeInfo instance) { if (instance.LocationField != null) { foreach (var i1 in instance.LocationField) { // Key for field: 1, LengthDelimited stream.WriteByte(10); using (var ms1 = new MemoryStream()) { Google.protobuf.SourceCodeInfo.Location.Serialize(ms1, i1); // Length delimited byte array uint ms1Length = (uint)ms1.Length; global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, ms1Length); stream.Write(ms1.GetBuffer(), 0, (int)ms1Length); } } } }
/// <summary>Serialize the instance into the stream</summary> public static void Serialize(Stream stream, MessageOptions instance) { // Key for field: 1, Varint stream.WriteByte(8); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBool(stream, instance.MessageSetWireFormat); // Key for field: 2, Varint stream.WriteByte(16); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBool(stream, instance.NoStandardDescriptorAccessor); if (instance.UninterpretedOption != null) { foreach (var i999 in instance.UninterpretedOption) { // Key for field: 999, LengthDelimited stream.Write(new byte[]{186, 62}, 0, 2); using (var ms999 = new MemoryStream()) { Google.protobuf.UninterpretedOption.Serialize(ms999, i999); // Length delimited byte array uint ms999Length = (uint)ms999.Length; global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, ms999Length); stream.Write(ms999.GetBuffer(), 0, (int)ms999Length); } } } }
public static void WriteData(Stream s) { BinaryWriter bw; int offset = 10; byte[] bytes = new byte[256 + offset]; for (int i=0;i<256;i++) bytes[i+offset] = (byte)i; // Test reading & writing at an offset into the user array... s.Write(bytes,offset,bytes.Length-offset); // Test WriteByte methods. s.WriteByte(0); s.WriteByte(65); s.WriteByte(255); s.Flush( ); bw = new BinaryWriter(s); for(int i=0;i<1000;i++) bw.Write(i); bw.Write(false); bw.Write(true); for(char ch='A';ch<='Z';ch++) bw.Write(ch); for(short i=-32000;i<=32000;i+=1000) bw.Write(i); for(int i=-2000000000;i<=2000000000;i+=100000000) bw.Write(i); bw.Write(0x0123456789ABCDE7L); bw.Write(0x7EDCBA9876543210L); bw.Write("Hello world"); bw.Write(Math.PI); bw.Write((float)(-2.0*Math.PI)); bw.Flush( ); }
public static bool ReadWriteBufferSwitchTest(Stream s) { String writableStr = "read-only"; if(s.CanWrite) writableStr="read/write"; Console.WriteLine(" (05) ReadWriteBufferSwitch test for a "+writableStr+" "+s.GetType( ).Name); if(s.Length<8200) Console.WriteLine("ReadWriteBufferSwitchTest assumes stream len is at least 8200"); s.Position = 0; // Assume buffer size is 8192 for(int i=0;i<8192;i++) s.ReadByte( ); // Console.WriteLine(" (05) Pos: "+s.Position+" s.Length: "+s.Length); s.WriteByte(0); // Calling the position property will verify internal buffer state. if(8193!=s.Position) throw new Exception("Position should be 8193! Position: "+s.Position); s.ReadByte( ); return true; }
public static void WriteShort(Stream fs, byte flag, short val) { fs.WriteByte(flag); fs.Write(BitConverter.GetBytes(2), 0, 4); fs.Write(BitConverter.GetBytes(val), 0, 2); }
/// <summary> /// Writes a byte to the current position in the stream and advances the position within the stream by one byte. /// </summary> /// <param name="value">The byte to write to the stream.</param> public override void WriteByte(byte value) { innerStream.WriteByte(value); }
/// <summary> /// Encodes the image to the specified stream from the <see cref="Image{TPixel}"/>. /// </summary> /// <typeparam name="TPixel">The pixel format.</typeparam> /// <param name="image">The <see cref="Image{TPixel}"/> to encode from.</param> /// <param name="stream">The <see cref="Stream"/> to encode the image data to.</param> public void Encode <TPixel>(Image <TPixel> image, Stream stream) where TPixel : struct, IPixel <TPixel> { Guard.NotNull(image, nameof(image)); Guard.NotNull(stream, nameof(stream)); this.configuration = image.GetConfiguration(); ImageMetadata metadata = image.Metadata; GifMetadata gifMetadata = metadata.GetGifMetadata(); this.colorTableMode = this.colorTableMode ?? gifMetadata.ColorTableMode; bool useGlobalTable = this.colorTableMode == GifColorTableMode.Global; // Quantize the image returning a palette. IQuantizedFrame <TPixel> quantized; using (IFrameQuantizer <TPixel> frameQuantizer = this.quantizer.CreateFrameQuantizer <TPixel>(image.GetConfiguration())) { quantized = frameQuantizer.QuantizeFrame(image.Frames.RootFrame); } // Get the number of bits. this.bitDepth = ImageMaths.GetBitsNeededForColorDepth(quantized.Palette.Length).Clamp(1, 8); // Write the header. this.WriteHeader(stream); // Write the LSD. int index = this.GetTransparentIndex(quantized); this.WriteLogicalScreenDescriptor(metadata, image.Width, image.Height, index, useGlobalTable, stream); if (useGlobalTable) { this.WriteColorTable(quantized, stream); } // Write the comments. this.WriteComments(gifMetadata, stream); // Write application extension to allow additional frames. if (image.Frames.Count > 1) { this.WriteApplicationExtension(stream, gifMetadata.RepeatCount); } if (useGlobalTable) { this.EncodeGlobal(image, quantized, index, stream); } else { this.EncodeLocal(image, quantized, stream); } // Clean up. quantized?.Dispose(); // TODO: Write extension etc stream.WriteByte(GifConstants.EndIntroducer); }
public void WriteByte(byte val) // WriteByte(byte val) is directly or indirectly called from several methods thus exceptions thrown here can also be thrown in all those methods { m_stream.WriteByte(val); // throws IOException, NotSupportedException, ObjectDisposedException }
/// <summary>変換可能なオブジェクトをストリームに書き込む</summary> public void Write(object v) { if (v is byte) { Stream.WriteByte((byte)v); } else if (v is ushort) { Stream.Write(BitConverter.GetBytes((ushort)v), 0, 2); } else if (v is int) { Stream.Write(BitConverter.GetBytes((int)v), 0, 4); } else if (v is uint) { Stream.Write(BitConverter.GetBytes((uint)v), 0, 4); } else if (v is long) { Stream.Write(BitConverter.GetBytes((long)v), 0, 8); } else if (v is ulong) { Stream.Write(BitConverter.GetBytes((ulong)v), 0, 8); } else if (v is ICtrlCmdReadWrite) { ((ICtrlCmdReadWrite)v).Write(Stream, Version); } else if (v is DateTime) { var t = (DateTime)v; Write((ushort)t.Year); Write((ushort)t.Month); Write((ushort)t.DayOfWeek); Write((ushort)t.Day); Write((ushort)t.Hour); Write((ushort)t.Minute); Write((ushort)t.Second); Write((ushort)t.Millisecond); } else if (v is string) { byte[] a = Encoding.Unicode.GetBytes((string)v); Write(a.Length + 6); Stream.Write(a, 0, a.Length); Write((ushort)0); } else if (v is System.Collections.IList) { long lpos = Stream.Position; Write(0); Write(((System.Collections.IList)v).Count); foreach (object o in ((System.Collections.IList)v)) { Write(o); } long pos = Stream.Position; Stream.Seek(lpos, SeekOrigin.Begin); Write((int)(pos - lpos)); Stream.Seek(pos, SeekOrigin.Begin); } else { throw new ArgumentException(); } }
public void Write(Stream stream, String value, Int64 offset) { // 先用局部变量临时保存,因为每新读出来一段,就要全部加上去 var keys = new List <Int32>(); var values = new List <String>(); var start = stream.Position; var p = 0; var isRef = false; var ss = ("" + value).Split("."); for (var i = 0; i < ss.Length; i++) { isRef = false; // 如果已存在,则写引用 var name = String.Join(".", ss, i, ss.Length - i); if (Values.Contains(name)) { //stream.WriteByte(0xC0); //stream.WriteByte((Byte)this[name]); // 偏移量的标准公式是:(Cn-C0)*256+偏移 // 相对位置,注意超长位移(大于0xFF) var abp = this[name]; var ab = abp / 0xFF; abp = abp & 0xFF; stream.WriteByte((Byte)(0xC0 + ab)); stream.WriteByte((Byte)abp); // 之前的每个加上str for (var j = 0; j < values.Count; j++) { values[j] += "." + name; } // 使用引用的必然是最后一个 isRef = true; break; } // 否则,先写长度,后存入引用 p = (Int32)(stream.Position - start); var buffer = Encoding.UTF8.GetBytes(ss[i]); stream.WriteByte((Byte)buffer.Length); stream.Write(buffer, 0, buffer.Length); // 之前的每个加上str for (var j = 0; j < values.Count; j++) { values[j] += "." + ss[i]; } // 加入当前项 keys.Add((Int32)(offset + p)); values.Add(ss[i]); } if (!isRef) { stream.WriteByte((Byte)0); } for (var i = 0; i < keys.Count; i++) { Keys.Add(keys[i]); Values.Add(values[i]); } }
public void WriteBits(uint value, uint bitlength, bool finish = false) { var r11 = (int)(Position & 0xFFFFFFFF & 0x1F); int r8 = 1; int r10 = (0x20 - r11); r11 = (int)(bitlength - r10); var r9 = (int)xshiftseed; if (r11 >= 0) { r10--; uint r6 = value >> r11; r10 = r8 << r10; r10 = (int)((r10 << 1) & 0xFFFFFFFE); r10--; r6 &= (uint)r10; r10 = (int)(~r10 & xshiftseed); r9 = (int)(r6 | r10); xbaseStream.WriteInt32(r9, true); r10 = 0x20 - r11; r11 = r8 << r11; r11--; r8 = (int)(value << r10); r11 <<= r10; } else { r10 = (int)(bitlength - 1); r11 = -r11; r10 = r8 << r10; r10 = (int)((r10 << 1) & 0xFFFFFFFE); r8 = (int)(value << r11); r10--; r11 = r10 << r11; } r10 = r8 & r11; r11 = (~r11 & r9); xshiftseed = (uint)(r10 | r11); CurrentBit += bitlength; if (finish) { r11 = (int)(Position & 0xFFFFFFFF & 0x1F); r10 = (0x20 - r11); r8 = (int)(xshiftseed >> r10); if (r10 <= 8) { xbaseStream.WriteByte((byte)r8); } else if (r10 <= 0x10) { xbaseStream.WriteInt16((short)r8, true); } else if (r10 <= 0x18) { xbaseStream.WriteInt24(r8, true); } else if (r10 < 0x20) { xbaseStream.WriteInt24(r8, true); } } }
public static void WriteInt(Stream fs, byte flag, int num) { fs.WriteByte(flag); fs.Write(BitConverter.GetBytes(4), 0, 4); fs.Write(BitConverter.GetBytes(num), 0, 4); }
/// <summary>Serialize the instance into the stream</summary> public static void Serialize(Stream stream, MyMessageV1 instance) { // Key for field: 1, Varint stream.WriteByte(8); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt64(stream,(ulong)instance.FieldA); if (instance.PreservedFields != null) { foreach (var kv in instance.PreservedFields) { global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteKey(stream, kv.Key); stream.Write(kv.Value, 0, kv.Value.Length); } } }
/// <summary>Serialize the instance into the stream</summary> public static void Serialize(Stream stream, Nested instance) { if (instance.NestedData != null) { // Key for field: 1, LengthDelimited stream.WriteByte(10); using (var ms1 = new MemoryStream()) { Proto.test.Data.Serialize(ms1, instance.NestedData); // Length delimited byte array uint ms1Length = (uint)ms1.Length; global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, ms1Length); stream.Write(ms1.GetBuffer(), 0, (int)ms1Length); } } }
public async Task File_AllDataCopied( Func <string, Stream> createDestinationStream, bool useAsync, bool preRead, bool preWrite, bool exposeHandle, bool cancelable, int bufferSize, int writeSize, int numWrites) { // Create the expected data long totalLength = writeSize * numWrites; var expectedData = new byte[totalLength]; new Random(42).NextBytes(expectedData); // Write it out into the source file string srcPath = GetTestFilePath(); File.WriteAllBytes(srcPath, expectedData); string dstPath = GetTestFilePath(); using (FileStream src = new FileStream(srcPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None, bufferSize, useAsync)) using (Stream dst = createDestinationStream(dstPath)) { // If configured to expose the handle, do so. This influences the stream's need to ensure the position is in sync. if (exposeHandle) { _ = src.SafeFileHandle; } // If configured to "preWrite", do a write before we start reading. if (preWrite) { src.Write(new byte[] { 42 }, 0, 1); dst.Write(new byte[] { 42 }, 0, 1); expectedData[0] = 42; } // If configured to "preRead", read one byte from the source prior to the CopyToAsync. // This helps test what happens when there's already data in the buffer, when the position // isn't starting at zero, etc. if (preRead) { int initialByte = src.ReadByte(); if (initialByte >= 0) { dst.WriteByte((byte)initialByte); } } // Do the copy await src.CopyToAsync(dst, writeSize, cancelable?new CancellationTokenSource().Token : CancellationToken.None); dst.Flush(); // Make sure we're at the end of the source file Assert.Equal(src.Length, src.Position); // Verify the copied data dst.Position = 0; var result = new MemoryStream(); dst.CopyTo(result); byte[] actualData = result.ToArray(); Assert.Equal(expectedData.Length, actualData.Length); Assert.Equal <byte>(expectedData, actualData); } }
/// <summary>Serialize the instance into the stream</summary> public static void Serialize(Stream stream, MyMessageV2 instance) { BinaryWriter bw = new BinaryWriter(stream); // Key for field: 1, Varint stream.WriteByte(8); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt64(stream,(ulong)instance.FieldA); // Key for field: 2, Fixed64 stream.WriteByte(17); bw.Write(instance.FieldB); // Key for field: 3, Fixed32 stream.WriteByte(29); bw.Write(instance.FieldC); // Key for field: 4, Varint stream.WriteByte(32); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt64(stream,(ulong)instance.FieldD); // Key for field: 5, Varint stream.WriteByte(40); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt64(stream,(ulong)instance.FieldE); // Key for field: 6, Varint stream.WriteByte(48); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, instance.FieldF); // Key for field: 7, Varint stream.WriteByte(56); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt64(stream, instance.FieldG); // Key for field: 8, Varint stream.WriteByte(64); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteZInt32(stream, instance.FieldH); // Key for field: 9, Varint stream.WriteByte(72); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteZInt64(stream, instance.FieldI); // Key for field: 10, Fixed32 stream.WriteByte(85); bw.Write(instance.FieldJ); // Key for field: 11, Fixed64 stream.WriteByte(89); bw.Write(instance.FieldK); // Key for field: 12, Fixed32 stream.WriteByte(101); bw.Write(instance.FieldL); // Key for field: 13, Fixed64 stream.WriteByte(105); bw.Write(instance.FieldM); // Key for field: 14, Varint stream.WriteByte(112); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBool(stream, instance.FieldN); if (instance.FieldO == null) throw new ArgumentNullException("FieldO", "Required by proto specification."); // Key for field: 15, LengthDelimited stream.WriteByte(122); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(instance.FieldO)); if (instance.FieldP == null) throw new ArgumentNullException("FieldP", "Required by proto specification."); // Key for field: 16, LengthDelimited stream.Write(new byte[]{130, 1}, 0, 2); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, instance.FieldP); // Key for field: 17, Varint stream.Write(new byte[]{136, 1}, 0, 2); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt64(stream,(ulong)instance.FieldQ); if (instance.FieldR != MyEnum.ETest2) { // Key for field: 18, Varint stream.Write(new byte[]{144, 1}, 0, 2); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt64(stream,(ulong)instance.FieldR); } if (instance.Dummy != null) { // Key for field: 19, LengthDelimited stream.Write(new byte[]{154, 1}, 0, 2); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(instance.Dummy)); } if (instance.FieldT != null) { // Key for field: 20, LengthDelimited stream.Write(new byte[]{162, 1}, 0, 2); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, 4u * (uint)instance.FieldT.Count); foreach (var i20 in instance.FieldT) { bw.Write(i20); } } if (instance.FieldS != null) { foreach (var i21 in instance.FieldS) { // Key for field: 21, Varint stream.Write(new byte[]{168, 1}, 0, 2); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, i21); } } if (instance.FieldU != null) { // Key for field: 22, LengthDelimited stream.Write(new byte[]{178, 1}, 0, 2); using (var ms22 = new MemoryStream()) { Theirs.TheirMessage.Serialize(ms22, instance.FieldU); // Length delimited byte array uint ms22Length = (uint)ms22.Length; global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, ms22Length); stream.Write(ms22.GetBuffer(), 0, (int)ms22Length); } } if (instance.FieldV != null) { foreach (var i23 in instance.FieldV) { // Key for field: 23, LengthDelimited stream.Write(new byte[]{186, 1}, 0, 2); using (var ms23 = new MemoryStream()) { Theirs.TheirMessage.Serialize(ms23, i23); // Length delimited byte array uint ms23Length = (uint)ms23.Length; global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, ms23Length); stream.Write(ms23.GetBuffer(), 0, (int)ms23Length); } } } }
/// <summary> /// Sends acknowledgment to remote server /// </summary> /// <param name="server">A connected server I/O stream</param> private void SCP_SendAck(Stream server) { server.WriteByte(0); server.Flush(); }
internal override void Write(Stream writer) { writer.WriteByte((Byte)_val); }
public static void WriteUInt8(this Stream dest, byte val) { dest.WriteByte(val); }
/// <summary> /// Write an entry to the archive. This method will call the putNextEntry /// and then write the contents of the entry, and finally call closeEntry() /// for entries that are files. For directories, it will call putNextEntry(), /// and then, if the recurse flag is true, process each entry that is a /// child of the directory. /// </summary> /// <param name="sourceEntry"> /// The TarEntry representing the entry to write to the archive. /// </param> /// <param name="recurse"> /// If true, process the children of directory entries. /// </param> private void WriteEntryCore(TarEntry sourceEntry, bool recurse) { string tempFileName = null; string entryFilename = sourceEntry.File; var entry = (TarEntry)sourceEntry.Clone(); if (applyUserInfoOverrides) { entry.GroupId = groupId; entry.GroupName = groupName; entry.UserId = userId; entry.UserName = userName; } OnProgressMessageEvent(entry, null); if (asciiTranslate && !entry.IsDirectory) { if (!IsBinary(entryFilename)) { tempFileName = Path.GetTempFileName(); using (StreamReader inStream = File.OpenText(entryFilename)) { using (Stream outStream = File.Create(tempFileName)) { while (true) { string line = inStream.ReadLine(); if (line == null) { break; } byte[] data = Encoding.ASCII.GetBytes(line); outStream.Write(data, 0, data.Length); outStream.WriteByte((byte)'\n'); } outStream.Flush(); } } entry.Size = new FileInfo(tempFileName).Length; entryFilename = tempFileName; } } string newName = null; if (!String.IsNullOrEmpty(rootPath)) { if (entry.Name.StartsWith(rootPath, StringComparison.OrdinalIgnoreCase)) { newName = entry.Name.Substring(rootPath.Length + 1); } } if (pathPrefix != null) { newName = (newName == null) ? pathPrefix + "/" + entry.Name : pathPrefix + "/" + newName; } if (newName != null) { entry.Name = newName; } tarOut.PutNextEntry(entry); if (entry.IsDirectory) { if (recurse) { TarEntry[] list = entry.GetDirectoryEntries(); for (int i = 0; i < list.Length; ++i) { WriteEntryCore(list[i], recurse); } } } else { using (Stream inputStream = File.OpenRead(entryFilename)) { byte[] localBuffer = new byte[32 * 1024]; while (true) { int numRead = inputStream.Read(localBuffer, 0, localBuffer.Length); if (numRead <= 0) { break; } tarOut.Write(localBuffer, 0, numRead); } } if (!string.IsNullOrEmpty(tempFileName)) { File.Delete(tempFileName); } tarOut.CloseEntry(); } }
public static void WriteUInt16(this Stream dest, ushort val) { dest.WriteByte((byte)(val & 0xff)); dest.WriteByte((byte)(val >> 8)); }
/// <summary>Serialize the instance into the stream</summary> public static void Serialize(Stream stream, MethodDescriptorProto instance) { if (instance.Name != null) { // Key for field: 1, LengthDelimited stream.WriteByte(10); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(instance.Name)); } if (instance.InputType != null) { // Key for field: 2, LengthDelimited stream.WriteByte(18); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(instance.InputType)); } if (instance.OutputType != null) { // Key for field: 3, LengthDelimited stream.WriteByte(26); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(instance.OutputType)); } if (instance.Options != null) { // Key for field: 4, LengthDelimited stream.WriteByte(34); using (var ms4 = new MemoryStream()) { Google.protobuf.MethodOptions.Serialize(ms4, instance.Options); // Length delimited byte array uint ms4Length = (uint)ms4.Length; global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, ms4Length); stream.Write(ms4.GetBuffer(), 0, (int)ms4Length); } } }
/// <summary> /// Writes a 16bit unsigned integer in big-endian format. /// </summary> /// <param name="stream">The stream to write the data to.</param> /// <param name="value">The value to write</param> public static void WriteBigEndian(this Stream stream, ushort value) { stream.WriteByte((byte)(value >> 8)); stream.WriteByte((byte)(value >> 0)); }
/// <summary>Serialize the instance into the stream</summary> public static void Serialize(Stream stream, Location instance) { if (instance.Path != null) { // Key for field: 1, LengthDelimited stream.WriteByte(10); using (var ms1 = new MemoryStream()) { foreach (var i1 in instance.Path) { global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt64(ms1,(ulong)i1); } // Length delimited byte array uint ms1Length = (uint)ms1.Length; global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, ms1Length); stream.Write(ms1.GetBuffer(), 0, (int)ms1Length); } } if (instance.Span != null) { // Key for field: 2, LengthDelimited stream.WriteByte(18); using (var ms2 = new MemoryStream()) { foreach (var i2 in instance.Span) { global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt64(ms2,(ulong)i2); } // Length delimited byte array uint ms2Length = (uint)ms2.Length; global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, ms2Length); stream.Write(ms2.GetBuffer(), 0, (int)ms2Length); } } if (instance.LeadingComments != null) { // Key for field: 3, LengthDelimited stream.WriteByte(26); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(instance.LeadingComments)); } if (instance.TrailingComments != null) { // Key for field: 4, LengthDelimited stream.WriteByte(34); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(instance.TrailingComments)); } }
public void WriteByte(byte b) { position++; stream?.WriteByte(b); }
/// <summary>Serialize the instance into the stream</summary> public static void Serialize(Stream stream, NamePart instance) { if (instance.NamePartField == null) throw new ArgumentNullException("NamePartField", "Required by proto specification."); // Key for field: 1, LengthDelimited stream.WriteByte(10); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(instance.NamePartField)); // Key for field: 2, Varint stream.WriteByte(16); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBool(stream, instance.IsExtension); }
/// <summary> /// Save the ID3v2 frames to a binary stream /// </summary> /// <param name="frameModel">Model keeping the ID3 Tag structure</param> /// <param name="stream">Stream keeping the ID3 Tag</param> public static void Serialize([NotNull] TagModel frameModel, [NotNull] Stream stream) { if (frameModel.Count <= 0) { throw new InvalidTagException("Can't serialize a ID3v2 tag without any frames, there must be at least one present."); } using (var memory = new MemoryStream()) using (var writer = new BinaryWriter(memory, Encoding.UTF8, true)) { var frameHelper = new FrameHelper(frameModel.Header); // Write the frames in binary format foreach (var frame in frameModel) { //TODO: Do validations on tag name correctness var frameId = new byte[4]; Encoding.UTF8.GetBytes(frame.FrameId, 0, 4, frameId, 0); writer.Write(frameId); // Write the 4 byte text tag var buffer = frameHelper.Make(frame, out var flags); var frameSize = (uint)buffer.Length; if (frameModel.Header.Version == 4) { frameSize = Sync.Safe(frameSize); } writer.Write(Swap.UInt32(frameSize)); writer.Write(Swap.UInt16(flags)); writer.Write(buffer); } var id3TagSize = (uint)memory.Position; // Skip the header 10 bytes for now, we will come back and write the Header // with the correct size once have the tag size + padding stream.Seek(10, SeekOrigin.Begin); // TODO: Add extended header handling if (frameModel.Header.Unsync) { id3TagSize += Sync.Safe(memory, stream, id3TagSize); } else { memory.WriteTo(stream); } // update the TagSize stored in the tagModel frameModel.Header.TagSize = id3TagSize; // If padding + tag size is too big, shrink the padding (rather than throwing an exception) frameModel.Header.PaddingSize = Math.Min(frameModel.Header.PaddingSize, 0x10000000 - id3TagSize); // next write the padding of zeros, if any if (frameModel.Header.Padding) { for (var i = 0; i < frameModel.Header.PaddingSize; i++) { stream.WriteByte(0); } } // next write the footer, if any if (frameModel.Header.Footer) { frameModel.Header.SerializeFooter(stream); } // Now seek back to the start and write the header var position = stream.Position; stream.Seek(0, SeekOrigin.Begin); frameModel.Header.Serialize(stream); // reset position to the end of the tag stream.Position = position; } }
/// <summary>Serialize the instance into the stream</summary> public static void Serialize(Stream stream, ExtensionRange instance) { // Key for field: 1, Varint stream.WriteByte(8); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt64(stream,(ulong)instance.Start); // Key for field: 2, Varint stream.WriteByte(16); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt64(stream,(ulong)instance.End); }
/// <summary>Serialize the instance into the stream</summary> public static void Serialize(Stream stream, MyMessage instance) { // Key for field: 1, Varint stream.WriteByte(8); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt64(stream,(ulong)instance.Foo); if (instance.Bar != null) { // Key for field: 2, LengthDelimited stream.WriteByte(18); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(instance.Bar)); } }
/// <summary>Serialize the instance into the stream</summary> public static void Serialize(Stream stream, Container instance) { if (instance.MyNestedMessage != null) { // Key for field: 1, LengthDelimited stream.WriteByte(10); using (var ms1 = new MemoryStream()) { Proto.test.Container.Nested.Serialize(ms1, instance.MyNestedMessage); // Length delimited byte array uint ms1Length = (uint)ms1.Length; global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, ms1Length); stream.Write(ms1.GetBuffer(), 0, (int)ms1Length); } } if (instance.NestedField != null) { // Key for field: 2, LengthDelimited stream.WriteByte(18); using (var ms2 = new MemoryStream()) { Proto.test.Container.Nested.Serialize(ms2, instance.NestedField); // Length delimited byte array uint ms2Length = (uint)ms2.Length; global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, ms2Length); stream.Write(ms2.GetBuffer(), 0, (int)ms2Length); } } }
/// <summary>Serialize the instance into the stream</summary> public static void Serialize(Stream stream, ExternalStruct instance) { BinaryWriter bw = new BinaryWriter(stream); // Key for field: 1, Fixed64 stream.WriteByte(9); bw.Write(instance.X); }
/// <summary>Serialize the instance into the stream</summary> public static void Serialize(Stream stream, Data instance) { BinaryWriter bw = new BinaryWriter(stream); // Key for field: 1, Fixed64 stream.WriteByte(9); bw.Write(instance.Somefield); }
public static void WriteLong(Stream fs, byte flag, long val) { fs.WriteByte(flag); fs.Write(BitConverter.GetBytes(8), 0, 4); fs.Write(BitConverter.GetBytes(val), 0, 8); }
/// <summary>Serialize the instance into the stream</summary> public static void Serialize(Stream stream, EnumDescriptorProto instance) { if (instance.Name != null) { // Key for field: 1, LengthDelimited stream.WriteByte(10); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(instance.Name)); } if (instance.Value != null) { foreach (var i2 in instance.Value) { // Key for field: 2, LengthDelimited stream.WriteByte(18); using (var ms2 = new MemoryStream()) { Google.protobuf.EnumValueDescriptorProto.Serialize(ms2, i2); // Length delimited byte array uint ms2Length = (uint)ms2.Length; global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, ms2Length); stream.Write(ms2.GetBuffer(), 0, (int)ms2Length); } } } if (instance.Options != null) { // Key for field: 3, LengthDelimited stream.WriteByte(26); using (var ms3 = new MemoryStream()) { Google.protobuf.EnumOptions.Serialize(ms3, instance.Options); // Length delimited byte array uint ms3Length = (uint)ms3.Length; global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, ms3Length); stream.Write(ms3.GetBuffer(), 0, (int)ms3Length); } } }
/// <summary> /// Write the specified 8-bits byte value. /// </summary> /// <param name="val">Byte value.</param> public void Write(byte val) { Stream.WriteByte(val); }
/// <summary>Serialize the instance into the stream</summary> public static void Serialize(Stream stream, TheirMessage instance) { // Key for field: 1, Varint stream.WriteByte(8); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt64(stream,(ulong)instance.FieldA); }
public static void WritePacket(Stream s, SecureChannelCode code) { s.WriteByte(Convert.ToByte(code)); s.Flush(); }
public static async Task StreamTest(Stream stream, Boolean fSuppress) { string strValue; int iValue; //[] We will first use the stream's 2 writing methods int iLength = 1 << 10; stream.Seek(0, SeekOrigin.Begin); for (int i = 0; i < iLength; i++) stream.WriteByte((byte)i); byte[] btArr = new byte[iLength]; for (int i = 0; i < iLength; i++) btArr[i] = (byte)i; stream.Write(btArr, 0, iLength); //we will write many things here using a binary writer BinaryWriter bw1 = new BinaryWriter(stream); bw1.Write(false); bw1.Write(true); for (int i = 0; i < 10; i++) { bw1.Write((byte)i); bw1.Write((sbyte)i); bw1.Write((short)i); bw1.Write((char)i); bw1.Write((UInt16)i); bw1.Write(i); bw1.Write((uint)i); bw1.Write((Int64)i); bw1.Write((ulong)i); bw1.Write((float)i); bw1.Write((double)i); } //Some strings, chars and Bytes char[] chArr = new char[iLength]; for (int i = 0; i < iLength; i++) chArr[i] = (char)i; bw1.Write(chArr); bw1.Write(chArr, 512, 512); bw1.Write(new string(chArr)); bw1.Write(new string(chArr)); //[] we will now read stream.Seek(0, SeekOrigin.Begin); for (int i = 0; i < iLength; i++) { Assert.Equal(i % 256, stream.ReadByte()); } btArr = new byte[iLength]; stream.Read(btArr, 0, iLength); for (int i = 0; i < iLength; i++) { Assert.Equal((byte)i, btArr[i]); } //Now, for the binary reader BinaryReader br1 = new BinaryReader(stream); Assert.False(br1.ReadBoolean()); Assert.True(br1.ReadBoolean()); for (int i = 0; i < 10; i++) { Assert.Equal( (byte)i, br1.ReadByte()); Assert.Equal((sbyte)i, br1.ReadSByte()); Assert.Equal((short)i, br1.ReadInt16()); Assert.Equal((char)i, br1.ReadChar()); Assert.Equal((UInt16)i, br1.ReadUInt16()); Assert.Equal(i, br1.ReadInt32()); Assert.Equal((uint)i, br1.ReadUInt32()); Assert.Equal((Int64)i, br1.ReadInt64()); Assert.Equal((ulong)i, br1.ReadUInt64()); Assert.Equal((float)i, br1.ReadSingle()); Assert.Equal((double)i, br1.ReadDouble()); } chArr = br1.ReadChars(iLength); for (int i = 0; i < iLength; i++) { Assert.Equal((char)i, chArr[i]); } chArr = new char[512]; chArr = br1.ReadChars(iLength / 2); for (int i = 0; i < iLength / 2; i++) { Assert.Equal((char)(iLength / 2 + i), chArr[i]); } chArr = new char[iLength]; for (int i = 0; i < iLength; i++) chArr[i] = (char)i; strValue = br1.ReadString(); Assert.Equal(new string(chArr), strValue); strValue = br1.ReadString(); Assert.Equal(new string(chArr), strValue); stream.Seek(1, SeekOrigin.Current); // In the original test, success here would end the test //[] we will do some async tests here now stream.Position = 0; btArr = new byte[iLength]; for (int i = 0; i < iLength; i++) btArr[i] = (byte)(i + 5); await stream.WriteAsync(btArr, 0, btArr.Length); stream.Position = 0; for (int i = 0; i < iLength; i++) { Assert.Equal((byte)(i + 5), stream.ReadByte()); } //we will read asynchronously stream.Position = 0; byte[] compArr = new byte[iLength]; iValue = await stream.ReadAsync(compArr, 0, compArr.Length); Assert.Equal(btArr.Length, iValue); for (int i = 0; i < iLength; i++) { Assert.Equal(compArr[i], btArr[i]); } }
static void UrlEncodeChar(char c, Stream result, bool isUnicode) { if (c > 255) { //FIXME: what happens when there is an internal error? //if (!isUnicode) // throw new ArgumentOutOfRangeException ("c", c, "c must be less than 256"); int idx; int i = (int)c; result.WriteByte((byte)'%'); result.WriteByte((byte)'u'); idx = i >> 12; result.WriteByte((byte)hexChars[idx]); idx = (i >> 8) & 0x0F; result.WriteByte((byte)hexChars[idx]); idx = (i >> 4) & 0x0F; result.WriteByte((byte)hexChars[idx]); idx = i & 0x0F; result.WriteByte((byte)hexChars[idx]); return; } if (c > ' ' && notEncoded.IndexOf(c) != -1) { result.WriteByte((byte)c); return; } if (c == ' ') { result.WriteByte((byte)'+'); return; } if ((c < '0') || (c < 'A' && c > '9') || (c > 'Z' && c < 'a') || (c > 'z')) { if (isUnicode && c > 127) { result.WriteByte((byte)'%'); result.WriteByte((byte)'u'); result.WriteByte((byte)'0'); result.WriteByte((byte)'0'); } else { result.WriteByte((byte)'%'); } int idx = ((int)c) >> 4; result.WriteByte((byte)hexChars[idx]); idx = ((int)c) & 0x0F; result.WriteByte((byte)hexChars[idx]); } else { result.WriteByte((byte)c); } }
public static bool CanPropertiesTest(Stream s) { Console.WriteLine(" (06) Can-Properties Test on "+s.GetType( ).Name); byte[] bytes = new byte[1]; int bytesTransferred; IAsyncResult asyncResult; if(s.CanRead) { // Ensure all Read methods work, if CanRead is true. int n = s.ReadByte( ); if(n==-1) throw new Exception("On a readable stream, ReadByte returned -1..."); bytesTransferred=s.Read(bytes,0,1); if(bytesTransferred!=1) throw new Exception("Read(byte[],0,1) should have returned 1! got: "+bytesTransferred); asyncResult=s.BeginRead(bytes,0,1,null,null); /* BeginRead */ bytesTransferred=s.EndRead(asyncResult); /* EndRead */ if(bytesTransferred!=1) throw new Exception("BeginRead(byte[],0,1) should have returned 1! got: " +bytesTransferred); } // End of (s.CanRead) Block else { // Begin of (!s.CanRead) Block try { s.ReadByte( ); throw new Exception("ReadByte on an unreadable stream should have thrown!"); } catch(NotSupportedException) { } try { s.Read(bytes,0,1); throw new Exception("Read(bytes,0,1) on an unreadable stream should have thrown!"); } catch(NotSupportedException) { } try { s.BeginRead(bytes,0,1,null,null); /* BeginRead */ throw new Exception("BeginRead on an unreadable stream should have thrown!"); } catch(NotSupportedException) { } } // End of (!s.CanRead) Block if(s.CanWrite) { // Ensure write methods work if CanWrite returns true. s.WriteByte(0); s.Write(bytes,0,1); asyncResult = s.BeginWrite(bytes,0,1,null,null); /* BeginWrite */ s.EndWrite(asyncResult); /* EndWrite */ } // End of (s.CanWrite) Block else { // Begin of (!s.CanWrite) Block try { s.WriteByte(2); throw new Exception("WriteByte on an unreadable stream should have thrown!"); } catch(NotSupportedException) { } try { s.Write(bytes,0,1); throw new Exception("Write(bytes,0,1) on an unreadable stream should have thrown!"); } catch(NotSupportedException) { } try { s.BeginWrite(bytes,0,1,null,null); /* BeginWrite */ throw new Exception("BeginWrite on an unreadable stream should have thrown!"); } catch(NotSupportedException) { } } // End of (!s.CanWrite) Block if(s.CanSeek) { // Ensure length-related methods work if CanSeek returns true long n = s.Length; n=s.Position; if(s.Position>s.Length) throw new Exception("Position is beyond the length of the stream!"); s.Position=0; s.Position=s.Length; if(s.Position!=s.Seek(0,SeekOrigin.Current)) throw new Exception("s.Position!=s.Seek(0,SeekOrigin.Current)"); if(s.CanWrite) // Verify you can set the length, if it's writable. s.SetLength(s.Length); } // End of (s.CanSeek) Block else { // Begin of (!s.CanSeek) Block try { s.Position=5; throw new Exception("set_Position should throw on a non-seekable stream!"); } catch(NotSupportedException) { } try { long n = s.Position; throw new Exception("get_Position should throw on a non-seekable stream!"); } catch(NotSupportedException) { } try { long n = s.Length; throw new Exception("get_Length should throw on a non-seekable stream!"); } catch(NotSupportedException) { } try { s.SetLength(1); throw new Exception("SetLength should throw on a non-seekable stream!"); } catch(NotSupportedException) { } try { s.Seek(0,SeekOrigin.Current); throw new Exception("Seek should throw on a non-seekable stream!"); } catch(NotSupportedException) { } } // End of (!s.CanSeek) Block return true; }
/// <summary>Serialize the instance into the stream</summary> public static void Serialize(Stream stream, DescriptorProto instance) { if (instance.Name != null) { // Key for field: 1, LengthDelimited stream.WriteByte(10); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(instance.Name)); } if (instance.Field != null) { foreach (var i2 in instance.Field) { // Key for field: 2, LengthDelimited stream.WriteByte(18); using (var ms2 = new MemoryStream()) { Google.protobuf.FieldDescriptorProto.Serialize(ms2, i2); // Length delimited byte array uint ms2Length = (uint)ms2.Length; global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, ms2Length); stream.Write(ms2.GetBuffer(), 0, (int)ms2Length); } } } if (instance.Extension != null) { foreach (var i6 in instance.Extension) { // Key for field: 6, LengthDelimited stream.WriteByte(50); using (var ms6 = new MemoryStream()) { Google.protobuf.FieldDescriptorProto.Serialize(ms6, i6); // Length delimited byte array uint ms6Length = (uint)ms6.Length; global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, ms6Length); stream.Write(ms6.GetBuffer(), 0, (int)ms6Length); } } } if (instance.NestedType != null) { foreach (var i3 in instance.NestedType) { // Key for field: 3, LengthDelimited stream.WriteByte(26); using (var ms3 = new MemoryStream()) { Google.protobuf.DescriptorProto.Serialize(ms3, i3); // Length delimited byte array uint ms3Length = (uint)ms3.Length; global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, ms3Length); stream.Write(ms3.GetBuffer(), 0, (int)ms3Length); } } } if (instance.EnumType != null) { foreach (var i4 in instance.EnumType) { // Key for field: 4, LengthDelimited stream.WriteByte(34); using (var ms4 = new MemoryStream()) { Google.protobuf.EnumDescriptorProto.Serialize(ms4, i4); // Length delimited byte array uint ms4Length = (uint)ms4.Length; global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, ms4Length); stream.Write(ms4.GetBuffer(), 0, (int)ms4Length); } } } if (instance.ExtensionRangeField != null) { foreach (var i5 in instance.ExtensionRangeField) { // Key for field: 5, LengthDelimited stream.WriteByte(42); using (var ms5 = new MemoryStream()) { Google.protobuf.DescriptorProto.ExtensionRange.Serialize(ms5, i5); // Length delimited byte array uint ms5Length = (uint)ms5.Length; global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, ms5Length); stream.Write(ms5.GetBuffer(), 0, (int)ms5Length); } } } if (instance.Options != null) { // Key for field: 7, LengthDelimited stream.WriteByte(58); using (var ms7 = new MemoryStream()) { Google.protobuf.MessageOptions.Serialize(ms7, instance.Options); // Length delimited byte array uint ms7Length = (uint)ms7.Length; global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, ms7Length); stream.Write(ms7.GetBuffer(), 0, (int)ms7Length); } } }
/// <summary> /// Write the colormap. /// Windows uses BGR0 map entries; OS/2 uses BGR entries. /// </summary> private void writeColormap(int map_colors, int map_entry_size) { byte[][] colormap = m_parameters.Colormap; int num_colors = m_parameters.ActualNumberOfColors; int i = 0; if (colormap != null) { if (m_parameters.ComponentsPerSample == 3) { /* Normal case with RGB colormap */ for (i = 0; i < num_colors; i++) { m_output.WriteByte(colormap[2][i]); m_output.WriteByte(colormap[1][i]); m_output.WriteByte(colormap[0][i]); if (map_entry_size == 4) { m_output.WriteByte(0); } } } else { /* Grayscale colormap (only happens with grayscale quantization) */ for (i = 0; i < num_colors; i++) { m_output.WriteByte(colormap[0][i]); m_output.WriteByte(colormap[0][i]); m_output.WriteByte(colormap[0][i]); if (map_entry_size == 4) { m_output.WriteByte(0); } } } } else { /* If no colormap, must be grayscale data. Generate a linear "map". */ for (i = 0; i < 256; i++) { m_output.WriteByte((byte)i); m_output.WriteByte((byte)i); m_output.WriteByte((byte)i); if (map_entry_size == 4) { m_output.WriteByte(0); } } } /* Pad colormap with zeros to ensure specified number of colormap entries */ if (i > map_colors) { throw new InvalidOperationException("Too many colors"); } for (; i < map_colors; i++) { m_output.WriteByte(0); m_output.WriteByte(0); m_output.WriteByte(0); if (map_entry_size == 4) { m_output.WriteByte(0); } } }
/// <summary>Serialize the instance into the stream</summary> public static void Serialize(Stream stream, FileOptions instance) { if (instance.JavaPackage != null) { // Key for field: 1, LengthDelimited stream.WriteByte(10); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(instance.JavaPackage)); } if (instance.JavaOuterClassname != null) { // Key for field: 8, LengthDelimited stream.WriteByte(66); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(instance.JavaOuterClassname)); } // Key for field: 10, Varint stream.WriteByte(80); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBool(stream, instance.JavaMultipleFiles); // Key for field: 20, Varint stream.Write(new byte[]{160, 1}, 0, 2); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBool(stream, instance.JavaGenerateEqualsAndHash); if (instance.OptimizeFor != OptimizeMode.SPEED) { // Key for field: 9, Varint stream.WriteByte(72); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt64(stream,(ulong)instance.OptimizeFor); } if (instance.GoPackage != null) { // Key for field: 11, LengthDelimited stream.WriteByte(90); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(instance.GoPackage)); } // Key for field: 16, Varint stream.Write(new byte[]{128, 1}, 0, 2); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBool(stream, instance.CcGenericServices); // Key for field: 17, Varint stream.Write(new byte[]{136, 1}, 0, 2); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBool(stream, instance.JavaGenericServices); // Key for field: 18, Varint stream.Write(new byte[]{144, 1}, 0, 2); global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBool(stream, instance.PyGenericServices); if (instance.UninterpretedOption != null) { foreach (var i999 in instance.UninterpretedOption) { // Key for field: 999, LengthDelimited stream.Write(new byte[]{186, 62}, 0, 2); using (var ms999 = new MemoryStream()) { Google.protobuf.UninterpretedOption.Serialize(ms999, i999); // Length delimited byte array uint ms999Length = (uint)ms999.Length; global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, ms999Length); stream.Write(ms999.GetBuffer(), 0, (int)ms999Length); } } } }
public void WriteTo(Stream s) { _nonce.WriteTo(s); s.WriteByte((byte)_cryptoOptions); }
public void Write(sbyte val) { Stream.WriteByte((byte)val); }