System.IO.MemoryStream.WriteByte(byte)

Here are the examples of the csharp api System.IO.MemoryStream.WriteByte(byte) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

658 Examples 7

19 View Source File : RdpPacket.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : 3gstudent

override public void WriteByte(byte value)
        {
            base.WriteByte(value);
        }

19 View Source File : SevenZipHelper.cs
License : MIT License
Project Creator : 91Act

public static byte[] Compress(byte[] inputBytes)
        {

            MemoryStream inStream = new MemoryStream(inputBytes);
            MemoryStream outStream = new MemoryStream();
            Encoder encoder = new Encoder();
            encoder.SetCoderProperties(propIDs, properties);
            encoder.WriteCoderProperties(outStream);
            long fileSize = inStream.Length;
            for (int i = 0; i < 8; i++)
                outStream.WriteByte((Byte)(fileSize >> (8 * i)));
            encoder.Code(inStream, outStream, -1, -1, null);
            return outStream.ToArray();
        }

19 View Source File : EditingCommandHandler.cs
License : MIT License
Project Creator : Abdesol

static bool CopyWholeLine(TextArea textArea, DoreplacedentLine line)
		{
			ISegment wholeLine = new SimpleSegment(line.Offset, line.TotalLength);
			string text = textArea.Doreplacedent.GetText(wholeLine);
			// Ensure we use the appropriate newline sequence for the OS
			text = TextUtilities.NormalizeNewLines(text, Environment.NewLine);
			DataObject data = new DataObject();
			if (ConfirmDataFormat(textArea, data, DataFormats.UnicodeText))
				data.SetText(text);

			// Also copy text in HTML format to clipboard - good for pasting text into Word
			// or to the SharpDevelop forums.
			if (ConfirmDataFormat(textArea, data, DataFormats.Html)) {
				IHighlighter highlighter = textArea.GetService(typeof(IHighlighter)) as IHighlighter;
				HtmlClipboard.SetHtml(data, HtmlClipboard.CreateHtmlFragment(textArea.Doreplacedent, highlighter, wholeLine, new HtmlOptions(textArea.Options)));
			}

			if (ConfirmDataFormat(textArea, data, LineSelectedType)) {
				MemoryStream lineSelected = new MemoryStream(1);
				lineSelected.WriteByte(1);
				data.SetData(LineSelectedType, lineSelected, false);
			}

			var copyingEventArgs = new DataObjectCopyingEventArgs(data, false);
			textArea.RaiseEvent(copyingEventArgs);
			if (copyingEventArgs.CommandCancelled)
				return false;

			try {
				Clipboard.SetDataObject(data, true);
			} catch (ExternalException) {
				// Apparently this exception sometimes happens randomly.
				// The MS controls just ignore it, so we'll do the same.
				return false;
			}
			textArea.OnTextCopied(new TextEventArgs(text));
			return true;
		}

19 View Source File : RectangleSelection.cs
License : MIT License
Project Creator : Abdesol

public override System.Windows.DataObject CreateDataObject(TextArea textArea)
		{
			var data = base.CreateDataObject(textArea);

			if (EditingCommandHandler.ConfirmDataFormat(textArea, data, RectangularSelectionDataType)) {
				MemoryStream isRectangle = new MemoryStream(1);
				isRectangle.WriteByte(1);
				data.SetData(RectangularSelectionDataType, isRectangle, false);
			}
			return data;
		}

19 View Source File : TsonSerializerBase.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public byte[] Close()
        {
            Stream.WriteByte(0xFF);
            Stream.WriteByte(0xFF);
            Buffer = Stream.ToArray();
            Stream.Dispose();
            return Buffer;
        }

19 View Source File : TsonSerializerBase.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public void WriteIndex(int idx)
        {
            Stream.WriteByte((byte)idx);
        }

19 View Source File : TsonSerializerBase.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public void WriteBoolValue(bool value)
        {
            Stream.WriteByte((byte)(value ? 1 : 0));
        }

19 View Source File : TsonSerializerBase.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public void WriteByteValue(byte value)
        {
            Stream.WriteByte(value);
        }

19 View Source File : TsonSerializerBase.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public void WriteValue(byte value)
        {
            Stream.WriteByte(value);
        }

19 View Source File : TsonSerializerBase.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public void WriteValue(byte* addr, int size)
        {
            for (var idx = 0; idx < size; idx++) Stream.WriteByte(*(addr + idx));
        }

19 View Source File : TsonSerializerBase.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public void WriteValue(bool value)
        {
            Stream.WriteByte((byte)(value ? 1 : 0));
        }

19 View Source File : TsonSerializerBase.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public void Begin(TsonDataType type= TsonDataType.Object)
        {
            Stream.WriteByte(Ver);
            Stream.WriteByte((byte)type);
        }

19 View Source File : TsonSerializerBase.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public void End()
        {
            Stream.WriteByte(0xFF);
        }

19 View Source File : AudioPlayer.cs
License : GNU General Public License v3.0
Project Creator : ahmed605

private void Filler(IntPtr data, int size)
        {
            int blockCount = _wave.BlockCount;
            byte[] b = new byte[size];

            if (_file != null && (_looped || _lastBlock < blockCount))
            {
                MemoryStream ms = new MemoryStream();

                if (_leftOverBuffer != null)
                {
                    ms.Write(_leftOverBuffer, 0, _leftOverBuffer.Length);
                }
                
                while (ms.Position < size)
                {
                    _lastBlock++;

                    if (_lastBlock >= blockCount)
                    {
                        if (!_looped)
                        {
                            while(ms.Position < size)
                            {
                                ms.WriteByte(0);
                            }
                            break;
                        }
                        else
                        {
                            _lastBlock = 0;
                            _state = new DviAdpcmDecoder.AdpcmState();
                        }
                    }

                    _file.SoundBank.ExportWaveBlockAsPCM(_wave.Index, _lastBlock, ref _state, _file.Stream, ms);
                }

                int extraData = (int)(ms.Position - size);
                
                ms.Seek(0, SeekOrigin.Begin);
                ms.Read(b, 0, size);

                if (extraData > 0)
                {
                    _leftOverBuffer = new byte[extraData];
                    ms.Read(_leftOverBuffer, 0, extraData);
                }
                else
                {
                    _leftOverBuffer = null;
                }
            }
            else
            {
                for (int i = 0; i < b.Length; i++)
                {
                    b[i] = 0;
                }
            }
            System.Runtime.InteropServices.Marshal.Copy(b, 0, data, size);
        }

19 View Source File : IconFile.cs
License : MIT License
Project Creator : ahopper

