/// <summary> /// This method is called when stream is requested, if you return a stream /// it will return it to the user else it will keep trying all the other StreamFactorys /// until one does return a stream. /// </summary> /// <param name="path">Path of file or object to create stream to.</param> /// <param name="mode">Determines how to open or create stream.</param> /// <returns>A Stream instance or NULL if this factory can't open the given stream.</returns> protected override Stream Request(object path, StreamMode mode) { // if (File.Exists(path.ToString()) == false && moede != StreamMode.Open) return null; try { switch (mode) { case StreamMode.Append: if (Directory.Exists(Path.GetDirectoryName(path.ToString()))) Directory.CreateDirectory(Path.GetDirectoryName(path.ToString())); if (File.Exists(path.ToString()) == false) File.Create(path.ToString()).Close(); return new FileStream(path.ToString(), FileMode.Append); case StreamMode.Open: return new FileStream(path.ToString(), FileMode.Open); case StreamMode.Truncate: if (Directory.Exists(Path.GetDirectoryName(path.ToString()))) Directory.CreateDirectory(Path.GetDirectoryName(path.ToString())); if (File.Exists(path.ToString()) == false) File.Create(path.ToString()).Close(); return new FileStream(path.ToString(), FileMode.Truncate); } } catch (Exception) {} return null; }
public Decrypt2Stream(Stream input, int size, uint key, StreamMode streamMode) { _input = input; _size = size; _streamMode = streamMode; _key = 278 * key; _blockKey = key | ((key ^ 25974) << 16); }
public void InitializeWrite(string sPath) { ActiveMode = StreamMode.WriteToDiskStream; disk_writer = new BinaryWriter(File.Open(sPath, FileMode.Create)); writer_thread = new Thread(writer_thread_func); writer_thread.Start(); }
/// <summary> /// This method is called when stream is requested, if you return a stream /// it will return it to the user else it will keep trying all the other StreamFactorys /// until one does return a stream. /// </summary> /// <param name="path">Path of file or object to create stream to.</param> /// <param name="mode">Determines how to open or create stream.</param> /// <returns>A Stream instance or NULL if this factory can't open the given stream.</returns> protected override Stream Request(object path, StreamMode mode) { if (Resources.ResourceManager.ResourceExists(path, true) == false) { return(null); } return(Resources.ResourceManager.RequestResourceStream(path.ToString())); }
// workitem 7813 - totally unnecessary // public override void WriteByte(byte b) // { // _buf1[0] = (byte)b; // // workitem 7159 // if (crc != null) // crc.SlurpBlock(_buf1, 0, 1); // Write(_buf1, 0, 1); // } public override void Write(byte[] buffer, int offset, int count) { // workitem 7159 // calculate the CRC on the unccompressed data (before writing) if (this.crc != null) { this.crc.SlurpBlock(buffer, offset, count); } if (this.streamMode == StreamMode.Undefined) { this.streamMode = StreamMode.Writer; } else if (this.streamMode != StreamMode.Writer) { throw new ZlibException("Cannot Write after Reading."); } if (count == 0) { return; } // first reference of z property will initialize the private var _z this.z.InputBuffer = buffer; this.z.NextIn = offset; this.z.AvailableBytesIn = count; bool done; do { this.z.OutputBuffer = this.WorkingBuffer; this.z.NextOut = 0; this.z.AvailableBytesOut = this.workingBuffer.Length; //int rc = (_wantCompress) // ? _z.Deflate(_flushMode) // : _z.Inflate(_flushMode); int rc = this.z.Inflate(this.FlushMode); if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END) { throw new ZlibException("inflating: " + this.z.Message); } this.Stream.Write(this.workingBuffer, 0, this.workingBuffer.Length - this.z.AvailableBytesOut); done = this.z.AvailableBytesIn == 0 && this.z.AvailableBytesOut != 0; // If GZIP and de-compress, we're done when 8 bytes remain. if (this.Flavor == ZlibStreamFlavor.Gzip) { done = (this.z.AvailableBytesIn == 8 && this.z.AvailableBytesOut != 0); } }while (!done); }
public void Process(StreamMode mode, StreamData data, Action <byte[], int> callback) { if (!_disposed) { var request = new AsyncStreamRequest(mode, data, callback); var task = new StreamTask(GetIdleUnit(), request); ThreadPool.QueueUserWorkItem(_ => { task.Run(); }); } }
public static Table Get(string tableName, StreamMode LoadSteam) { if (!tableMap.ContainsKey(tableName)) { Table newTable = GenerateTable(tableName, LoadSteam); tableMap.Add(tableName, newTable); } return(tableMap[tableName]); }
public override void Write(System.Byte[] buffer, int offset, int count) { #if !NETFX_CORE // workitem 7159 // calculate the CRC on the unccompressed data (before writing) if (crc != null) { crc.SlurpBlock(buffer, offset, count); } #endif if (_streamMode == StreamMode.Undefined) { _streamMode = StreamMode.Writer; } else if (_streamMode != StreamMode.Writer) { throw new ZlibException("Cannot Write after Reading."); } if (count == 0) { return; } // first reference of z property will initialize the private var _z z.InputBuffer = buffer; _z.NextIn = offset; _z.AvailableBytesIn = count; bool done = false; do { _z.OutputBuffer = workingBuffer; _z.NextOut = 0; _z.AvailableBytesOut = _workingBuffer.Length; int rc = (_wantCompress) ? _z.Deflate(_flushMode) : _z.Inflate(_flushMode); if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END) { throw new ZlibException((_wantCompress ? "de" : "in") + "flating: " + _z.Message); } //if (_workingBuffer.Length - _z.AvailableBytesOut > 0) _stream.Write(_workingBuffer, 0, _workingBuffer.Length - _z.AvailableBytesOut); done = _z.AvailableBytesIn == 0 && _z.AvailableBytesOut != 0; // If GZIP and de-compress, we're done when 8 bytes remain. if (_flavor == ZlibStreamFlavor.GZIP && !_wantCompress) { done = (_z.AvailableBytesIn == 8 && _z.AvailableBytesOut != 0); } }while (!done); }
public QueueStream(Stream stream, StreamMode mode, int bufferSize, BufferManager bufferManager) { if (mode == StreamMode.Read) { _stream = new ReadStream(stream, bufferSize, bufferManager); } else if (mode == StreamMode.Write) { _stream = new WriteStream(new CacheStream(stream, QueueStream.BlockSize, bufferManager), bufferSize, bufferManager); } }
/// <summary> /// Makes the specified font and brush to the current graphics objects. /// </summary> void RealizeFont(Glyphs glyphs) { if (this.streamMode != StreamMode.Text) { this.streamMode = StreamMode.Text; WriteLiteral("BT\n"); // Text matrix is empty after BT this.graphicsState.realizedTextPosition = new XPoint(); } this.graphicsState.RealizeFont(glyphs); }
void ValidStreamMode(StreamMode streamMode) { if (_streamMode == StreamMode.Undefined) { _streamMode = streamMode; } else if (_streamMode != streamMode) { throw new ZlibException(streamMode == StreamMode.Reader ? "无法在读取的时候写入。" : "无法在写入时候读取。"); } }
public Task <int> WriteAsync(byte[] buffer, int offset, int length, StreamMode mode) { Utilities.CheckStreamArguments(buffer, offset, length, mode); int processed = 0; while (length > 0) { Frame frame; lock (mSyncObject) { System.Diagnostics.Debug.Assert(mRunning); if (mDisposeTask != null) { throw new OperationCanceledException(); } while (mQueue.Count == 0) { Monitor.Wait(mSyncObject); if (mDisposeTask != null) { throw new OperationCanceledException(); } } frame = mQueue.Peek(); } var capacity = frame.mEnding - frame.mOffset; var copySize = Math.Min(capacity, length > Int32.MaxValue ? Int32.MaxValue : (int)length); Buffer.BlockCopy(buffer, offset, frame.mBuffer, frame.mOffset, copySize); frame.mOffset += copySize; offset += copySize; processed += copySize; length -= copySize; if (copySize == capacity || frame.mMode == StreamMode.Partial) { frame.mCompletion.SetResult(frame.mOffset - frame.mOrigin); lock (mSyncObject) { System.Diagnostics.Debug.Assert(mRunning); var other = mQueue.Dequeue(); System.Diagnostics.Debug.Assert(other == frame); } } } return(Task.FromResult(processed)); }
public Decrypt1Stream(Stream input, int version, int size, byte[] dataHash, uint hashLow, StreamMode streamMode) { _input = input; _version = version; _size = size; _hashLow = hashLow; _streamMode = streamMode; _seed = BitConverter.ToUInt64(dataHash, (int)(hashLow % 2) * 8); _seedLow = (uint)_seed & 0xFFFFFFFF; _seedHigh = (uint)(_seed >> 32); }
public bool Save(StreamMode SaveMode = StreamMode.AppData) { switch (SaveMode) { case StreamMode.AppData: path = (AppDataPath + name + ".csv"); break; case StreamMode.Resource: return(false); } return(Save(path)); }
internal void OpenStream(string key, StreamMode mode, string group, string subGroup, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheDependency dependency, CacheItemPriority priority) { _mode = mode; _key = key; _priority = priority; if (mode == StreamMode.Write) { _absExpiration = absoluteExpiration; _slidingExpiration = slidingExpiration; _dependency = dependency; } if (_mode == StreamMode.Read) { _lockHandle = _cacheHandle.OpenStream(key, StreamModes.Read, group, subGroup, absoluteExpiration, slidingExpiration, dependency, _priority); } else if (mode == StreamMode.ReadWithoutLock) { string lockHandle = _cacheHandle.OpenStream(key, StreamModes.ReadWithoutLock, group, subGroup, absoluteExpiration, slidingExpiration, dependency, _priority); if (lockHandle != null) { return; } else { throw new StreamNotFoundException(); } } else { _lockHandle = _cacheHandle.OpenStream(key, StreamModes.Write, group, subGroup, absoluteExpiration, slidingExpiration, dependency, _priority); } if (_lockHandle == null) { throw new StreamException("An error occurred while opening stream"); } _length = _cacheHandle.GetStreamLength(key, _lockHandle); if (_mode == StreamMode.Write) { _position = Length; } }
void Stream.Write(byte[] A_0, int A_1, int A_2) { // This item is obfuscated and can not be translated. int num = 2; if (this.class356_0 != null) { this.class356_0.method_6(A_0, A_1, A_2); } if (this.streamMode_0 == StreamMode.Undefined) { this.streamMode_0 = StreamMode.Writer; } else if (this.streamMode_0 != StreamMode.Writer) { throw new Exception0(BookmarkStart.b("欧䬩䈫䀭弯䘱ᐳ愵䨷匹䠻嬽怿⍁≃㉅ⵇ㡉汋ᱍ㕏㍑こ㽕㙗㵙牛", num)); } if (A_2 != 0) { this.method_2().byte_0 = A_0; this.class1068_0.int_0 = A_1; this.class1068_0.int_1 = A_2; bool flag = false; while (true) { this.class1068_0.byte_1 = this.method_3(); this.class1068_0.int_2 = 0; this.class1068_0.int_3 = this.byte_0.Length; if (this.method_1()) { } int num2 = this.class1068_0.method_14(this.flushType_0); if ((num2 != 0) && (num2 != 1)) { throw new Exception0((this.method_1() ? BookmarkStart.b("䰧伩", num) : BookmarkStart.b("䄧䐩", num)) + BookmarkStart.b("丧䘩䴫娭夯就匳వᠷ", num) + this.class1068_0.string_0); } this.stream_0.Write(this.byte_0, 0, this.byte_0.Length - this.class1068_0.int_3); flag = (this.class1068_0.int_1 == 0) && (this.class1068_0.int_3 != 0); if ((this.zlibStreamFlavor_0 == ZlibStreamFlavor.GZIP) && !this.method_1()) { flag = (this.class1068_0.int_1 == 8) && (this.class1068_0.int_3 != 0); } if (flag) { return; } } } }
/// <summary>Align the stream's position by a certain page boundry</summary> /// <param name="alignmentBit">log2 size of the alignment (ie, 1<<bit)</param> /// <returns>True if any alignment had to be performed, false if otherwise</returns> public bool AlignToBoundry(int alignmentBit) { if (IsReading) { return(Reader.AlignToBoundry(alignmentBit)); } else if (IsWriting) { return(Writer.AlignToBoundry(alignmentBit)); } else { throw new Debug.UnreachableException(StreamMode.ToString()); } }
public FlacStream(string file, StreamMode mode, StreamAccessMode accessMode) { FileMode fileMode; FileAccess fileAccessMode; switch (mode) { case StreamMode.CreateNew: { fileMode = FileMode.Create; break; } case StreamMode.OpenExisting: { fileMode = FileMode.Open; break; } default: { throw new FlacDebugException(); } } switch (accessMode) { case StreamAccessMode.Read: case StreamAccessMode.Write: case StreamAccessMode.Both: { fileAccessMode = (FileAccess)accessMode; break; } default: { throw new FlacDebugException(); } } fileStream_ = new FileStream(file, fileMode, fileAccessMode, FileShare.Read); if ((accessMode & StreamAccessMode.Read) == StreamAccessMode.Read) { reader_ = new FlacStreamReader(fileStream_); } if ((accessMode & StreamAccessMode.Write) == StreamAccessMode.Write) { writer_ = new FlacStreamWriter(fileStream_); } }
public void InitializeRead(string sPath, bool bReadAll = false) { if (bReadAll) { ActiveMode = StreamMode.InMemoryStream; } else { ActiveMode = StreamMode.ReadFromDiskStream; } disk_reader = new BinaryReader(File.Open(sPath, FileMode.Open)); if (bReadAll) { ReadAllFrames(); } }
public async Task <int> ReadAsync(byte[] buffer, int offset, int length, StreamMode mode) { System.Diagnostics.Debug.Assert(mEncoderInput == null); if (mode == StreamMode.Complete) { throw new NotImplementedException(); } var result = await mSession.ReadInternalAsync(buffer, offset, length, mode).ConfigureAwait(false); mLength += result; mChecksum = CRC.Update(mChecksum, buffer, offset, result); return(result); }
public Container(string containerName, StreamMode mode) { PrimaryTable = SqlStringSanitizer.Sanitize(containerName); var columns = _codeEdgeColumns; if (mode == StreamMode.EventStream) { columns = columns.Union(_eventStreamCodeEdgeColumns).ToArray(); } Tables = new Dictionary <string, Table> { ["Codes"] = new Table($"{PrimaryTable}Codes", columns, _codeEdgeColumns.Select(x => x.Name)), ["Edges"] = new Table($"{PrimaryTable}Edges", columns, _codeEdgeColumns.Select(x => x.Name)) }; }
static void Main(string[] args) { int bufferSize = 1024 * 4; StreamMode mode = StreamMode.FrameworkDefault; if (args.Length < 1) { Proxy.WriteLine("\nError in parameters", ConsoleColor.Red); Console.WriteLine("usage: HttpProxy {StreamMode} {BufferSize} "); Console.WriteLine("\nStreamMode is a number from 0-4: FrameworkDefault, FrameworkBuffer, FrameworkCopy, MultiWrite"); Console.WriteLine("BufferSize is in Bytes\n"); Console.WriteLine("Example\n"); Console.WriteLine("HttpProxy 0"); Console.WriteLine("HttpProxy 1 4096"); Console.WriteLine("HttpProxy 3 4096\n"); return; } // Get Stream Mode int modeInteger; if (int.TryParse(args[0], out modeInteger)) { mode = (StreamMode)modeInteger; } // Get BufferSize if (mode != StreamMode.FrameworkDefault) { if (args.Length > 1) { bufferSize = int.Parse(args[1]); } } var listener = new Proxy(mode, bufferSize); Console.BackgroundColor = ConsoleColor.DarkRed; Console.WriteLine("Press Enter to exit"); Console.BackgroundColor = ConsoleColor.Black; Console.ReadLine(); listener.Shutdown(); }
public Stream OpenStream(Uri uri, StreamMode mode, StreamAccess access, StreamShare share, int bufferSize) { var fmode = FileMode.Append; switch (mode) { case StreamMode.Append: fmode = FileMode.Append; break; case StreamMode.Open: fmode = FileMode.Open; break; case StreamMode.Truncate: fmode = FileMode.Truncate; break; } var filePath = PathFromUri(uri); return(OpenStream(filePath, fmode, access, share, bufferSize)); }
public override void Write(byte[] buffer, int offset, int count) { if (crc != null) { crc.SlurpBlock(buffer, offset, count); } if (_streamMode == StreamMode.Undefined) { _streamMode = StreamMode.Writer; } else if (_streamMode != 0) { throw new ZlibException("Cannot Write after Reading."); } if (count == 0) { return; } z.InputBuffer = buffer; _z.NextIn = offset; _z.AvailableBytesIn = count; bool flag = false; while (true) { _z.OutputBuffer = workingBuffer; _z.NextOut = 0; _z.AvailableBytesOut = _workingBuffer.Length; int num = _wantCompress ? _z.Deflate(_flushMode) : _z.Inflate(_flushMode); if (num != 0 && num != 1) { break; } _stream.Write(_workingBuffer, 0, _workingBuffer.Length - _z.AvailableBytesOut); flag = (_z.AvailableBytesIn == 0 && _z.AvailableBytesOut != 0); if (_flavor == ZlibStreamFlavor.GZIP && !_wantCompress) { flag = (_z.AvailableBytesIn == 8 && _z.AvailableBytesOut != 0); } if (flag) { return; } } throw new ZlibException((_wantCompress ? "de" : "in") + "flating: " + _z.Message); }
public override void Write(byte[] buffer, int offset, int count) { _crc?.SlurpBlock(buffer, offset, count); if (_streamMode == StreamMode.Undefined) { _streamMode = StreamMode.Writer; } else if (_streamMode != StreamMode.Writer) { throw new ZlibException("Cannot Write after Reading."); } if (count == 0) { return; } z.InputBuffer = buffer; Z.NextIn = offset; Z.AvailableBytesIn = count; bool done; do { Z.OutputBuffer = WorkingBuffer; Z.NextOut = 0; Z.AvailableBytesOut = _workingBuffer.Length; var rc = WantCompress ? Z.Deflate(FlushMode) : Z.Inflate(FlushMode); if (rc != ZlibConstants.ZOk && rc != ZlibConstants.ZStreamEnd) { throw new ZlibException((WantCompress ? "de" : "in") + "flating: " + Z.Message); } Stream.Write(_workingBuffer, 0, _workingBuffer.Length - Z.AvailableBytesOut); done = Z.AvailableBytesIn == 0 && Z.AvailableBytesOut != 0; if (Flavor == ZlibStreamFlavor.Gzip && !WantCompress) { done = Z.AvailableBytesIn == 8 && Z.AvailableBytesOut != 0; } } while (!done); }
public ZlibBaseStream(Stream stream, CompressionMode compressionMode, CompressionLevel level, ZlibStreamFlavor flavor, bool leaveOpen, int windowBits) { this._streamMode = StreamMode.Undefined; this._bufferSize = 0x4000; this._buf1 = new byte[1]; this._flushMode = FlushType.None; this._stream = stream; this._leaveOpen = leaveOpen; this._compressionMode = compressionMode; this._flavor = flavor; this._level = level; this.windowBitsMax = windowBits; if (flavor == ZlibStreamFlavor.GZIP) { this.crc = new CRC32(); } }
public async Task <int> WriteAsync(byte[] buffer, int offset, int length, StreamMode mode) { System.Diagnostics.Debug.Assert(mEncoderOutput == null); System.Diagnostics.Debug.Assert(!mCompletionTask.Task.IsCompleted); // TODO: calculate checksum asynchronously? if (mCalculateChecksum) { for (int i = 0; i < length; i++) { mChecksum = CRC.Update(mChecksum, buffer[offset + i]); } } await mStream.WriteAsync(buffer, offset, length).ConfigureAwait(false); return(length); }
Task <int> IStreamReader.ReadAsync(byte[] buffer, int offset, int length, StreamMode mode) { Utilities.DebugCheckStreamArguments(buffer, offset, length, mode); lock (this) { int total = 0; while (length > 0) { while (mBuffer == null) { if (mComplete) { return(Task.FromResult(total)); } Monitor.Wait(this); } int copied = Math.Min(length, mLength); System.Diagnostics.Debug.Assert(copied > 0); Buffer.BlockCopy(mBuffer, mOffset, buffer, offset, copied); mOffset += copied; mLength -= copied; offset += copied; length -= copied; total += copied; if (mLength == 0) { mBuffer = null; Monitor.PulseAll(this); } if (mode == StreamMode.Partial) { break; } } return(Task.FromResult(total)); } }
/// <summary> /// This method is called when a stream is requested, it illiterates through all /// the registered StreamFactory instances to see if there is one capable of opening the /// given stream. /// </summary> /// <param name="path">Path of file or object to create stream to.</param> /// <param name="mode">Determines how to open or create stream.</param> /// <returns>A Stream instance or NULL if unable to find a factory to open this stream.</returns> public static Stream RequestStream(object path, StreamMode mode) { if (path.ToString().ToLower().StartsWith("pak@")) { path = path.ToString().Substring(4); // Legacy support. } // If this is already a stream then copy its data to a new stream // that we can read from. if (path as Stream != null) { Stream stream = (path as Stream); MemoryStream memStream = new MemoryStream(); byte[] data = new byte[stream.Length]; stream.Read(data, 0, (int)stream.Length); stream.Position = 0; memStream.Write(data, 0, data.Length); memStream.Position = 0; return(memStream); } foreach (StreamFactory factory in _loaderList) { #if RELEASE || PROFILE try { #endif Stream stream = factory.Request(path, mode); if (stream != null) { return(stream); } #if RELEASE || PROFILE } catch (System.IO.IOException) { // Don't do anything here, just here to catch any errors that may occur. } #endif } return(null); }
public virtual IEnumerable <PostgreSqlConnectorCommand> BuildCreateContainerSql( string tableName, IEnumerable <ConnectionDataType> columns, IEnumerable <string> keys, string context, StreamMode streamMode, ILogger logger) { if (string.IsNullOrWhiteSpace(tableName)) { throw new InvalidOperationException("The tableName must be provided."); } if (columns == null) { throw new InvalidOperationException("The data to specify columns must be provided."); } var builder = new StringBuilder(); var trimmedColumns = columns.Where(x => x.Name != "Codes").ToList(); builder.AppendLine($"CREATE TABLE IF NOT EXISTS {SqlStringSanitizer.Sanitize(tableName)}("); var index = 0; var count = trimmedColumns.Count; foreach (var column in trimmedColumns) { builder.AppendLine($"{SqlStringSanitizer.Sanitize(column.Name)} text NULL " + // TODO: appoint PK to valid column for StreamMode Event $"{(column.Name.ToLower().Equals("originentitycode") && context == "Data" && streamMode == StreamMode.Sync ? "PRIMARY KEY" : "")}" + $"{(index < count - 1 ? "," : "")} "); index++; } builder.AppendLine(");"); return(new[] { new PostgreSqlConnectorCommand { Text = builder.ToString() } }); }
/// <summary> /// This method is called when stream is requested, if you return a stream /// it will return it to the user else it will keep trying all the other StreamFactorys /// until one does return a stream. /// </summary> /// <param name="path">Path of file or object to create stream to.</param> /// <param name="mode">Determines how to open or create stream.</param> /// <returns>A Stream instance or NULL if this factory can't open the given stream.</returns> protected override Stream Request(object path,StreamMode mode) { if (path.ToString().ToLower().Substring(0, 4) != "mem@") return null; // Check if we have been handed a capacity as well. if (path.ToString().Length > 4) { string capacityStr = path.ToString().Substring(4, path.ToString().Length - 4); int capacity = 0; if (int.TryParse(capacityStr, out capacity) == true) return new MemoryStream(capacity); else return new MemoryStream(); } else { return new MemoryStream(); } }
/// <summary> /// Initializes a new instance of the <see cref="BizTalkMessagePartStream"/> class. /// </summary> /// <param name="stream">The stream from which to read (or write if in compression mode).</param> /// <param name="mode">The compression mode.</param> public BizTalkMessagePartStream(Stream stream, StreamMode mode) { this.innerStream = stream; this.streamMode = mode; if (mode == StreamMode.Write) { this.writeStream = new BizTalkBlockStream(this.innerStream); } else if (mode == StreamMode.Read) { this.reader = new BizTalkBlockReader(stream); this.readBuffer = new MemoryStream(); } else { throw new ArgumentException("Unknown stream mode specified: " + mode, "mode"); } }
public override void Write(byte[] buffer, int offset, int count) { if (this.crc != null) { this.crc.SlurpBlock(buffer, offset, count); } if (this._streamMode == StreamMode.Undefined) { this._streamMode = StreamMode.Writer; } else if (this._streamMode != StreamMode.Writer) { throw new ZlibException("Cannot Write after Reading."); } if (count != 0) { this.z.InputBuffer = buffer; this._z.NextIn = offset; this._z.AvailableBytesIn = count; bool flag = false; while (true) { this._z.OutputBuffer = this.workingBuffer; this._z.NextOut = 0; this._z.AvailableBytesOut = this._workingBuffer.Length; int num = !this._wantCompress ? this._z.Inflate(this._flushMode) : this._z.Deflate(this._flushMode); if ((num != 0) && (num != 1)) { throw new ZlibException((!this._wantCompress ? "in" : "de") + "flating: " + this._z.Message); } this._stream.Write(this._workingBuffer, 0, this._workingBuffer.Length - this._z.AvailableBytesOut); flag = (this._z.AvailableBytesIn == 0) && (this._z.AvailableBytesOut != 0); if ((this._flavor == ZlibStreamFlavor.GZIP) && !this._wantCompress) { flag = (this._z.AvailableBytesIn == 8) && (this._z.AvailableBytesOut != 0); } if (flag) { return; } } } }
Task<int> IStreamReader.ReadAsync(byte[] buffer, int offset, int length, StreamMode mode) { Utilities.DebugCheckStreamArguments(buffer, offset, length, mode); lock (this) { int total = 0; while (length > 0) { while (mBuffer == null) { if (mComplete) return Task.FromResult(total); Monitor.Wait(this); } int copied = Math.Min(length, mLength); System.Diagnostics.Debug.Assert(copied > 0); Buffer.BlockCopy(mBuffer, mOffset, buffer, offset, copied); mOffset += copied; mLength -= copied; offset += copied; length -= copied; total += copied; if (mLength == 0) { mBuffer = null; Monitor.PulseAll(this); } if (mode == StreamMode.Partial) break; } return Task.FromResult(total); } }
public Task<int> WriteAsync(byte[] buffer, int offset, int length, StreamMode mode) { Utilities.CheckStreamArguments(buffer, offset, length, mode); int processed = 0; while (length > 0) { Frame frame; lock (mSyncObject) { System.Diagnostics.Debug.Assert(mRunning); if (mDisposeTask != null) throw new OperationCanceledException(); while (mQueue.Count == 0) { Monitor.Wait(mSyncObject); if (mDisposeTask != null) throw new OperationCanceledException(); } frame = mQueue.Peek(); } var capacity = frame.mEnding - frame.mOffset; var copySize = Math.Min(capacity, length > Int32.MaxValue ? Int32.MaxValue : (int)length); Buffer.BlockCopy(buffer, offset, frame.mBuffer, frame.mOffset, copySize); frame.mOffset += copySize; offset += copySize; processed += copySize; length -= copySize; if (copySize == capacity || frame.mMode == StreamMode.Partial) { frame.mCompletion.SetResult(frame.mOffset - frame.mOrigin); lock (mSyncObject) { System.Diagnostics.Debug.Assert(mRunning); var other = mQueue.Dequeue(); System.Diagnostics.Debug.Assert(other == frame); } } } return Task.FromResult(processed); }
public override int Read( byte [] buffer, int offset, int count ) { if ( streamMode == StreamMode.Undefined ) { if ( !this.stream.CanRead ) throw new CompressionProcessException ( "The stream is not readable." ); streamMode = StreamMode.Reader; z.AvailableBytesIn = 0; } if ( streamMode != StreamMode.Reader ) throw new CompressionProcessException ( "Cannot Read after Writing." ); if ( count == 0 ) return 0; if ( nomoreinput && _wantCompress ) return 0; if ( buffer == null ) throw new ArgumentNullException ( "buffer" ); if ( count < 0 ) throw new ArgumentOutOfRangeException ( "count" ); if ( offset < buffer.GetLowerBound ( 0 ) ) throw new ArgumentOutOfRangeException ( "offset" ); if ( ( offset + count ) > buffer.GetLength ( 0 ) ) throw new ArgumentOutOfRangeException ( "count" ); int rc = 0; _z.OutputBuffer = buffer; _z.NextOut = offset; _z.AvailableBytesOut = count; _z.InputBuffer = workingBuffer; do { if ( ( _z.AvailableBytesIn == 0 ) && ( !nomoreinput ) ) { _z.NextIn = 0; _z.AvailableBytesIn = stream.Read ( _workingBuffer, 0, _workingBuffer.Length ); if ( _z.AvailableBytesIn == 0 ) nomoreinput = true; } rc = ( _wantCompress ) ? _z.Deflate ( flushMode ) : _z.Inflate ( flushMode ); if ( nomoreinput && ( rc == ZlibConstants.Z_BUF_ERROR ) ) return 0; if ( rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END ) throw new CompressionProcessException ( String.Format ( "{0}flating: rc={1} msg={2}", ( _wantCompress ? "de" : "in" ), rc, _z.Message ) ); if ( ( nomoreinput || rc == ZlibConstants.Z_STREAM_END ) && ( _z.AvailableBytesOut == count ) ) break; } while ( _z.AvailableBytesOut > 0 && !nomoreinput && rc == ZlibConstants.Z_OK ); if ( _z.AvailableBytesOut > 0 ) { if ( rc == ZlibConstants.Z_OK && _z.AvailableBytesIn == 0 ) { } if ( nomoreinput ) { if ( _wantCompress ) { rc = _z.Deflate ( FlushType.Finish ); if ( rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END ) throw new CompressionProcessException ( String.Format ( "Deflating: rc={0} msg={1}", rc, _z.Message ) ); } } } rc = ( count - _z.AvailableBytesOut ); return rc; }
public override void Write(System.Byte[] buffer, int offset, int count) { // workitem 7159 // calculate the CRC on the unccompressed data (before writing) if (crc != null) crc.SlurpBlock(buffer, offset, count); if (_streamMode == StreamMode.Undefined) _streamMode = StreamMode.Writer; else if (_streamMode != StreamMode.Writer) throw new ZlibException("Cannot Write after Reading."); if (count == 0) return; // first reference of z property will initialize the private var _z z.InputBuffer = buffer; _z.NextIn = offset; _z.AvailableBytesIn = count; bool done = false; do { _z.OutputBuffer = workingBuffer; _z.NextOut = 0; _z.AvailableBytesOut = _workingBuffer.Length; int rc = (_wantCompress) ? _z.Deflate(_flushMode) : _z.Inflate(_flushMode); if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END) throw new ZlibException((_wantCompress ? "de" : "in") + "flating: " + _z.Message); //if (_workingBuffer.Length - _z.AvailableBytesOut > 0) _stream.Write(_workingBuffer, 0, _workingBuffer.Length - _z.AvailableBytesOut); done = _z.AvailableBytesIn == 0 && _z.AvailableBytesOut != 0; // If GZIP and de-compress, we're done when 8 bytes remain. if (_flavor == ZlibStreamFlavor.GZIP && !_wantCompress) done = (_z.AvailableBytesIn == 8 && _z.AvailableBytesOut != 0); } while (!done); }
public override System.Int32 Read(System.Byte[] buffer, System.Int32 offset, System.Int32 count) { // According to MS documentation, any implementation of the IO.Stream.Read function must: // (a) throw an exception if offset & count reference an invalid part of the buffer, // or if count < 0, or if buffer is null // (b) return 0 only upon EOF, or if count = 0 // (c) if not EOF, then return at least 1 byte, up to <count> bytes if (_streamMode == StreamMode.Undefined) { if (!this._stream.CanRead) throw new ZlibException("The stream is not readable."); // for the first read, set up some controls. _streamMode = StreamMode.Reader; // (The first reference to _z goes through the private accessor which // may initialize it.) z.AvailableBytesIn = 0; if (_flavor == ZlibStreamFlavor.GZIP) { _gzipHeaderByteCount = _ReadAndValidateGzipHeader(); // workitem 8501: handle edge case (decompress empty stream) if (_gzipHeaderByteCount == 0) return 0; } } if (_streamMode != StreamMode.Reader) throw new ZlibException("Cannot Read after Writing."); if (count == 0) return 0; // workitem 10562 // this quits too early if the input buffer has been consumed but // there's still output which hasn't been created yet (e.g. block // data for tables / tree, or the trailing adler32 data). we // need to wait for a Z_STREAM_END from Deflate instead. //if (nomoreinput && _wantCompress) return 0; // workitem 8557 if (buffer == null) throw new ArgumentNullException("buffer"); if (count < 0) throw new ArgumentOutOfRangeException("count"); if (offset < buffer.GetLowerBound(0)) throw new ArgumentOutOfRangeException("offset"); if ((offset + count) > buffer.GetLength(0)) throw new ArgumentOutOfRangeException("count"); int rc = 0; // set up the output of the deflate/inflate codec: _z.OutputBuffer = buffer; _z.NextOut = offset; _z.AvailableBytesOut = count; // This is necessary in case _workingBuffer has been resized. (new byte[]) // (The first reference to _workingBuffer goes through the private accessor which // may initialize it.) _z.InputBuffer = workingBuffer; do { // need data in _workingBuffer in order to deflate/inflate. Here, we check if we have any. if ((_z.AvailableBytesIn == 0) && (!nomoreinput)) { // No data available, so try to Read data from the captive stream. _z.NextIn = 0; _z.AvailableBytesIn = _stream.Read(_workingBuffer, 0, _workingBuffer.Length); if (_z.AvailableBytesIn == 0) nomoreinput = true; } // workitem 10562 // if we've consumed all the input then we need to generate any // remaining block data and checksums and put them in the pending array if (nomoreinput) _flushMode = FlushType.Finish; // we have data in InputBuffer; now compress or decompress as appropriate rc = (_wantCompress) ? _z.Deflate(_flushMode) : _z.Inflate(_flushMode); if (nomoreinput && (rc == ZlibConstants.Z_BUF_ERROR)) return 0; if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END) throw new ZlibException(String.Format("{0}flating: rc={1} msg={2}", (_wantCompress ? "de" : "in"), rc, _z.Message)); if ((nomoreinput || rc == ZlibConstants.Z_STREAM_END) && (_z.AvailableBytesOut == count)) { // workitem 10562 // we've genuinely reached the end of the output stream now, // including any block data and adler32 which appears after // the compressed input data. we don't have any more bytes // to return so we can stop processing return 0; // nothing more to read }; } //while (_z.AvailableBytesOut == count && rc == ZlibConstants.Z_OK); //while (_z.AvailableBytesOut > 0 && !nomoreinput && rc == ZlibConstants.Z_OK); while (_z.AvailableBytesOut > 0 && rc == ZlibConstants.Z_OK); // workitem 10562 // the following is no longer required as we now call _z.Deflate // in the main loop above instead //// workitem 8557 //// is there more room in output? //if (_z.AvailableBytesOut > 0) //{ // if (rc == ZlibConstants.Z_OK && _z.AvailableBytesIn == 0) // { // // deferred // } // // // are we completely done reading? // if (nomoreinput) // { // // and in compression? // if (_wantCompress) // { // // no more input data available; therefore we flush to // // try to complete the read // rc = _z.Deflate(FlushType.Finish); // // if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END) // throw new ZlibException(String.Format("Deflating: rc={0} msg={1}", rc, _z.Message)); // } // } //} rc = (count - _z.AvailableBytesOut); // calculate CRC after reading if (crc != null) crc.SlurpBlock(buffer, offset, rc); return rc; }
public Task<int> WriteAsync(byte[] buffer, int offset, int length, StreamMode mode) { if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (length < 0 || length > buffer.Length - offset) throw new ArgumentOutOfRangeException(nameof(length)); var frame = new Frame(); frame.mBuffer = buffer; frame.mOrigin = offset; frame.mOffset = offset; frame.mEnding = offset + length; lock (mSyncObject) { if (mDisposeTask != null) throw new ObjectDisposedException(null); if (mCompleted) throw new InvalidOperationException(); mQueue.Enqueue(frame); Monitor.PulseAll(mSyncObject); } return frame.mCompletion.Task; }
/// <param name="buffer"></param><param name="offset"></param> <param name="count"></param><exception cref = "ZlibException"></exception><exception cref = "ZlibException"></exception> public override void Write(byte[] buffer, int offset, int count) { // workitem 7159 // calculate the CRC on the unccompressed data (before writing) if (this.crc != null) { this.crc.SlurpBlock(buffer, offset, count); } if (this.Mode == StreamMode.Undefined) { this.Mode = StreamMode.Writer; } else if (this.Mode != StreamMode.Writer) { throw new ZlibException("Cannot Write after Reading."); } if (count == 0) { return; } // first reference of z property will initialize the private var _z this.Z.InputBuffer = buffer; this.ZlibCodec.NextIn = offset; this.ZlibCodec.AvailableBytesIn = count; bool done; do { this.ZlibCodec.OutputBuffer = this.WorkingBuffer; this.ZlibCodec.NextOut = 0; this.ZlibCodec.AvailableBytesOut = this.workBuffer.Length; int rc = this.WantCompress ? this.ZlibCodec.Deflate(this.flushMode) : this.ZlibCodec.Inflate(); if (rc != ZlibConstants.Zok && rc != ZlibConstants.ZStreamEnd) { throw new ZlibException((this.WantCompress ? "de" : "in") + "flating: " + this.ZlibCodec.Message); } // if (_workingBuffer.Length - _z.AvailableBytesOut > 0) this.Stream.Write(this.workBuffer, 0, this.workBuffer.Length - this.ZlibCodec.AvailableBytesOut); done = this.ZlibCodec.AvailableBytesIn == 0 && this.ZlibCodec.AvailableBytesOut != 0; // If GZIP and de-compress, we're done when 8 bytes remain. if (this.flavor == ZlibStreamFlavor.Gzip && !this.WantCompress) { done = this.ZlibCodec.AvailableBytesIn == 8 && this.ZlibCodec.AvailableBytesOut != 0; } } while (!done); }
public async Task<int> WriteAsync(byte[] buffer, int offset, int count, StreamMode mode) { System.Diagnostics.Debug.Assert(mEncoderOutputToConnectionInput == null); System.Diagnostics.Debug.Assert(buffer != null); System.Diagnostics.Debug.Assert(0 <= offset && offset < buffer.Length); System.Diagnostics.Debug.Assert(0 < count && count <= buffer.Length - offset); if (mConnectionOutputToEncoderInput != null) { var written = await mConnectionOutputToEncoderInput.WriteAsync(buffer, offset, count, mode); mTotalLength += written; return written; } int result = 0; do { lock (this) { while (mBuffer == null) Monitor.Wait(this); var written = Math.Min(count, mEnding - mOffset); Buffer.BlockCopy(buffer, offset, mBuffer, mOffset, written); mTotalLength += written; result += written; offset += written; count -= written; mBuffer = null; mResult.SetResult(written); } } while (mode == StreamMode.Complete && count > 0); return result; }
internal async Task<int> ReadInternalAsync(byte[] buffer, int offset, int length, StreamMode mode) { Utilities.DebugCheckStreamArguments(buffer, offset, length, mode); Stream stream; lock (mLockObject) { while (mPendingStream == null) { if (mComplete) { mCompleteAck = true; Monitor.PulseAll(mLockObject); return 0; } Monitor.Wait(mLockObject); } stream = mPendingStream; } int result = 0; for (;;) { var fetched = await stream.ReadAsync(buffer, offset, length).ConfigureAwait(false); if (fetched < 0 || fetched > length) throw new InvalidOperationException("Source stream violated stream contract."); result += fetched; offset += fetched; length -= fetched; mResultLength += fetched; // could be interlocked but doesn't need to be since we are currently 'owning' the stream (and also consider ourselves 'owning' this counter) if (fetched > 0) { if (mode == StreamMode.Partial || length == 0) return result; } else { lock (mLockObject) { if (mPendingStream != stream) throw new InternalFailureException(); mPendingStream = null; Monitor.PulseAll(mLockObject); while (mPendingStream == null) { if (mComplete) { mCompleteAck = true; Monitor.PulseAll(mLockObject); return result; } Monitor.Wait(mLockObject); } stream = mPendingStream; } } } }
public async Task<int> ReadAsync(byte[] buffer, int offset, int length, StreamMode mode) { System.Diagnostics.Debug.Assert(mEncoderInput == null); if (mode == StreamMode.Complete) throw new NotImplementedException(); var result = await mSession.ReadInternalAsync(buffer, offset, length, mode).ConfigureAwait(false); mLength += result; mChecksum = CRC.Update(mChecksum, buffer, offset, result); return result; }
Task<int> IStreamWriter.WriteAsync(byte[] buffer, int offset, int length, StreamMode mode) { Utilities.DebugCheckStreamArguments(buffer, offset, length, mode); lock (this) { System.Diagnostics.Debug.Assert(!mComplete); while (mBuffer != null) { Monitor.Wait(this); System.Diagnostics.Debug.Assert(!mComplete); } mBuffer = buffer; mOffset = offset; mLength = length; Monitor.PulseAll(this); while (mBuffer != null) { Monitor.Wait(this); System.Diagnostics.Debug.Assert(!mComplete); System.Diagnostics.Debug.Assert(mBuffer == null || mBuffer == buffer); if (mode == StreamMode.Partial && mBuffer != null && mLength < length) { mBuffer = null; Monitor.PulseAll(this); return Task.FromResult(length - mLength); } } return Task.FromResult(length); } }
/// <summary> /// Makes the specified font and brush to the current graphics objects. /// </summary> void Realize(XFont font, XBrush brush, int renderMode) { BeginPage(); RealizeTransform(); if (this.streamMode != StreamMode.Text) { this.streamMode = StreamMode.Text; this.content.Append("BT\n"); // Text matrix is empty after BT this.gfxState.realizedTextPosition = new XPoint(); } this.gfxState.RealizeFont(font, brush, renderMode); }
/// <summary> /// Read output data from the decoder. You should not use the specified region of the buffer until the returned task completes. /// </summary> /// <param name="buffer">The buffer into which output data should be written.</param> /// <param name="offset">The offset at which output data should be written.</param> /// <param name="length">The maximum number of bytes which should be written.</param> /// <param name="mode"> /// Specifies whether to wait until the whole output buffer has been filled, /// or wether to return as soon as some data is available. /// </param> /// <returns>A task which, when completed, tells you how much data has been read.</returns> public Task<int> ReadOutputAsync(byte[] buffer, int offset, int length, StreamMode mode) { if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (length < 0 || length > buffer.Length - offset) throw new ArgumentOutOfRangeException(nameof(length)); if (mode != StreamMode.Complete && mode != StreamMode.Partial) throw new ArgumentOutOfRangeException(nameof(mode)); var frame = new OutputFrame(); frame.mBuffer = buffer; frame.mOrigin = offset; frame.mOffset = offset; frame.mEnding = offset + length; frame.mMode = mode; PushOutputFrame(frame); return frame.mCompletion.Task; }
public Task<int> ReadAsync(byte[] buffer, int offset, int count, StreamMode mode) { System.Diagnostics.Debug.Assert(mConnectionOutputToEncoderInput == null); System.Diagnostics.Debug.Assert(buffer != null); System.Diagnostics.Debug.Assert(0 <= offset && offset < buffer.Length); System.Diagnostics.Debug.Assert(0 < count && count <= buffer.Length - offset); if (mEncoderOutputToConnectionInput != null) return mEncoderOutputToConnectionInput.ReadAsync(buffer, offset, count, mode); lock (this) { // Multiple outstanding ReadAsync calls are not allowed. if (mBuffer != null) throw new InternalFailureException(); if (mComplete) return Task.FromResult(0); mBuffer = buffer; mOffset = offset; mEnding = offset + count; // CompletionSource must be async so we can complete it from within the lock. // If we move the completion outside the lock we may be able to do inline completion? mResult = AsyncTaskCompletionSource<int>.Create(); Monitor.PulseAll(this); return mResult.Task; } }
/// <param name="buffer"></param><param name="offset"></param> <param name="count"></param><exception cref = "ArgumentNullException"></exception> /// <exception cref = "ArgumentOutOfRangeException"></exception><exception cref = "ArgumentOutOfRangeException"></exception> <exception cref = "ArgumentOutOfRangeException"></exception><returns></returns> public override int Read(byte[] buffer, int offset, int count) { // According to MS documentation, any implementation of the IO.Stream.Read function must: (a) throw an // exception if offset & count reference an invalid part of the buffer, or if count < 0, or if buffer is // null (b) return 0 only upon EOF, or if count = 0 (c) if not EOF, then return at least 1 byte, up to // <count> bytes if (this.Mode == StreamMode.Undefined) { if (!this.Stream.CanRead) { throw new ZlibException("The stream is not readable."); } // for the first read, set up some controls. this.Mode = StreamMode.Reader; // (The first reference to _z goes through the private accessor which may initialize it.) this.Z.AvailableBytesIn = 0; if (this.flavor == ZlibStreamFlavor.Gzip) { this.GzipHeaderByteCount = this.ReadAndValidateGzipHeader(); // workitem 8501: handle edge case (decompress empty stream) if (this.GzipHeaderByteCount == 0) { return 0; } } } if (this.Mode != StreamMode.Reader) { throw new ZlibException("Cannot Read after Writing."); } if (count == 0) { return 0; } if (this.nomoreinput && this.WantCompress) { return 0; // workitem 8557 } if (buffer == null) { throw new ArgumentNullException("buffer"); } if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if (offset < buffer.GetLowerBound(0)) { throw new ArgumentOutOfRangeException("offset"); } if ((offset + count) > buffer.GetLength(0)) { throw new ArgumentOutOfRangeException("count"); } int rc; // set up the output of the deflate/inflate codec: this.ZlibCodec.OutputBuffer = buffer; this.ZlibCodec.NextOut = offset; this.ZlibCodec.AvailableBytesOut = count; // This is necessary in case _workingBuffer has been resized. (new byte[]) (The first reference to // _workingBuffer goes through the private accessor which may initialize it.) this.ZlibCodec.InputBuffer = this.WorkingBuffer; do { // need data in _workingBuffer in order to deflate/inflate. Here, we check if we have any. if ((this.ZlibCodec.AvailableBytesIn == 0) && (!this.nomoreinput)) { // No data available, so try to Read data from the captive stream. this.ZlibCodec.NextIn = 0; this.ZlibCodec.AvailableBytesIn = this.Stream.Read(this.workBuffer, 0, this.workBuffer.Length); if (this.ZlibCodec.AvailableBytesIn == 0) { this.nomoreinput = true; } } // we have data in InputBuffer; now compress or decompress as appropriate rc = this.WantCompress ? this.ZlibCodec.Deflate(this.flushMode) : this.ZlibCodec.Inflate(); if (this.nomoreinput && (rc == ZlibConstants.ZBufError)) { return 0; } if (rc != ZlibConstants.Zok && rc != ZlibConstants.ZStreamEnd) { throw new ZlibException( string.Format( CultureInfo.InvariantCulture, "{0}flating: rc={1} msg={2}", this.WantCompress ? "de" : "in", rc, this.ZlibCodec.Message)); } if ((this.nomoreinput || rc == ZlibConstants.ZStreamEnd) && (this.ZlibCodec.AvailableBytesOut == count)) { break; // nothing more to read } } while (this.ZlibCodec.AvailableBytesOut > 0 && !this.nomoreinput && rc == ZlibConstants.Zok); // workitem 8557 is there more room in output? if (this.ZlibCodec.AvailableBytesOut > 0) { if (rc == ZlibConstants.Zok && this.ZlibCodec.AvailableBytesIn == 0) { // deferred } // are we completely done reading? if (this.nomoreinput) { // and in compression? if (this.WantCompress) { // no more input data available; therefore we flush to try to complete the read rc = this.ZlibCodec.Deflate(FlushType.Finish); if (rc != ZlibConstants.Zok && rc != ZlibConstants.ZStreamEnd) { throw new ZlibException( string.Format( CultureInfo.InvariantCulture, "Deflating: rc={0} msg={1}", rc, this.ZlibCodec.Message)); } } } } rc = count - this.ZlibCodec.AvailableBytesOut; // calculate CRC after reading if (this.crc != null) { this.crc.SlurpBlock(buffer, offset, rc); } return rc; }
public async Task<int> WriteAsync(byte[] buffer, int offset, int length, StreamMode mode) { System.Diagnostics.Debug.Assert(mEncoderOutput == null); System.Diagnostics.Debug.Assert(!mCompletionTask.Task.IsCompleted); // TODO: calculate checksum asynchronously? if (mCalculateChecksum) for (int i = 0; i < length; i++) mChecksum = CRC.Update(mChecksum, buffer[offset + i]); await mStream.WriteAsync(buffer, offset, length).ConfigureAwait(false); return length; }
public Task<int> ReadAsync(byte[] buffer, int offset, int length, StreamMode mode) { Utilities.CheckStreamArguments(buffer, offset, length, mode); var frame = new Frame(); frame.mBuffer = buffer; frame.mOrigin = offset; frame.mOffset = offset; frame.mEnding = offset + length; frame.mMode = mode; lock (mSyncObject) { if (mDisposeTask != null) throw new ObjectDisposedException(null); mQueue.Enqueue(frame); Monitor.Pulse(mSyncObject); } return frame.mCompletion.Task; }
// workitem 7813 - totally unnecessary // public override void WriteByte(byte b) // { // _buf1[0] = (byte)b; // // workitem 7159 // if (crc != null) // crc.SlurpBlock(_buf1, 0, 1); // Write(_buf1, 0, 1); // } public override void Write(byte[] buffer, int offset, int count) { // workitem 7159 // calculate the CRC on the unccompressed data (before writing) if (this.crc != null) this.crc.SlurpBlock(buffer, offset, count); if (this.streamMode == StreamMode.Undefined) this.streamMode = StreamMode.Writer; else if (this.streamMode != StreamMode.Writer) throw new ZlibException("Cannot Write after Reading."); if (count == 0) return; // first reference of z property will initialize the private var _z this.z.InputBuffer = buffer; this.z.NextIn = offset; this.z.AvailableBytesIn = count; bool done; do { this.z.OutputBuffer = this.WorkingBuffer; this.z.NextOut = 0; this.z.AvailableBytesOut = this.workingBuffer.Length; //int rc = (_wantCompress) // ? _z.Deflate(_flushMode) // : _z.Inflate(_flushMode); int rc = this.z.Inflate(this.FlushMode); if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END) throw new ZlibException("inflating: " + this.z.Message); this.Stream.Write(this.workingBuffer, 0, this.workingBuffer.Length - this.z.AvailableBytesOut); done = this.z.AvailableBytesIn == 0 && this.z.AvailableBytesOut != 0; // If GZIP and de-compress, we're done when 8 bytes remain. if (this.Flavor == ZlibStreamFlavor.Gzip) done = (this.z.AvailableBytesIn == 8 && this.z.AvailableBytesOut != 0); } while (!done); }
public Task<int> ReadAsync(byte[] buffer, int offset, int length, StreamMode mode) { Utilities.CheckStreamArguments(buffer, offset, length, mode); int total = 0; while (length > 0) { Frame frame; lock (mSyncObject) { System.Diagnostics.Debug.Assert(mRunning); if (mDisposeTask != null) throw new OperationCanceledException(); while (mQueue.Count == 0) { if (mCompleted) return Task.FromResult(total); Monitor.Wait(mSyncObject); if (mDisposeTask != null) throw new OperationCanceledException(); } frame = mQueue.Peek(); } System.Diagnostics.Debug.Assert(frame.mOffset < frame.mEnding); var processed = Math.Min(frame.mEnding - frame.mOffset, length); System.Diagnostics.Debug.Assert(processed > 0); Buffer.BlockCopy(frame.mBuffer, frame.mOffset, buffer, offset, processed); frame.mOffset += processed; total += processed; offset += processed; length -= processed; if (frame.mOffset == frame.mEnding) { frame.mCompletion.SetResult(frame.mOffset - frame.mOrigin); lock (mSyncObject) { System.Diagnostics.Debug.Assert(mRunning); var other = mQueue.Dequeue(); System.Diagnostics.Debug.Assert(other == frame); if (mDisposeTask != null) throw new OperationCanceledException(); } } if (mode == StreamMode.Partial) break; } return Task.FromResult(total); }
public override void Write( System.Byte [] buffer, int offset, int count ) { if ( streamMode == StreamMode.Undefined ) streamMode = StreamMode.Writer; else if ( streamMode != StreamMode.Writer ) throw new CompressionProcessException ( "Cannot Write after Reading." ); if ( count == 0 ) return; z.InputBuffer = buffer; _z.NextIn = offset; _z.AvailableBytesIn = count; bool done = false; do { _z.OutputBuffer = workingBuffer; _z.NextOut = 0; _z.AvailableBytesOut = _workingBuffer.Length; int rc = ( _wantCompress ) ? _z.Deflate ( flushMode ) : _z.Inflate ( flushMode ); if ( rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END ) throw new CompressionProcessException ( ( _wantCompress ? "de" : "in" ) + "flating: " + _z.Message ); stream.Write ( _workingBuffer, 0, _workingBuffer.Length - _z.AvailableBytesOut ); done = _z.AvailableBytesIn == 0 && _z.AvailableBytesOut != 0; } while ( !done ); }
public override System.Int32 Read(System.Byte[] buffer, System.Int32 offset, System.Int32 count) { if (_streamMode == StreamMode.Undefined) { // for the first read, set up some controls. _streamMode = StreamMode.Reader; _z.AvailableBytesIn = 0; } if (_streamMode != StreamMode.Reader) throw new ZlibException("Cannot Read after Writing."); if (!this._stream.CanRead) throw new ZlibException("The stream is not readable."); if (count == 0) return 0; int rc; // set up the output of the deflate/inflate codec: _z.OutputBuffer = buffer; _z.NextOut = offset; _z.AvailableBytesOut = count; // this is not always necessary, but is helpful in case _workingBuffer has been resized. (new byte[]) _z.InputBuffer = _workingBuffer; do { // need data in _workingBuffer in order to deflate/inflate. Here, we check if we have any. if ((_z.AvailableBytesIn == 0) && (!nomoreinput)) { // No data available, so try to Read data from the captive stream. _z.NextIn = 0; _z.AvailableBytesIn = SharedUtils.ReadInput(_stream, _workingBuffer, 0, _workingBuffer.Length); //(bufsize<z.avail_out ? bufsize : z.avail_out)); if (_z.AvailableBytesIn == -1) { _z.AvailableBytesIn = 0; nomoreinput = true; } } // we have data in InputBuffer; now compress or decompress as appropriate rc = (_wantCompress) ? -1 : _z.Inflate(_flushMode); if (nomoreinput && (rc == ZlibConstants.Z_BUF_ERROR)) return (-1); if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END) throw new ZlibException((_wantCompress ? "de" : "in") + "flating: " + _z.Message); if ((nomoreinput || rc == ZlibConstants.Z_STREAM_END) && (_z.AvailableBytesOut == count)) return (-1); } while (_z.AvailableBytesOut == count && rc == ZlibConstants.Z_OK); return (count - _z.AvailableBytesOut); }
public static extern int SetQHYCCDStreamMode(IntPtr handle, StreamMode mode);
public override System.Int32 Read(System.Byte[] buffer, System.Int32 offset, System.Int32 count) { // According to MS documentation, any implementation of the IO.Stream.Read function must: // (a) throw an exception if offset & count reference an invalid part of the buffer, // or if count < 0, or if buffer is null // (b) return 0 only upon EOF, or if count = 0 // (c) if not EOF, then return at least 1 byte, up to <count> bytes if (_streamMode == StreamMode.Undefined) { if (!this._stream.CanRead) throw new ZlibException("The stream is not readable."); // for the first read, set up some controls. _streamMode = StreamMode.Reader; // (The first reference to _z goes through the private accessor which // may initialize it.) z.AvailableBytesIn = 0; if (_flavor == ZlibStreamFlavor.GZIP) { _gzipHeaderByteCount = _ReadAndValidateGzipHeader(); // workitem 8501: handle edge case (decompress empty stream) if (_gzipHeaderByteCount == 0) return 0; } } if (_streamMode != StreamMode.Reader) throw new ZlibException("Cannot Read after Writing."); if (count == 0) return 0; if (nomoreinput && _wantCompress) return 0; // workitem 8557 if (buffer == null) throw new ArgumentNullException("buffer"); if (count < 0) throw new ArgumentOutOfRangeException("count"); if (offset < buffer.GetLowerBound(0)) throw new ArgumentOutOfRangeException("offset"); if ((offset + count) > buffer.GetLength(0)) throw new ArgumentOutOfRangeException("count"); int rc = 0; // set up the output of the deflate/inflate codec: _z.OutputBuffer = buffer; _z.NextOut = offset; _z.AvailableBytesOut = count; // This is necessary in case _workingBuffer has been resized. (new byte[]) // (The first reference to _workingBuffer goes through the private accessor which // may initialize it.) _z.InputBuffer = workingBuffer; do { // need data in _workingBuffer in order to deflate/inflate. Here, we check if we have any. if ((_z.AvailableBytesIn == 0) && (!nomoreinput)) { // No data available, so try to Read data from the captive stream. _z.NextIn = 0; _z.AvailableBytesIn = _stream.Read(_workingBuffer, 0, _workingBuffer.Length); if (_z.AvailableBytesIn == 0) nomoreinput = true; } // we have data in InputBuffer; now compress or decompress as appropriate rc = (_wantCompress) ? _z.Deflate(_flushMode) : _z.Inflate(_flushMode); if (nomoreinput && (rc == ZlibConstants.Z_BUF_ERROR)) return 0; if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END) throw new ZlibException(String.Format("{0}flating: rc={1} msg={2}", (_wantCompress ? "de" : "in"), rc, _z.Message)); if ((nomoreinput || rc == ZlibConstants.Z_STREAM_END) && (_z.AvailableBytesOut == count)) break; // nothing more to read } //while (_z.AvailableBytesOut == count && rc == ZlibConstants.Z_OK); while (_z.AvailableBytesOut > 0 && !nomoreinput && rc == ZlibConstants.Z_OK); // workitem 8557 // is there more room in output? if (_z.AvailableBytesOut > 0) { if (rc == ZlibConstants.Z_OK && _z.AvailableBytesIn == 0) { // deferred } // are we completely done reading? if (nomoreinput) { // and in compression? if (_wantCompress) { // no more input data available; therefore we flush to // try to complete the read rc = _z.Deflate(FlushType.Finish); if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END) throw new ZlibException(String.Format("Deflating: rc={0} msg={1}", rc, _z.Message)); } } } rc = (count - _z.AvailableBytesOut); // calculate CRC after reading if (crc != null) crc.SlurpBlock(buffer, offset, rc); return rc; }
public override void Write(System.Byte[] buffer, int offset, int length) { if (_streamMode == StreamMode.Undefined) _streamMode = StreamMode.Writer; if (_streamMode != StreamMode.Writer) throw new ZlibException("Cannot Write after Reading."); if (length == 0) return; _z.InputBuffer = buffer; _z.NextIn = offset; _z.AvailableBytesIn = length; do { _z.OutputBuffer = _workingBuffer; _z.NextOut = 0; _z.AvailableBytesOut = _workingBuffer.Length; int rc = (_wantCompress) ? 1 : _z.Inflate(_flushMode); if (rc != ZlibConstants.Z_OK && rc != ZlibConstants.Z_STREAM_END) throw new ZlibException((_wantCompress ? "de" : "in") + "flating: " + _z.Message); _stream.Write(_workingBuffer, 0, _workingBuffer.Length - _z.AvailableBytesOut); } while (_z.AvailableBytesIn > 0 || _z.AvailableBytesOut == 0); }