static public void SaveToICO(Drawing drawing, List<int> sizes, string filename)
        {
            int headerLen = 6 + sizes.Count * 16;
            using (var icoStream = new MemoryStream())
            {
                //write ICONDIR
                icoStream.WriteByte(0);
                icoStream.WriteByte(0);
                icoStream.WriteByte(1);
                icoStream.WriteByte(0);
                icoStream.WriteByte((byte)sizes.Count);
                icoStream.WriteByte(0);
                
                icoStream.Position = headerLen;
                
                for (int i =0; i< sizes.Count; i++)
                {
                    var start = icoStream.Position;
                    SaveDrawing(drawing, sizes[i], icoStream);
                    var end = icoStream.Position;
                    int pngLen = (int)(end - start);
               
                    icoStream.Position = 6 + i * 16;
                    icoStream.WriteByte((byte)sizes[i]);
                    icoStream.WriteByte((byte)sizes[i]);
                    icoStream.WriteByte(0);
                    icoStream.WriteByte(0);
                    icoStream.WriteByte(0);
                    icoStream.WriteByte(0);
                    icoStream.WriteByte(0);
                    icoStream.WriteByte(32);

                    icoStream.WriteByte((byte)(pngLen & 0xff));
                    icoStream.WriteByte((byte)((pngLen >> 8) & 0xff)); 
                    icoStream.WriteByte((byte)((pngLen >> 16) & 0xff));
                    icoStream.WriteByte((byte)(pngLen >> 24));
                   
                    icoStream.WriteByte((byte)(start & 0xff)); 
                    icoStream.WriteByte((byte)((start >> 8) & 0xff));
                    icoStream.WriteByte((byte)((start >> 16) & 0xff));
                    icoStream.WriteByte((byte)(start >> 24));
           
                    icoStream.Position=end;
                }
                using(var icoFile=File.Create(filename))
                {
                    icoFile.Write(icoStream.GetBuffer(), 0, (int)icoStream.Position);
                }
            }
        }

19 View Source File : IconFile.cs
License : MIT License
Project Creator : ahopper

static public void SaveToICNS(Drawing drawing, List<int> sizes, string filename)
        {
            int headerLen = 8;
            int fileLen = headerLen;
            using (var icoStream = new MemoryStream())
            {
                icoStream.WriteByte(0x69);
                icoStream.WriteByte(0x63);
                icoStream.WriteByte(0x6e);
                icoStream.WriteByte(0x73);
                
                icoStream.Position = headerLen;

                for (int i = 0; i < sizes.Count; i++)
                {
                    var start = icoStream.Position;
                    icoStream.Position += 8;
                    SaveDrawing(drawing, sizes[i], icoStream);
                    var end = icoStream.Position;
                    int pngLen = (int)(end - start);
                    fileLen += pngLen;

                    icoStream.Position = start;
                    string iconType;
                    switch(sizes[i])
                    {
                        case 16: iconType = "icp4"; break;
                        case 32: iconType = "icp5"; break;
                        case 64: iconType = "icp6"; break;
                        case 128: iconType = "ic07"; break;
                        case 256: iconType = "ic08"; break;
                        case 512: iconType = "ic09"; break;
                        default: throw new Exception($"Unsupported icns size {sizes[i]}");
                    }
                    icoStream.Write(ASCIIEncoding.ASCII.GetBytes(iconType));

                    icoStream.WriteByte((byte)(pngLen >> 24));
                    icoStream.WriteByte((byte)((pngLen >> 16) & 0xff));
                    icoStream.WriteByte((byte)((pngLen >> 8) & 0xff));
                    icoStream.WriteByte((byte)(pngLen & 0xff));
                    
                    icoStream.Position = end;
                }
                icoStream.Position = 4;

                icoStream.WriteByte((byte)(fileLen >> 24));
                icoStream.WriteByte((byte)((fileLen >> 16) & 0xff));
                icoStream.WriteByte((byte)((fileLen >> 8) & 0xff));
                icoStream.WriteByte((byte)(fileLen & 0xff));
                
                using (var icoFile = File.Create(filename))
                {
                    icoFile.Write(icoStream.GetBuffer(), 0, fileLen);
                }
            }
        }

19 View Source File : Mnemonic.cs
License : Apache License 2.0
Project Creator : ajuna-network

public static byte[] PBKDF2Sha512GetBytes(int dklen, byte[] preplacedword, byte[] salt, int iterationCount)
        {
            using (var hmac = new HMACSHA512(preplacedword))
            {
                int hashLength = hmac.HashSize / 8;
                if ((hmac.HashSize & 7) != 0)
                    hashLength++;
                int keyLength = dklen / hashLength;
                if (dklen > (0xFFFFFFFFL * hashLength) || dklen < 0)
                {
                    throw new ArgumentOutOfRangeException("dklen");
                }
                if (dklen % hashLength != 0)
                {
                    keyLength++;
                }
                byte[] extendedkey = new byte[salt.Length + 4];
                Buffer.BlockCopy(salt, 0, extendedkey, 0, salt.Length);
                using (var ms = new MemoryStream())
                {
                    for (int i = 0; i < keyLength; i++)
                    {
                        extendedkey[salt.Length] = (byte)(((i + 1) >> 24) & 0xFF);
                        extendedkey[salt.Length + 1] = (byte)(((i + 1) >> 16) & 0xFF);
                        extendedkey[salt.Length + 2] = (byte)(((i + 1) >> 8) & 0xFF);
                        extendedkey[salt.Length + 3] = (byte)(((i + 1)) & 0xFF);
                        byte[] u = hmac.ComputeHash(extendedkey);
                        Array.Clear(extendedkey, salt.Length, 4);
                        byte[] f = u;
                        for (int j = 1; j < iterationCount; j++)
                        {
                            u = hmac.ComputeHash(u);
                            for (int k = 0; k < f.Length; k++)
                            {
                                f[k] ^= u[k];
                            }
                        }
                        ms.Write(f, 0, f.Length);
                        Array.Clear(u, 0, u.Length);
                        Array.Clear(f, 0, f.Length);
                    }
                    byte[] dk = new byte[dklen];
                    ms.Position = 0;
                    ms.Read(dk, 0, dklen);
                    ms.Position = 0;
                    for (long i = 0; i < ms.Length; i++)
                    {
                        ms.WriteByte(0);
                    }
                    Array.Clear(extendedkey, 0, extendedkey.Length);
                    return dk;
                }
            }
        }

19 View Source File : MessageBuilder.cs
License : MIT License
Project Creator : allartprotocol

internal byte[] Build()
        {
            if (RecentBlockHash == null) 
                // werent we supposed to fetch it from the api in this case?
                throw new Exception("recent block hash is required");
            if (_instructions == null) 
                throw new Exception("no instructions provided in the transaction");

            _messageHeader = new MessageHeader();
            
            var keysList = GetAccountKeys();
            var accountAddressesLength = ShortVectorEncoding.EncodeLength(keysList.Count);
            var compiledInstructionsLength = 0;
            var compiledInstructions = new List<CompiledInstruction>();

            foreach (var instruction in _instructions)
            {
                var keyCount = instruction.Keys.Count;
                var keyIndices = new byte[keyCount];

                for (var i = 0; i < keyCount; i++)
                {
                    keyIndices[i] = (byte) FindAccountIndex(keysList, instruction.Keys[i].PublicKey);
                }

                var compiledInstruction = new CompiledInstruction
                {
                    ProgramIdIndex = (byte) FindAccountIndex(keysList, instruction.ProgramId),
                    KeyIndicesCount = ShortVectorEncoding.EncodeLength(keyCount),
                    KeyIndices = keyIndices,
                    DataLength = ShortVectorEncoding.EncodeLength(instruction.Data.Length),
                    Data = instruction.Data
                };
                compiledInstructions.Add(compiledInstruction);
                compiledInstructionsLength += compiledInstruction.Length();
            }


            var accountKeysBufferSize = _accountKeysList.AccountList.Count * 32;
            var accountKeysBuffer = new MemoryStream(accountKeysBufferSize);
            var instructionsLength = ShortVectorEncoding.EncodeLength(compiledInstructions.Count);
            
            foreach (var accountMeta in keysList)
            {
                accountKeysBuffer.Write(accountMeta.PublicKey,0, accountMeta.PublicKey.Length);
                if (accountMeta.Signer)
                {
                    _messageHeader.RequiredSignatures += 1;
                    if (!accountMeta.Writable)
                        _messageHeader.ReadOnlySignedAccounts += 1;
                }
                else 
                {
                    if (!accountMeta.Writable)
                        _messageHeader.ReadOnlyUnsignedAccounts += 1;
                }
            }

            #region Build Message Body

            
            var messageBufferSize = MessageHeader.HeaderLength + BlockHashLength + accountAddressesLength.Length +
                                    + instructionsLength.Length + compiledInstructionsLength + accountKeysBufferSize;
            var buffer = new MemoryStream(messageBufferSize);
            var messageHeaderBytes = _messageHeader.ToBytes();

            buffer.Write(messageHeaderBytes, 0, messageHeaderBytes.Length);
            buffer.Write(accountAddressesLength, 0, accountAddressesLength.Length);
            buffer.Write(accountKeysBuffer.ToArray(),0, accountKeysBuffer.ToArray().Length);
            buffer.Write(Base58Encoding.Decode(RecentBlockHash),0, Base58Encoding.Decode(RecentBlockHash).Length);
            buffer.Write(instructionsLength, 0, instructionsLength.Length);
            
            foreach (var compiledInstruction in compiledInstructions)
            {
                buffer.WriteByte(compiledInstruction.ProgramIdIndex);
                buffer.Write(compiledInstruction.KeyIndicesCount, 0, compiledInstruction.KeyIndicesCount.Length);
                buffer.Write(compiledInstruction.KeyIndices,0, compiledInstruction.KeyIndices.Length);
                buffer.Write(compiledInstruction.DataLength,0, compiledInstruction.DataLength.Length);
                buffer.Write(compiledInstruction.Data,0, compiledInstruction.Data.Length);
            }

            #endregion
            
            return buffer.ToArray();
        }

19 View Source File : DefaultProtobufSerializer.cs
License : MIT License
Project Creator : AlphaYu

private void WriteType(MemoryStream ms, Type type)
        {
            var typeName = TypeHelper.BuildTypeName(type);
            var typeArray = Encoding.UTF8.GetBytes(typeName);

            var len = typeArray.Length;
            // BinaryWrite Int32
            ms.WriteByte((byte)len);
            ms.WriteByte((byte)(len >> 8));
            ms.WriteByte((byte)(len >> 16));
            ms.WriteByte((byte)(len >> 24));
            // BinaryWrite String
            ms.Write(typeArray, 0, len);
        }

19 View Source File : CharsetProber.cs
License : Mozilla Public License 2.0
Project Creator : amrali-eg

protected static byte[] FilterWithoutEnglishLetters(byte[] buf, int offset, int len)
        {
            byte[] result;

            using (MemoryStream ms = new MemoryStream(buf.Length))
            {
                bool meetMSB = false;
                int max = offset + len;
                int prev = offset;
                int cur = offset;

                while (cur < max)
                {
                    byte b = buf[cur];

                    if ((b & 0x80) != 0)
                    {
                        meetMSB = true;
                    }
                    else if (b < CAPITAL_A || (b > CAPITAL_Z && b < SMALL_A) || b > SMALL_Z)
                    {
                        if (meetMSB && cur > prev)
                        {
                            ms.Write(buf, prev, cur - prev);
                            ms.WriteByte(SPACE);
                            meetMSB = false;
                        }
                        prev = cur + 1;
                    }
                    cur++;
                }

                if (meetMSB && cur > prev)
                    ms.Write(buf, prev, cur - prev);
                ms.SetLength(ms.Position);
                result = ms.ToArray();
            }
            return result;
        }

19 View Source File : CharsetProber.cs
License : Mozilla Public License 2.0
Project Creator : amrali-eg

protected static byte[] FilterWithEnglishLetters(byte[] buf, int offset, int len)
        {
            byte[] result;

            using (MemoryStream ms = new MemoryStream(buf.Length))
            {

                bool inTag = false;
                int max = offset + len;
                int prev = offset;
                int cur = offset;

                while (cur < max)
                {

                    byte b = buf[cur];

                    if (b == GREATER_THAN)
                        inTag = false;
                    else if (b == LESS_THAN)
                        inTag = true;

                    // it's ascii, but it's not a letter
                    if ((b & 0x80) == 0 && (b < CAPITAL_A || b > SMALL_Z
                           || (b > CAPITAL_Z && b < SMALL_A)))
                    {
                        if (cur > prev && !inTag)
                        {
                            ms.Write(buf, prev, cur - prev);
                            ms.WriteByte(SPACE);
                        }
                        prev = cur + 1;
                    }
                    cur++;
                }

                // If the current segment contains more than just a symbol 
                // and it is not inside a tag then keep it.
                if (!inTag && cur > prev)
                    ms.Write(buf, prev, cur - prev);
                ms.SetLength(ms.Position);
                result = ms.ToArray();
            }
            return result;
        }

19 View Source File : HttpUtility.cs
License : MIT License
Project Creator : andruzzzhka

private static byte[] urlDecodeToBytes (byte[] bytes, int offset, int count)
    {
      using (var buff = new MemoryStream ()) {
        var end = offset + count - 1;
        for (var i = offset; i <= end; i++) {
          var b = bytes[i];

          var c = (char) b;
          if (c == '%') {
            if (i > end - 2)
              break;

            var num = getNumber (bytes, i + 1, 2);
            if (num == -1)
              break;

            buff.WriteByte ((byte) num);
            i += 2;

            continue;
          }

          if (c == '+') {
            buff.WriteByte ((byte) ' ');
            continue;
          }

          buff.WriteByte (b);
        }

        buff.Close ();
        return buff.ToArray ();
      }
    }

19 View Source File : ZipExtraData.cs
License : GNU General Public License v3.0
Project Creator : anydream

public void AddData(byte data)
		{
			_newEntry.WriteByte(data);
		}

19 View Source File : ZipExtraData.cs
License : GNU General Public License v3.0
Project Creator : anydream

public void AddLeShort(int toAdd)
		{
			unchecked {
				_newEntry.WriteByte((byte)toAdd);
				_newEntry.WriteByte((byte)(toAdd >> 8));
			}
		}

19 View Source File : VBACompression.cs
License : Apache License 2.0
Project Creator : Appdynamics

private static void DecompressChunk(MemoryStream ms, byte[] compBuffer, ref int pos)
        {
            ushort header = BitConverter.ToUInt16(compBuffer, pos);
            int decomprPos = 0;
            byte[] buffer = new byte[4198]; //Add an extra 100 byte. Some workbooks have overflowing worksheets.
            int size = (int)(header & 0xFFF) + 3;
            int endPos = pos + size;
            int a = (int)(header & 0x7000) >> 12;
            int b = (int)(header & 0x8000) >> 15;
            pos += 2;
            if (b == 1) //Compressed chunk
            {
                while (pos < compBuffer.Length && pos < endPos)
                {
                    //Decompress token
                    byte token = compBuffer[pos++];
                    if (pos >= endPos)
                        break;
                    for (int i = 0; i < 8; i++)
                    {
                        //Literal token
                        if ((token & (1 << i)) == 0)
                        {
                            ms.WriteByte(compBuffer[pos]);
                            buffer[decomprPos++] = compBuffer[pos++];
                        }
                        else //copy token
                        {
                            var t = BitConverter.ToUInt16(compBuffer, pos);
                            int bitCount = GetLengthBits(decomprPos);
                            int bits = (16 - bitCount);
                            ushort lengthMask = (ushort)((0xFFFF) >> bits);
                            UInt16 offsetMask = (ushort)~lengthMask;
                            var length = (lengthMask & t) + 3;
                            var offset = (offsetMask & t) >> (bitCount);
                            int source = decomprPos - offset - 1;
                            if (decomprPos + length >= buffer.Length)
                            {
                                // Be lenient on decompression, so extend our decompression
                                // buffer. Excel generated VBA projects do encounter this issue.
                                // One would think (not surprisingly that the VBA project spec)
                                // over emphasizes the size restrictions of a DecompressionChunk.
                                var largerBuffer = new byte[buffer.Length + 4098];
                                Array.Copy(buffer, largerBuffer, decomprPos);
                                buffer = largerBuffer;
                            }

                            // Even though we've written to the MemoryStream,
                            // We still should decompress the token into this buffer
                            // in case a later token needs to use the bytes we're
                            // about to decompress.
                            for (int c = 0; c < length; c++)
                            {
                                ms.WriteByte(buffer[source]); //Must copy byte-wise because copytokens can overlap compressed buffer.
                                buffer[decomprPos++] = buffer[source++];
                            }

                            pos += 2;

                        }
                        if (pos >= endPos)
                            break;
                    }
                }
                return;
            }
            else //Raw chunk
            {
                ms.Write(compBuffer, pos, size);
                pos += size;
                return;
            }
        }

19 View Source File : ImageFormats.cs
License : GNU General Public License v3.0
Project Creator : arklumpus

public unsafe static void SavePNG(byte* image, int width, int height, bool hasAlpha, Stream fs, FilterModes filter, int threadCount = 0)
        {
            if (threadCount == 0)
            {
                threadCount = filter == FilterModes.Adaptive ? Math.Max(1, Math.Min(width / 600, Environment.ProcessorCount - 2)) : 1;
            }

            //Header
            fs.Write(new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A }, 0, 8);

            //IHDR chunk
            fs.WriteInt(13);
            using (MemoryStream ihdr = new MemoryStream(13))
            {
                ihdr.WriteASCIIString("IHDR");
                ihdr.WriteInt(width);
                ihdr.WriteInt(height);
                ihdr.WriteByte(8); //Bit depth
                
                if (hasAlpha)
                {
                    ihdr.WriteByte(6); //Colour type
                }
                else
                {
                    ihdr.WriteByte(2); //Colour type
                }
                
                ihdr.WriteByte(0); //Compression method
                ihdr.WriteByte(0); //Filter method
                ihdr.WriteByte(0); //Interlace

                ihdr.Seek(0, SeekOrigin.Begin);
                ihdr.CopyTo(fs);

                fs.WriteUInt(CRC32.ComputeCRC(ihdr));
            }

            //IDAT chunk
            IntPtr filteredImage;
            
            if (threadCount > 1)
            {
                filteredImage = FilterImageData(image, width, height, hasAlpha ? 4 : 3, FilterModes.Adaptive, threadCount);
            }
            else
            {
                filteredImage = FilterImageData(image, width, height, hasAlpha ? 4 : 3, FilterModes.Adaptive);
            }
            
            using (MemoryStream compressedImage = StreamUtils.ZLibCompress(filteredImage, height * (width * (hasAlpha ? 4 : 3) + 1)))
            {
                compressedImage.Seek(0, SeekOrigin.Begin);
                fs.WriteUInt((uint)compressedImage.Length);
                fs.WriteASCIIString("IDAT");
                compressedImage.Seek(0, SeekOrigin.Begin);
                compressedImage.CopyTo(fs);

                fs.WriteUInt(CRC32.ComputeCRC(compressedImage.GetBuffer(), (int)compressedImage.Length, new byte[] { 73, 68, 65, 84 }));
            }

            Marshal.FreeHGlobal(filteredImage);

            //IEND chunk
            fs.WriteInt(0);
            fs.WriteASCIIString("IEND");
            fs.Write(new byte[] { 0xAE, 0x42, 0x60, 0x82 }, 0, 4);

        }

19 View Source File : ZipExtraData.cs
License : MIT License
Project Creator : ay2015

public void AddLeShort(int toAdd)
		{
			unchecked {
				_newEntry.WriteByte(( byte )toAdd);
				_newEntry.WriteByte(( byte )(toAdd >> 8));
			}
		}

19 View Source File : Page.cs
License : MIT License
Project Creator : azist

internal void EndWriting()
    {
      Ensure(Status.Writing);
      m_Raw.WriteByte(Format.ENTRY_HEADER_EOF_1);
      m_Raw.WriteByte(Format.ENTRY_HEADER_EOF_2);

      //varbit entry header padding
      m_Raw.WriteByte(0xAA);
      m_Raw.WriteByte(0xAA);
      m_Raw.WriteByte(0xAA);

      m_State = Status.Written;
    }

19 View Source File : Page.cs
License : MIT License
Project Creator : azist

internal void EndWriting()
    {
      Ensure(Status.Writing);
      m_Raw.WriteByte(Format.ENTRY_HEADER_EOF_1);
      m_Raw.WriteByte(Format.ENTRY_HEADER_EOF_2);

      //varbit entry header padding
      m_Raw.WriteByte(0xAA);
      m_Raw.WriteByte(0xAA);
      m_Raw.WriteByte(0xAA);

      m_State = Status.Written;
    }

19 View Source File : Page.cs
License : MIT License
Project Creator : azist

public int Append(ArraySegment<byte> entry)
    {
      Ensure(Status.Writing);
      Aver.IsTrue(entry.Array != null && entry.Count > 0);

      var addr = (int)m_Raw.Position;

      Aver.IsTrue(entry.Count < Format.ENTRY_MAX_LEN, "exceeded ENTRY_MAX_LEN");
      Aver.IsTrue(addr + entry.Count < Format.PAGE_MAX_BUFFER_LEN, "exceeded PAGE_MAX_BUFFER_LEN");

      m_Raw.WriteByte(Format.ENTRY_HEADER_1);
      m_Raw.WriteByte(Format.ENTRY_HEADER_2);
      writeVarLength(m_Raw, entry.Count);

      m_Raw.Write(entry.Array, entry.Offset, entry.Count);

      return addr;
    }

19 View Source File : Page.cs
License : MIT License
Project Creator : azist

[MethodImpl(MethodImplOptions.AggressiveInlining)]
    private static void writeVarLength(MemoryStream stream, int length)
    {
      uint value = (uint)length;
      var has = true;
      while (has)
      {
        byte b = (byte)(value & 0x7f);
        value = value >> 7;
        has = value != 0;
        if (has)
          b = (byte)(b | 0x80);
        stream.WriteByte(b);
      }
    }

19 View Source File : JokeCalculatorClientForm.cs
License : MIT License
Project Creator : azist

private void m_btnStream_Click(object sender, EventArgs e)
    {
      var buf = new byte[317];
      using (var ms = new MemoryStream(buf))
      {
        ms.WriteByte(14);
        ms.SetLength(40);
        ms.SetLength(310);
      }

      MessageBox.Show(buf[0].ToString(), "");
    }

19 View Source File : BSONTestForm.cs
License : MIT License
Project Creator : azist

private void button6_Click(object sender, EventArgs e)
    {
      var message = string.Empty;
      var value = 1999;
      var timer = new Stopwatch();
      using (var stream = new MemoryStream())
      {
        timer.Start();
        var buffer = new byte[4];
        for (int i=0; i<10000000; i++)
        {
          buffer[0] = (byte)value;
          buffer[1] = (byte)(value >> 8);
          buffer[2] = (byte)(value >> 16);
          buffer[3] = (byte)(value >> 24);
          stream.Write(buffer, 0, 4);
        }
        timer.Stop();
        message += "Writing int as byte array to stream (10000000 iters): " + timer.ElapsedMilliseconds;
      }

      timer.Reset();
      using (var stream = new MemoryStream())
      {
        timer.Start();
        for (int i=0; i<10000000; i++)
        {
          stream.WriteByte((byte)value);
          stream.WriteByte((byte)(value >> 8));
          stream.WriteByte((byte)(value >> 16));
          stream.WriteByte((byte)(value >> 34));
        }
        timer.Stop();
        message +=  Environment.NewLine + "Writing int byte by byte to stream (10000000 iters): " + timer.ElapsedMilliseconds;
      }

      label3.Text = message;
    }

19 View Source File : MultipartTests.cs
License : MIT License
Project Creator : azist

[Run]
    public void EncodeToStreamDecode()
    {
      var partField = getDefaultField();
      var partFile = getDefaultFile();

      var stream = new MemoryStream();
      stream.WriteByte(0xFF);
      stream.WriteByte(0xFF);

      var mpE = new Multipart(new Multipart.Part[] { partField, partFile });
      var enc = mpE.Encode(stream);
      Aver.AreEqual(enc.StartIdx, 2);

      var src = new byte[enc.Length];
      Array.Copy(enc.Buffer, enc.StartIdx, src, 0, src.Length);

      string boundary = null;
      var mpD = Multipart.ReadFromBytes(src, ref boundary);

      Aver.AreEqual(enc.Boundary, boundary);
      Aver.AreEqual(partField.Content.replacedtring(), mpD.Parts[partField.Name].Content.replacedtring());
      Aver.IsNull(mpD.Parts[partField.Name].ContentType);
      Aver.IsNull(mpD.Parts[partField.Name].FileName);
      Aver.AreEqual(partFile.FileName, mpD.Parts[partFile.Name].FileName);
      Aver.AreEqual(partFile.ContentType, mpD.Parts[partFile.Name].ContentType);
      Aver.IsTrue(IOUtils.MemBufferEquals(partFile.Content as byte[], mpD.Parts[partFile.Name].Content as byte[]));
    }

19 View Source File : DefaultVolumeTests.cs
License : MIT License
Project Creator : azist

[Run("compress=null pgsz=1024  cnt=2000")]
    [Run("compress=null pgsz=16000 cnt=2000")]
    [Run("compress=gzip pgsz=1024  cnt=2000")]
    [Run("compress=gzip pgsz=16000 cnt=2000")]
    public void Corrupt_Volume_Read(string compress, int pgsz, int cnt)
    {
      var ms = new MemoryStream();
      var meta = VolumeMetadataBuilder.Make("String archive", StringArchiveAppender.CONTENT_TYPE_STRING)
                                      .SetVersion(1, 0)
                                      .SetDescription("Testing string messages")
                                      .SetChannel(Atom.Encode("dvop"))
                                      .SetCompressionScheme(compress);

      var volume = new DefaultVolume(NOPApplication.Instance.SecurityManager.Cryptography, meta, ms)
      {
          PageSizeBytes = pgsz
      };

      using(var appender = new StringArchiveAppender(volume, NOPApplication.Instance.TimeSource, new Atom(65), "[email protected]"))
      {
        for(var i=0; i<cnt; i++)
        {
          appender.Append("string-data--------------------------------------------------------" + i.ToString());
        }
      }

      "Volume size is {0:n0} bytes".SeeArgs(ms.Length);

      var reader = new StringArchiveReader(volume);

      var allCount = reader.All.Count();
      Aver.AreEqual(cnt, allCount);

      reader.All.ForEach( (s, i) => Aver.IsTrue(s.EndsWith("---" + i.ToString())));

      var pageCount = reader.GetPagesStartingAt(0).Count();
      Aver.IsTrue(pageCount > 0);

      "Before corruption: there are {0:n0} total records in {1:n0} pages".SeeArgs(allCount, pageCount);

      var midPoint = ms.Length / 2;
      ms.Position = midPoint;
      for(var j=0; j<pgsz*2; j++) ms.WriteByte(0x00);//corruption

      "-------------- corrupted {0:n0} bytes of {1:n0} total at {2:n0} position -----------  ".SeeArgs(pgsz*2, ms.Length, midPoint);

      var allCount2 = reader.GetEntriesStartingAt(new Bookmark(), skipCorruptPages: true).Count();
      Aver.IsTrue( allCount > allCount2);

      var pageCount2 = reader.GetPagesStartingAt(0, skipCorruptPages: true).Count();
      Aver.IsTrue(pageCount > pageCount2);

      "After corruption: there are {0:n0} total records in {1:n0} pages".SeeArgs(allCount2, pageCount2);

      volume.Dispose();
    }

19 View Source File : PEMEncoder.cs
License : Apache License 2.0
Project Creator : Azure-App-Service

private static void WriteLength(this MemoryStream mem, int length)
        {
            if (length > 127)
            {
                int size = 1;
                uint val = (uint)length;

                while ((val >>= 8) != 0)
                {
                    size++;
                }

                mem.WriteByte((byte)(size | 0x80));

                for (int i = (size - 1) * 8; i >= 0; i -= 8)
                {
                    mem.WriteByte((byte)(length >> i));
                }
            }
            else
            {
                mem.WriteByte((byte)length);
            }
        }

19 View Source File : PEMEncoder.cs
License : Apache License 2.0
Project Creator : Azure-App-Service

private static void WriteTag(this MemoryStream mem, int tag)
        {
            mem.WriteByte((byte)tag);
        }

19 View Source File : Utils.cs
License : MIT License
Project Creator : baking-bad

internal static byte[] Serialize(KeyPath keyPath)
        {
            replacedertKeyPath(keyPath);
            MemoryStream memoryStream = new MemoryStream();
            memoryStream.WriteByte((byte) keyPath.Indexes.Length);
            for (int index = 0; index < keyPath.Indexes.Length; ++index)
            {
                byte[] bytes = ToBytes(keyPath.Indexes[index], false);
                memoryStream.Write(bytes, 0, bytes.Length);
            }
            return memoryStream.ToArray();
        }

19 View Source File : StringTable.cs
License : The Unlicense
Project Creator : BAndysc

public int Write(string str, bool duplicates = false, bool stripCr = true)
        {
            if (stripCr)
                str = str.Replace("\r\n", "\n").Replace(Environment.NewLine, "\n");

            var offset = 0;
            if (str == "") //Empty string always 0
                return offset;

            //WDB2 with MaxId allows duplicates else distinct strings
            if (duplicates || !stringlookup.TryGetValue(str, out offset))
            {
                byte[] strBytes = Encoding.UTF8.GetBytes(str);
                offset = (int) StringStream.Position;

                if (!duplicates)
                    stringlookup.Add(str, offset);

                StringStream.Write(strBytes, 0, strBytes.Length);
                StringStream.WriteByte(0);
            }

            return offset;
        }

19 View Source File : IconFactory.cs
License : Apache License 2.0
Project Creator : beckzhu

public static Cursor CreateCursor(double rx, double ry, SolidColorBrush brush, Pen pen)
        {
            var vis = new DrawingVisual();
            using (var dc = vis.RenderOpen())
            {
                dc.DrawRectangle(brush, new Pen(Brushes.Black, 0.1), new Rect(0, 0, rx, ry));
                dc.Close();
            }
            var rtb = new RenderTargetBitmap(64, 64, 96, 96, PixelFormats.Pbgra32);
            rtb.Render(vis);

            using (var ms1 = new MemoryStream())
            {
                var penc = new PngBitmapEncoder();
                penc.Frames.Add(BitmapFrame.Create(rtb));
                penc.Save(ms1);

                var pngBytes = ms1.ToArray();
                var size = pngBytes.GetLength(0);

                //.cur format spec http://en.wikipedia.org/wiki/ICO_(file_format)
                using (var ms = new MemoryStream())
                {
                    {
                        //ICONDIR Structure
                        ms.Write(BitConverter.GetBytes((Int16)0), 0, 2); //Reserved must be zero; 2 bytes
                        ms.Write(BitConverter.GetBytes((Int16)2), 0, 2); //image type 1 = ico 2 = cur; 2 bytes
                        ms.Write(BitConverter.GetBytes((Int16)1), 0, 2); //number of images; 2 bytes
                    }

                    {
                        //ICONDIRENTRY structure
                        ms.WriteByte(32); //image width in pixels
                        ms.WriteByte(32); //image height in pixels

                        ms.WriteByte(0); //Number of Colors in the color palette. Should be 0 if the image doesn't use a color palette
                        ms.WriteByte(0); //reserved must be 0

                        ms.Write(BitConverter.GetBytes((Int16)(rx / 2.0)), 0, 2); //2 bytes. In CUR format: Specifies the horizontal coordinates of the hotspot in number of pixels from the left.
                        ms.Write(BitConverter.GetBytes((Int16)(ry / 2.0)), 0, 2); //2 bytes. In CUR format: Specifies the vertical coordinates of the hotspot in number of pixels from the top.

                        ms.Write(BitConverter.GetBytes(size), 0, 4); //Specifies the size of the image's data in bytes
                        ms.Write(BitConverter.GetBytes((Int32)22), 0, 4); //Specifies the offset of BMP or PNG data from the beginning of the ICO/CUR file
                    }

                    ms.Write(pngBytes, 0, size); //write the png data.
                    ms.Seek(0, SeekOrigin.Begin);
                    return new Cursor(ms);
                }
            }
        }

19 View Source File : Tag.cs
License : GNU General Public License v3.0
Project Creator : Bililive

internal static Stream HexStringToMemoryStream(string hex)
            {
                var stream = new MemoryStream(hex.Length / 2);
                for (var i = 0; i < hex.Length; i += 2)
                    stream.WriteByte(Convert.ToByte(hex.Substring(i, 2), 16));
                return stream;
            }

19 View Source File : BCTest.cs
License : MIT License
Project Creator : BlazorExtensions

private async Task<byte[]> WritePacket(USBDevice device, byte[] data)
        {
            var toCRC = new MemoryStream();
            await toCRC.WriteAsync(data, 0, data.Length);
            toCRC.WriteByte(PinPadConstants.ETB);
            var crc = toCRC.ToArray().ComputeCRC16();

            // <SYN>[MESSAGE]<ETB>{CRC}
            var output = new MemoryStream();
            output.WriteByte(PinPadConstants.SYN); //<SYN>
            await output.WriteAsync(data, 0, data.Length); //[MESSAGE]
            output.WriteByte(PinPadConstants.ETB); //<ETB>
            await output.WriteAsync(crc, 0, crc.Length); //{CRC}

            var outputData = output.ToArray();
            this._logger.LogInformation($"{PinPadConstants.APP_TO_PINPAD} {PacketToString(outputData)}");

            var trxResult = await device.TransferOut(2, outputData);

            if (trxResult.Status != USBTransferStatus.OK)
            {
                this._logger.LogWarning("NOT OK!!!");
                this._logger.LogWarning(trxResult);
            }
            this._logger.LogInformation(trxResult);
            int sendFailures = 0;
            var readResult = await device.TransferIn(1, 64);
            this._logger.LogInformation(readResult);
            var read = readResult.Data[0];

            while (read == PinPadConstants.NAK && sendFailures < 3)
            {
                this._logger.LogInformation($"{PinPadConstants.PINPAD_TO_APP} {PinPadConstants.NAK_STR}");
                trxResult = await device.TransferOut(2, outputData);
                if (trxResult.Status != USBTransferStatus.OK)
                {
                    this._logger.LogWarning("WRITE NOT OK!!!");
                    this._logger.LogWarning(trxResult);
                }
                readResult = await device.TransferIn(1, 64);
                if (readResult.Status != USBTransferStatus.OK)
                {
                    this._logger.LogWarning("READ NOT OK!!!");
                    this._logger.LogWarning(readResult);
                }
                read = readResult.Data[0];
                sendFailures++;
                this._logger.LogInformation($"Failures: {sendFailures}");
            }

            if (read != PinPadConstants.ACK) throw new InvalidOperationException(PinPadConstants.NAK_STR);

            this._logger.LogInformation($"{PinPadConstants.PINPAD_TO_APP} {PinPadConstants.ACK_STR}");

            var response = new MemoryStream();

            if (readResult.Data.Length > 1 && readResult.Data.Length < 64)
            {
                await response.WriteAsync(readResult.Data, 0, readResult.Data.Length);
            }
            else
            {
                do
                {
                    this._logger.LogInformation($"Reading mode data...");
                    readResult = await device.TransferIn(1, 64);
                    await response.WriteAsync(readResult.Data, 0, readResult.Data.Length);
                } while (readResult.Data.Length == 64);
            }

            this._logger.LogInformation($"Data length: {response.Length}");

            return await ReadPacket(device, response.ToArray());
        }

19 View Source File : BCTest.cs
License : MIT License
Project Creator : BlazorExtensions

internal async Task<byte[]> ReadPacket(USBDevice device, byte[] packet)
        {
            var input = new MemoryStream();

            for (int i = 0; i < packet.Length; i++)
            {
                var readedByte = packet[i];
                if (readedByte == PinPadConstants.ACK || readedByte == PinPadConstants.NAK) continue;
                input.WriteByte(readedByte);

                if (readedByte == PinPadConstants.SYN) continue;

                if (readedByte == PinPadConstants.ETB)
                {
                    var data = input.ToArray().Skip(1).ToArray();
                    await device.TransferOut(2, new byte[] { PinPadConstants.ACK });
                    return data.Take(data.Length - 1).ToArray();
                }
            }
            return null;
        }

19 View Source File : MessageBuilder.cs
License : MIT License
Project Creator : bmresearch

internal byte[] Build()
        {
            if (RecentBlockHash == null && NonceInformation == null)
                throw new Exception("recent block hash or nonce information is required");
            if (Instructions == null)
                throw new Exception("no instructions provided in the transaction");

            // In case the user specified nonce information, we'll use it.
            if (NonceInformation != null)
            {
                RecentBlockHash = NonceInformation.Nonce;
                _accountKeysList.Add(NonceInformation.Instruction.Keys);
                _accountKeysList.Add(AccountMeta.ReadOnly(new PublicKey(NonceInformation.Instruction.ProgramId),
                    false));
                List<TransactionInstruction> newInstructions = new() { NonceInformation.Instruction };
                newInstructions.AddRange(Instructions);
                Instructions = newInstructions;
            }

            _messageHeader = new MessageHeader();

            List<AccountMeta> keysList = GetAccountKeys();
            byte[] accountAddressesLength = ShortVectorEncoding.EncodeLength(keysList.Count);
            int compiledInstructionsLength = 0;
            List<CompiledInstruction> compiledInstructions = new();

            foreach (TransactionInstruction instruction in Instructions)
            {
                int keyCount = instruction.Keys.Count;
                byte[] keyIndices = new byte[keyCount];

                for (int i = 0; i < keyCount; i++)
                {
                    keyIndices[i] = (byte)FindAccountIndex(keysList, instruction.Keys[i].PublicKeyBytes);
                }

                CompiledInstruction compiledInstruction = new CompiledInstruction
                {
                    ProgramIdIndex = (byte)FindAccountIndex(keysList, instruction.ProgramId),
                    KeyIndicesCount = ShortVectorEncoding.EncodeLength(keyCount),
                    KeyIndices = keyIndices,
                    DataLength = ShortVectorEncoding.EncodeLength(instruction.Data.Length),
                    Data = instruction.Data
                };
                compiledInstructions.Add(compiledInstruction);
                compiledInstructionsLength += compiledInstruction.Length();
            }

            int accountKeysBufferSize = _accountKeysList.AccountList.Count * 32;
            MemoryStream accountKeysBuffer = new MemoryStream(accountKeysBufferSize);
            byte[] instructionsLength = ShortVectorEncoding.EncodeLength(compiledInstructions.Count);

            foreach (AccountMeta accountMeta in keysList)
            {
                accountKeysBuffer.Write(accountMeta.PublicKeyBytes);
                if (accountMeta.IsSigner)
                {
                    _messageHeader.RequiredSignatures += 1;
                    if (!accountMeta.IsWritable)
                        _messageHeader.ReadOnlySignedAccounts += 1;
                }
                else
                {
                    if (!accountMeta.IsWritable)
                        _messageHeader.ReadOnlyUnsignedAccounts += 1;
                }
            }

            #region Build Message Body

            int messageBufferSize = MessageHeader.Layout.HeaderLength + BlockHashLength +
                                    accountAddressesLength.Length +
                                    +instructionsLength.Length + compiledInstructionsLength + accountKeysBufferSize;
            MemoryStream buffer = new MemoryStream(messageBufferSize);
            byte[] messageHeaderBytes = _messageHeader.ToBytes();

            buffer.Write(messageHeaderBytes);
            buffer.Write(accountAddressesLength);
            buffer.Write(accountKeysBuffer.ToArray());
            buffer.Write(Encoders.Base58.DecodeData(RecentBlockHash));
            buffer.Write(instructionsLength);

            foreach (CompiledInstruction compiledInstruction in compiledInstructions)
            {
                buffer.WriteByte(compiledInstruction.ProgramIdIndex);
                buffer.Write(compiledInstruction.KeyIndicesCount);
                buffer.Write(compiledInstruction.KeyIndices);
                buffer.Write(compiledInstruction.DataLength);
                buffer.Write(compiledInstruction.Data);
            }

            #endregion

            return buffer.ToArray();
        }

19 View Source File : Message.cs
License : MIT License
Project Creator : bmresearch

public byte[] Serialize()
        {
            byte[] accountAddressesLength = ShortVectorEncoding.EncodeLength(AccountKeys.Count);
            byte[] instructionsLength = ShortVectorEncoding.EncodeLength(Instructions.Count);
            int accountKeysBufferSize = AccountKeys.Count * 32;

            MemoryStream accountKeysBuffer = new(accountKeysBufferSize);

            foreach (PublicKey key in AccountKeys)
            {
                accountKeysBuffer.Write(key.KeyBytes);
            }

            int messageBufferSize = MessageHeader.Layout.HeaderLength + PublicKey.PublicKeyLength +
                                    accountAddressesLength.Length +
                                    +instructionsLength.Length + Instructions.Count + accountKeysBufferSize;
            MemoryStream buffer = new(messageBufferSize);
            buffer.Write(Header.ToBytes());
            buffer.Write(accountAddressesLength);
            buffer.Write(accountKeysBuffer.ToArray());
            buffer.Write(Encoders.Base58.DecodeData(RecentBlockhash));
            buffer.Write(instructionsLength);

            foreach (CompiledInstruction compiledInstruction in Instructions)
            {
                buffer.WriteByte(compiledInstruction.ProgramIdIndex);
                buffer.Write(compiledInstruction.KeyIndicesCount);
                buffer.Write(compiledInstruction.KeyIndices);
                buffer.Write(compiledInstruction.DataLength);
                buffer.Write(compiledInstruction.Data);
            }
            return buffer.ToArray();
        }

19 View Source File : CompressorTests.cs
License : GNU Affero General Public License v3.0
Project Creator : bonimy

[TestMethod]
        public void RepeatedBetweenUncomppressableLongTotal()
        {
            /*
            We run into more edge case pain when one or both sides of uncompressable data is over 32 bytes, when we get into long commands.

            When both sides are uncompressable, each side is less than 32 bytes, but the total section size is greater than 32 bytes, inserting the repeated byte copy saves space.

            data:   [n <= 0x20 bytes] 00 00 00 [m <= 0x20 bytes] : n + m + 3 > 0x20
            best:   0n [n bytes]|22 00|0m [m bytes] = (1 + n) + 2 +(1 + m) bytes
            alt:    xx xx [n + m + 3 bytes]         =  2 +(n + m + 3) bytes
            */

            // Specify the sizes of the uncompressed data's left and right uncompressable sequences.
            var leftUncompressedSize = 0x10;
            var repeatedByteSize = 3;
            var rightUncompressedSize = 0x10;

            var uncompressedData = CreateRepeatedBetweenUncompressable(
                leftUncompressedSize,
                repeatedByteSize,
                rightUncompressedSize);

            var leftCompressedSize = leftUncompressedSize + 1;
            var rightCompressedSize = rightUncompressedSize + 1;

            var compressedSize = leftCompressedSize
                + 2
                + rightCompressedSize
                + 1;

            var expectedCompressedData = new byte[compressedSize];
            using (var stream = new MemoryStream(expectedCompressedData))
            {
                stream.WriteByte(
                    (byte)(leftUncompressedSize - 1));

                stream.Write(
                    Uncompressable,
                    0,
                    leftUncompressedSize);

                stream.WriteByte(
                    (byte)(0x20 | (repeatedByteSize - 1)));

                stream.Seek(1, SeekOrigin.Current);

                stream.WriteByte(
                    (byte)(rightUncompressedSize - 1));

                stream.Write(
                    Uncompressable,
                    leftUncompressedSize,
                    rightUncompressedSize);

                stream.WriteByte(0xFF);
            }

            replacedertCompressionQuality(
                uncompressedData,
                expectedCompressedData);
        }

19 View Source File : CompressorTests.cs
License : GNU Affero General Public License v3.0
Project Creator : bonimy

private static void replacedertRepeatedBetweenLongUncompressable(
            int leftUncompressedSize,
            int repeatedByteSize,
            int rightUncompressedSize)
        {
            var uncompressedData = CreateRepeatedBetweenUncompressable(
                leftUncompressedSize,
                repeatedByteSize,
                rightUncompressedSize);

            var compressedSize = 2
                + leftUncompressedSize
                + repeatedByteSize
                + rightUncompressedSize
                + 1;

            var expectedCompressedData = new byte[compressedSize];
            using (var stream = new MemoryStream(expectedCompressedData))
            {
                var writeSize = uncompressedData.Length - 1;
                stream.WriteByte(
                    (byte)(0xE0 | (writeSize >> 8)));

                stream.WriteByte(
                    (byte)writeSize);

                stream.Write(
                    Uncompressable,
                    0,
                    leftUncompressedSize);

                stream.Seek(
                    repeatedByteSize,
                    SeekOrigin.Current);

                stream.Write(
                    Uncompressable,
                    leftUncompressedSize,
                    rightUncompressedSize);

                stream.WriteByte(0xFF);
            }

            replacedertCompressionQuality(
                uncompressedData,
                expectedCompressedData);
        }

19 View Source File : HttpUtility.cs
License : MIT License
Project Creator : bonzaiferroni

internal static string UrlDecodeInternally (
      byte [] bytes, int offset, int count, Encoding encoding)
    {
      var output = new StringBuilder ();
      using (var acc = new MemoryStream ()) {
        var end = count + offset;

        int xchar;
        for (int i = offset; i < end; i++) {
          if (bytes [i] == '%' && i + 2 < count && bytes [i + 1] != '%') {
            if (bytes [i + 1] == (byte) 'u' && i + 5 < end) {
              if (acc.Length > 0) {
                output.Append (getChars (acc, encoding));
                acc.SetLength (0);
              }

              xchar = getChar (bytes, i + 2, 4);
              if (xchar != -1) {
                output.Append ((char) xchar);
                i += 5;

                continue;
              }
            }
            else if ((xchar = getChar (bytes, i + 1, 2)) != -1) {
              acc.WriteByte ((byte) xchar);
              i += 2;

              continue;
            }
          }

          if (acc.Length > 0) {
            output.Append (getChars (acc, encoding));
            acc.SetLength (0);
          }

          if (bytes [i] == '+')
            output.Append (' ');
          else
            output.Append ((char) bytes [i]);
        }

        if (acc.Length > 0)
          output.Append (getChars (acc, encoding));
      }

      return output.ToString ();
    }

19 View Source File : HttpUtility.cs
License : MIT License
Project Creator : bonzaiferroni

internal static byte [] UrlDecodeToBytesInternally (byte [] bytes, int offset, int count)
    {
      using (var res = new MemoryStream ()) {
        var end = offset + count;
        for (int i = offset; i < end; i++) {
          var c = (char) bytes [i];
          if (c == '+') {
            c = ' ';
          }
          else if (c == '%' && i < end - 2) {
            var xchar = getChar (bytes, i + 1, 2);
            if (xchar != -1) {
              c = (char) xchar;
              i += 2;
            }
          }

          res.WriteByte ((byte) c);
        }

        res.Close ();
        return res.ToArray ();
      }
    }

19 View Source File : Hybi13Handler.cs
License : GNU General Public License v3.0
Project Creator : bp2008

public static byte[] FrameData(byte[] payload, FrameType frameType)
        {
            var memoryStream = new MemoryStream();
            byte op = (byte)((byte)frameType + 128);
            
            memoryStream.WriteByte(op);
            
            if (payload.Length > UInt16.MaxValue) {
                memoryStream.WriteByte(127);
                var lengthBytes = payload.Length.ToBigEndianBytes<ulong>();
                memoryStream.Write(lengthBytes, 0, lengthBytes.Length);
            } else if (payload.Length > 125) {
                memoryStream.WriteByte(126);
                var lengthBytes = payload.Length.ToBigEndianBytes<ushort>();
                memoryStream.Write(lengthBytes, 0, lengthBytes.Length);
            } else {
                memoryStream.WriteByte((byte)payload.Length);
            }
            
            memoryStream.Write(payload, 0, payload.Length);
            
            return memoryStream.ToArray();
        }

See More Examples