internal override bool Write(WriteBuffer buf) { if (_charPos == -1) { // Start new query if (buf.WriteSpaceLeft < 1 + 4) return false; _charPos = 0; var queryByteLen = _encoding.GetByteCount(_query); _queryChars = _query.ToCharArray(); buf.WriteByte(Code); buf.WriteInt32(4 + // Message length (including self excluding code) queryByteLen + // Query byte length 1); // Null terminator } if (_charPos < _queryChars.Length) { int charsUsed; bool completed; buf.WriteStringChunked(_queryChars, _charPos, _queryChars.Length - _charPos, true, out charsUsed, out completed); _charPos += charsUsed; if (!completed) return false; } if (buf.WriteSpaceLeft < 1) return false; buf.WriteByte(0); _charPos = -1; return true; }
private int WriteByte(byte[] buffer, int offset, WriteBuffer writeBuffer) { // The body of this method should rather be inlined where it is called, but doing so seems to cause a huge // (>5x) perf hit. var currentByte = buffer[offset]; if (this.previousWasEscapeByte) { this.previousWasEscapeByte = false; this.crc = Crc.AddCrcCcitt(this.crc, currentByte); currentByte = (byte)(currentByte ^ Frame.EscapeXor); ++offset; } else { if (currentByte < Frame.InvalidStart) { this.crc = Crc.AddCrcCcitt(this.crc, currentByte); ++offset; } else { currentByte = Frame.EscapeByte; this.previousWasEscapeByte = true; } } writeBuffer[writeBuffer.Count++] = currentByte; return offset; }
internal async Task WriteToAsync(WriteBuffer writerBuffer, CancellationToken cancellationToken) { await writerBuffer.ReserveAsync(2, cancellationToken); writerBuffer[writerBuffer.Count++] = this.Slot; writerBuffer[writerBuffer.Count++] = this.messageType; await this.Command.WriteToAsync(writerBuffer, cancellationToken); }
internal override void WriteFully(WriteBuffer buf) { Contract.Requires(BackendProcessId != 0); buf.WriteInt32(Length); buf.WriteInt32(CancelRequestCode); buf.WriteInt32(BackendProcessId); buf.WriteInt32(BackendSecretKey); }
internal override void WriteFully(WriteBuffer buf) { Contract.Requires(Name != null && Name.All(c => c < 128)); buf.WriteByte(Code); buf.WriteInt32(Length - 1); buf.WriteByte((byte)StatementOrPortal); buf.WriteBytesNullTerminated(Encoding.ASCII.GetBytes(Name)); }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////// internal static async Task<MessageEncodingStream> CreateAsync( WriteBuffer rawBuffer, S101Message message, CancellationToken cancellationToken) { message.PacketFlags = PacketFlags.FirstPacket | (message.CanHaveMultiplePackets ? PacketFlags.None : PacketFlags.LastPacket); var framingStream = await FramingStream.CreateAsync(rawBuffer, cancellationToken); var result = new MessageEncodingStream(message, rawBuffer, framingStream); await message.WriteToAsync(result.unframedBuffer, cancellationToken); return result; }
internal override void WriteFully(WriteBuffer buf) { Contract.Requires(Portal != null && Portal.All(c => c < 128)); var portalNameBytes = Portal == "" ? PGUtil.EmptyBuffer : Encoding.ASCII.GetBytes(Portal); buf.WriteByte(Code); buf.WriteInt32(Length - 1); buf.WriteBytesNullTerminated(portalNameBytes); buf.WriteInt32(MaxRows); }
internal sealed override async Task WriteToCoreAsync( WriteBuffer writeBuffer, CancellationToken cancellationToken) { await base.WriteToCoreAsync(writeBuffer, cancellationToken); await writeBuffer.ReserveAsync(3, cancellationToken); writeBuffer[writeBuffer.Count++] = (byte)this.PacketFlags; writeBuffer[writeBuffer.Count++] = this.dtd; writeBuffer[writeBuffer.Count++] = (byte)this.applicationBytes.Length; await writeBuffer.WriteAsync( this.applicationBytes, 0, this.applicationBytes.Length, cancellationToken); }
public bool WriteTo(WriteBuffer buffer) { // 0. init header // 1. loop on header // 2. loop on Key, if any // 3. loop on Data, if any // 4. done switch (state) { case STATE_INITIAL: goto init; case STATE_WRITE_HEADER: goto write_header; case STATE_WRITE_KEY: goto write_key; case STATE_WRITE_BODY: goto write_body; default: return false; } // TODO put these inside switch..case init: PrepareHeader(); state = STATE_WRITE_HEADER; write_header: writeOffset += buffer.Append(header, writeOffset, headerLength - writeOffset); if (writeOffset < headerLength) return true; if (Key.Length > 0) { writeOffset = 0; state = STATE_WRITE_KEY; } else goto pre_body; write_key: writeOffset += buffer.Append(Key.Array, writeOffset, Key.Length - writeOffset); if (writeOffset < Key.Length) return true; pre_body: if (Data.Count > 0) { writeOffset = 0; state = STATE_WRITE_BODY; } else goto done; write_body: writeOffset += buffer.Append(Data.Array, Data.Offset + writeOffset, Data.Count - writeOffset); if (writeOffset < Data.Count) return true; done: state = STATE_DONE; return false; }
internal override void WriteFully(WriteBuffer buf) { buf.WriteInt32(_length); buf.WriteInt32(ProtocolVersion3); foreach (var kv in _parameters) { buf.WriteBytesNullTerminated(kv.Key); buf.WriteBytesNullTerminated(kv.Value); } buf.WriteByte(0); }
internal override void WriteFully(WriteBuffer buf) { buf.WriteByte(Code); buf.WriteInt32(Length - 1); if (_errorMessageLen == 0) { buf.WriteByte(0); } else { buf.WriteBytesNullTerminated(PGUtil.UTF8Encoding.GetBytes(_errorMessage)); } }
public void WriteSequence(int[] targetBuffer) { long bufferEnd = _bufferShift + _BufferCount; if (_lastValue < bufferEnd) { var wb = new WriteBuffer(_bufferShift, targetBuffer); long shift = _lastValue - _bufferShift; do { wb.Shift(shift); wb.WriteOne(); shift = _step; _lastValue += _step; }while (_lastValue < bufferEnd); } _bufferShift += _BufferCount; }
internal void WriteCancelRequest(int backendProcessId, int backendSecretKey) { const int len = sizeof(int) + // Length sizeof(int) + // Cancel request code sizeof(int) + // Backend process id sizeof(int); // Backend secret key Debug.Assert(backendProcessId != 0); if (WriteBuffer.WriteSpaceLeft < len) { Flush(false).GetAwaiter().GetResult(); } WriteBuffer.WriteInt32(len); WriteBuffer.WriteInt32(1234 << 16 | 5678); WriteBuffer.WriteInt32(backendProcessId); WriteBuffer.WriteInt32(backendSecretKey); }
internal override async Task Write(WriteBuffer buf, bool async, CancellationToken cancellationToken) { Debug.Assert(Statement != null && Statement.All(c => c < 128)); var queryByteLen = _encoding.GetByteCount(Query); if (buf.WriteSpaceLeft < 1 + 4 + Statement.Length + 1) { await buf.Flush(async, cancellationToken); } var messageLength = 1 + // Message code 4 + // Length Statement.Length + 1 + // Null terminator queryByteLen + 1 + // Null terminator 2 + // Number of parameters ParameterTypeOIDs.Count * 4; buf.WriteByte(Code); buf.WriteInt32(messageLength - 1); buf.WriteNullTerminatedString(Statement); await buf.WriteString(Query, queryByteLen, async, cancellationToken); if (buf.WriteSpaceLeft < 1 + 2) { await buf.Flush(async, cancellationToken); } buf.WriteByte(0); // Null terminator for the query buf.WriteInt16((short)ParameterTypeOIDs.Count); foreach (uint t in ParameterTypeOIDs) { if (buf.WriteSpaceLeft < 4) { await buf.Flush(async, cancellationToken); } buf.WriteInt32((int)t); } }
static PregeneratedMessage() { _tempBuf = new WriteBuffer(null, new MemoryStream(), WriteBuffer.MinimumBufferSize, Encoding.ASCII); _tempQuery = new QueryMessage(PGUtil.UTF8Encoding); BeginTrans = BuildQuery("BEGIN;"); SetTransRepeatableRead = BuildQuery("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;"); SetTransSerializable = BuildQuery("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;"); SetTransReadCommitted = BuildQuery("SET TRANSACTION ISOLATION LEVEL READ COMMITTED;"); SetTransReadUncommitted = BuildQuery("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;"); CommitTransaction = BuildQuery("COMMIT"); RollbackTransaction = BuildQuery("ROLLBACK"); DiscardAll = BuildQuery("DISCARD ALL"); UnlistenAll = BuildQuery("UNLISTEN *"); KeepAlive = BuildQuery("SELECT NULL"); _tempBuf = null; _tempQuery = null; }
static PregeneratedMessage() { _tempBuf = new WriteBuffer(null, new MemoryStream(), WriteBuffer.MinimumBufferSize, Encoding.ASCII); _tempQuery = new QueryMessage(); BeginTrans = BuildQuery("BEGIN;"); SetTransRepeatableRead = BuildQuery("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;"); SetTransSerializable = BuildQuery("SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;"); SetTransReadCommitted = BuildQuery("SET TRANSACTION ISOLATION LEVEL READ COMMITTED;"); SetTransReadUncommitted = BuildQuery("SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;"); CommitTransaction = BuildQuery("COMMIT"); RollbackTransaction = BuildQuery("ROLLBACK"); DiscardAll = BuildQuery("DISCARD ALL"); UnlistenAll = BuildQuery("UNLISTEN *"); KeepAlive = BuildQuery("SELECT NULL"); _tempBuf = null; _tempQuery = null; }
internal ConfigurationOptions GetConfigurationOptions() { ConfigurationOptions configurationOptions = new ConfigurationOptions() { ClientName = ClientName, ServiceName = ServiceName, KeepAlive = KeepAlive.GetValueOrDefault(-1), SyncTimeout = SyncTimeout.GetValueOrDefault(1000), AllowAdmin = AllowAdmin.GetValueOrDefault(), Password = Password, TieBreaker = TieBreaker ?? "__Booksleeve_TieBreak", WriteBuffer = WriteBuffer.GetValueOrDefault(4096), Ssl = Ssl.GetValueOrDefault(), SslHost = SslHost, HighPrioritySocketThreads = HighPrioritySocketThreads ?? true, ConfigurationChannel = ConfigChannel, ResolveDns = ResolveDns.GetValueOrDefault(), CommandMap = CommandMap, ChannelPrefix = ChannelPrefix, ConnectRetry = ConnectRetry ?? 3, ConfigCheckSeconds = ConfigCheckSeconds.GetValueOrDefault(60), DefaultDatabase = DefaultDatabase, ReconnectRetryPolicy = ReconnectRetryPolicy, SslProtocols = this.SslProtocols }; foreach (var server in Servers) { configurationOptions.EndPoints.Add(server); } configurationOptions.ConnectTimeout = ConnectTimeout ?? Math.Max(5000, configurationOptions.SyncTimeout); configurationOptions.ResponseTimeout = ResponseTimeout ?? configurationOptions.SyncTimeout; configurationOptions.AbortOnConnectFail = AbortConnect ?? GetDefaultAbortOnConnectFailSetting(configurationOptions.EndPoints); if (Enum.TryParse <Proxy>(Proxy, true, out var proxy)) { configurationOptions.Proxy = proxy; } return(configurationOptions); }
protected override void OnDocumentCompleted(WebBrowserDocumentCompletedEventArgs e) { if (this._initialized) { return; } // Load template switch (this._initializationMode) { case OutputControlInitializationMode.Delayed: this.Document.Write(this.Template); break; case OutputControlInitializationMode.External: this._execute("Write", this.Template); break; } // Setup properties this._updateProperties(); // Setup events this.Document.Click -= new HtmlElementEventHandler(OnClick); this.Document.Click += new HtmlElementEventHandler(OnClick); this.Document.MouseUp -= new HtmlElementEventHandler(OnMouseUp); this.Document.MouseUp += new HtmlElementEventHandler(OnMouseUp); // Trigger event this._initialized = true; base.OnDocumentCompleted(e); // Clear buffer if (this.Document != null && this.Document.Body != null) { while (this._buffer.Count > 0) { WriteBuffer buffer = this._buffer.Dequeue(); this.Write(buffer.Template, buffer.Element, buffer.Style, buffer.Scroll); } // Fire ready event if (this.ReadyEvent != null) { this.ReadyEvent(this); } } }
internal override async Task Write(WriteBuffer buf, bool async, CancellationToken cancellationToken) { if (buf.WriteSpaceLeft < 1 + 5) { await buf.Flush(async); } buf.WriteByte(Code); buf.WriteInt32(4 + PayloadLength); if (PayloadLength <= buf.WriteSpaceLeft) { // The entire array fits in our buffer, copy it into the buffer as usual. buf.WriteBytes(Payload, PayloadOffset, Payload.Length); return; } await buf.Flush(async); buf.DirectWrite(Payload, PayloadOffset, PayloadLength); }
internal async Task WritePassword(byte[] payload, int offset, int count, bool async, CancellationToken cancellationToken = default) { if (WriteBuffer.WriteSpaceLeft < sizeof(byte) + sizeof(int)) { await WriteBuffer.Flush(async, cancellationToken); } WriteBuffer.WriteByte(FrontendMessageCode.Password); WriteBuffer.WriteInt32(sizeof(int) + count); if (count <= WriteBuffer.WriteSpaceLeft) { // The entire array fits in our WriteBuffer, copy it into the WriteBuffer as usual. WriteBuffer.WriteBytes(payload, offset, count); return; } await WriteBuffer.Flush(async, cancellationToken); await WriteBuffer.DirectWrite(new ReadOnlyMemory <byte>(payload, offset, count), async, cancellationToken); }
private WriteBuffer CloseTag() { if (this.writers.Count <= 1) { throw new SWFModellerException( SWFModellerError.Internal, "Call to CloseTag when no tag was open."); } WriteBuffer tagWriter = this.writers.Peek(); tagWriter.Align8(); byte[] tagData = tagWriter.Data; int tagCode = (int)tagWriter.Tag; #if DEBUG this.LogMessage("Body length of " + tagWriter.Tag.ToString() + " " + tagData.Length + " bytes on " + tagWriter.LogData, true); #endif this.writers.Pop(); tagWriter = this.writers.Peek(); tagWriter.Align8(); if (tagData.Length >= 63) { /* Long record header */ int hdr = (tagCode << 6) | 0x3f; tagWriter.WriteUI16((uint)hdr); tagWriter.WriteSI32(tagData.Length); } else { /* Short record header */ int hdr = (tagCode << 6) | tagData.Length; tagWriter.WriteUI16((uint)hdr); } tagWriter.Write(tagData, 0, tagData.Length); return(tagWriter); }
// 广播消息给房间内所有人 public void Broadcast(string op, Action <IWriteableBuffer> cb) { foreach (var s in ss) { if (s == null) { continue; } s.Conn.Send2Usr(op, cb); } var wb = new WriteBuffer(true); cb.SC(wb); var rb = new RingBuffer(true, true); rb.Write(wb.Data, 0, wb.Available); currentBattleMsgHistory.Add(new KeyValuePair <string, IReadableBuffer>(op, rb)); }
protected override async Task Write(object value, WriteBuffer buf, LengthCache lengthCache, NpgsqlParameter parameter, bool async, CancellationToken cancellationToken) { var polygon = (NpgsqlPolygon)value; if (buf.WriteSpaceLeft < 4) { await buf.Flush(async, cancellationToken); } buf.WriteInt32(polygon.Count); foreach (var p in polygon) { if (buf.WriteSpaceLeft < 16) { await buf.Flush(async, cancellationToken); } buf.WriteDouble(p.X); buf.WriteDouble(p.Y); } }
public override void PrepareWrite(object value, WriteBuffer buf, LengthCache lengthCache, NpgsqlParameter parameter = null) { _writeBuf = buf; if (value is ArraySegment <byte> ) { _value = (ArraySegment <byte>)value; if (!(parameter == null || parameter.Size <= 0 || parameter.Size >= _value.Count)) { _value = new ArraySegment <byte>(_value.Array, _value.Offset, parameter.Size); } } else { var array = (byte[])value; var len = parameter == null || parameter.Size <= 0 || parameter.Size >= array.Length ? array.Length : parameter.Size; _value = new ArraySegment <byte>(array, 0, len); } }
internal override async Task Write(WriteBuffer buf, bool async, CancellationToken cancellationToken) { if (buf.WriteSpaceLeft < 1 + 4) { await buf.Flush(async, cancellationToken); } var queryByteLen = _encoding.GetByteCount(_query); buf.WriteByte(Code); buf.WriteInt32(4 + // Message length (including self excluding code) queryByteLen + // Query byte length 1); // Null terminator await buf.WriteString(_query, queryByteLen, async, cancellationToken); if (buf.WriteSpaceLeft < 1) { await buf.Flush(async, cancellationToken); } buf.WriteByte(0); }
internal override bool Write(WriteBuffer buf) { if (_charPos == -1) { // Start new query if (buf.WriteSpaceLeft < 1 + 4) { return(false); } _charPos = 0; var queryByteLen = _encoding.GetByteCount(_query); _queryChars = _query.ToCharArray(); buf.WriteByte(Code); buf.WriteInt32(4 + // Message length (including self excluding code) queryByteLen + // Query byte length 1); // Null terminator } if (_charPos < _queryChars.Length) { int charsUsed; bool completed; buf.WriteStringChunked(_queryChars, _charPos, _queryChars.Length - _charPos, true, out charsUsed, out completed); _charPos += charsUsed; if (!completed) { return(false); } } if (buf.WriteSpaceLeft < 1) { return(false); } buf.WriteByte(0); _charPos = -1; return(true); }
protected override async Task Write(object value, WriteBuffer buf, LengthCache lengthCache, NpgsqlParameter parameter, bool async, CancellationToken cancellationToken) { var path = (NpgsqlPath)value; if (buf.WriteSpaceLeft < 5) { await buf.Flush(async, cancellationToken); } buf.WriteByte((byte)(path.Open ? 0 : 1)); buf.WriteInt32(path.Count); foreach (var p in path) { if (buf.WriteSpaceLeft < 16) { await buf.Flush(async, cancellationToken); } buf.WriteDouble(p.X); buf.WriteDouble(p.Y); } }
public override void SetAllValuesCommunication(ValueType[] values) { if (values.Length < channelCount) { throw new ArgumentOutOfRangeException(nameof(values), "values length"); } var valuesToSend = new float[channelCount]; for (int i = 0; i < 4; ++i) { valuesToSend[i] = Convert.ToSingle(values[i]); } var buf = new WriteBuffer(); foreach (var val in valuesToSend) { buf.Add(val, sizeof(float)); } Write(30, buf); }
protected override async Task Write(object value, WriteBuffer buf, LengthCache lengthCache, NpgsqlParameter parameter, bool async, CancellationToken cancellationToken) { var asDict = (IDictionary <string, string>)value; if (buf.WriteSpaceLeft < 4) { await buf.Flush(async, cancellationToken); } buf.WriteInt32(asDict.Count); if (asDict.Count == 0) { return; } foreach (var kv in asDict) { await _textHandler.WriteWithLength(kv.Key, buf, lengthCache, parameter, async, cancellationToken); await _textHandler.WriteWithLength(kv.Value, buf, lengthCache, parameter, async, cancellationToken); } }
protected override async Task Write(object value, WriteBuffer buf, LengthCache lengthCache, NpgsqlParameter parameter, bool async, CancellationToken cancellationToken) { var range = (NpgsqlRange <TElement>)value; if (buf.WriteSpaceLeft < 1) { await buf.Flush(async, cancellationToken); } buf.WriteByte((byte)range.Flags); if (range.IsEmpty) { return; } if (!range.LowerBoundInfinite) { await ElementHandler.WriteWithLength(range.LowerBound, buf, lengthCache, null, async, cancellationToken); } if (!range.UpperBoundInfinite) { await ElementHandler.WriteWithLength(range.UpperBound, buf, lengthCache, null, async, cancellationToken); } }
internal async Task WriteQuery(string sql, bool async, CancellationToken cancellationToken = default) { var queryByteLen = TextEncoding.GetByteCount(sql); if (WriteBuffer.WriteSpaceLeft < 1 + 4) { await Flush(async, cancellationToken); } WriteBuffer.WriteByte(FrontendMessageCode.Query); WriteBuffer.WriteInt32( sizeof(int) + // Message length (including self excluding code) queryByteLen + // Query byte length sizeof(byte)); // Null terminator await WriteBuffer.WriteString(sql, queryByteLen, async, cancellationToken); if (WriteBuffer.WriteSpaceLeft < 1) { await Flush(async, cancellationToken); } WriteBuffer.WriteByte(0); // Null terminator }
public static void BuildQuestionnaire(GameServer srv) { BC <QuestionnaireMgr>(); // 问卷调查 BC <QuestionnaireResultMgr>(); // 问卷调查 var qrc = new QuestionnaireResultContainer(new MySqlDbPersistence <QuestionnaireResult, string>( "scm_qr", "127.0.0.1", "root", "123456", @"Qa", "CREATE TABLE Qa(ID VARCHAR(100) BINARY, Data MediumBlob," + "PRIMARY KEY(ID ASC));", null, (da) => { var buff = new WriteBuffer(); da.Serialize(buff); return(buff.Data); }, (data) => { var rb = new RingBuffer(data); var qr = new QuestionnaireResult(); qr.Deserialize(rb); return(qr); }, null)); srv.Add("QuestionnaireResultContainer", qrc); }
private void BindClasses(ListSet <Timeline> unboundClasses) { if (unboundClasses.Count > 0) { WriteBuffer symbolBuf = this.OpenTag(Tag.SymbolClass); symbolBuf.WriteUI16((uint)unboundClasses.Count); foreach (Timeline t in unboundClasses) { symbolBuf.WriteUI16((uint)this.characterMarshal.GetIDFor((ICharacter)t)); symbolBuf.WriteString(t.Class.QualifiedName); this.LogMessage( "ID:" + (uint)this.characterMarshal.GetIDFor((ICharacter)t) + " => " + t.Class.QualifiedName); } this.CloseTag(); unboundClasses.Clear(); } }
private void WriteFileAttributesTag() { WriteBuffer tagWriter = this.OpenTag(Tag.FileAttributes); /* ISSUE 27: Some of these flags are for SWF v10 - check the flash 9 spec for defaults instead. */ /* No data written yet, so data will be aligned. */ tagWriter.WriteBit(false); /* Reserved, must be 0 */ tagWriter.WriteBit(true); /* UseDirectBlit, TODO: We set this to '1' but I dunno what the IDE does. */ tagWriter.WriteBit(true); /* UseGPU, TODO: We set this to '1' but I dunno what the IDE does. */ tagWriter.WriteBit(this.options.RDFMetadata != null); tagWriter.WriteBit(true); /* AS3, because we don't like AS2. Boo. */ tagWriter.WriteUBits(0, 2); /* Reserved, must be 0 */ tagWriter.WriteBit(false); /* UseNetwork. TODO: Check what the IDE sets for this. */ tagWriter.WriteUBits(0, 24); /* Reserved, must be 0 */ this.CloseTag(); if (this.options.RDFMetadata != null) { this.OpenTag(Tag.Metadata) .WriteString(this.options.RDFMetadata); this.CloseTag(); } }
private static ReadBuffer UnpackVLE(ReadBuffer packedData) { var widthsCount = packedData[0]; var widths = packedData.Slice(1, widthsCount); var alphabetCount = widths.Select(val => (int)val).Sum(); var alphabet = packedData.Slice(1 + widthsCount, alphabetCount); var dictionary = new HuffmanTree(widths, alphabet); var stream = EnumerateBits(packedData.Drop(1 + widthsCount + alphabetCount)); var result = new WriteBuffer(); while (true) { int value = dictionary.DecodeByte(stream); if (value < 0) { break; } result.Append((byte)value); } return(result.ToReadBuffer()); }
override public void Encode(WriteBuffer wb) { Eproto.PackArray(wb, 1); if (this.info == null) { Eproto.PackNil(wb); } else { Eproto.PackArray(wb, this.info.Length); for (int i = 0; i < this.info.Length; ++i) { table_info v = this.info[i]; if (v == null) { Eproto.PackNil(wb); } else { v.Encode(wb); } } } }
public override void PrepareWrite(object value, WriteBuffer buf, LengthCache lengthCache, NpgsqlParameter parameter = null) { _writeBuf = buf; _charPos = -1; _byteLen = lengthCache.GetLast(); if (parameter?.ConvertedValue != null) { value = parameter.ConvertedValue; } _str = value as string; if (_str != null) { _charLen = parameter == null || parameter.Size <= 0 || parameter.Size >= _str.Length ? _str.Length : parameter.Size; return; } _chars = value as char[]; if (_chars != null) { _charLen = parameter == null || parameter.Size <= 0 || parameter.Size >= _chars.Length ? _chars.Length : parameter.Size; return; } if (value is char) { _singleCharArray[0] = (char)value; _chars = _singleCharArray; _charLen = 1; return; } _str = Convert.ToString(value); _charLen = parameter == null || parameter.Size <= 0 || parameter.Size >= _str.Length ? _str.Length : parameter.Size; }
/// <summary>See <i>"X.690"</i><cite>X.690</cite>, chapter 8.5 and /// <see href="http://technet.microsoft.com/en-us/library/0b34tf65.aspx">IEEE Floating-Point /// Representation</see>. Of course the assumption is that C# has the same floating point representation as C++ /// (pretty safe, as floating point calculations are done by the hardware).</summary> private static void WriteReal(WriteBuffer writeBuffer, double value) { if (!BitConverter.IsLittleEndian) { throw new NotSupportedException("Method is not supported for big endian system."); } if (double.IsInfinity(value)) { writeBuffer[writeBuffer.Count++] = (byte)(value > 0 ? 0x40 : 0x41); // 8.5.6 c) and 8.5.9 return; } if (double.IsNaN(value)) { writeBuffer[writeBuffer.Count++] = 0x42; // 8.5.9 return; } var bits = BitConverter.DoubleToInt64Bits(value); if (bits == NegativeZeroInteger) { writeBuffer[writeBuffer.Count++] = 0x43; // 8.5.3 and 8.5.9 return; } // 8.5.2 if (bits == 0) { return; } // 8.5.6 a) byte firstContentsOctet = 0x80; const long SignMask = long.MinValue; // 8.5.7.1 if ((bits & SignMask) != 0) { firstContentsOctet |= 0x40; } var exponent = ((bits & Constants.DoubleExponentMask) >> Constants.DoubleMantissaBits) - Constants.DoubleExponentBias; var exponentShift = Get8BitStartShift(exponent, true); firstContentsOctet |= (byte)(GetLengthFromShift8Bit(exponentShift) - 1); // 8.5.7.4 writeBuffer[writeBuffer.Count++] = firstContentsOctet; Write8Bit(writeBuffer, exponent, exponentShift); const long MantissaAssumedLeadingOne = 1L << Constants.DoubleMantissaBits; var mantissa = (bits & Constants.DoubleMantissaMask) | MantissaAssumedLeadingOne; // CER denormalization 11.3.1 (not required but saves space) while ((mantissa & 0xFF) == 0) { mantissa >>= Constants.BitsPerByte; } while ((mantissa & 0x01) == 0) { mantissa >>= 1; } // TODO: According to 8.5.7.5 we should pass false below, but we pass true to avoid a bug in EmberLib. Write8Bit(writeBuffer, mantissa, Get8BitStartShift(mantissa, true)); // 8.5.6.5 }
private HResult GetFileStream( int commandId, string relativePath, long byteOffset, uint length, Guid streamGuid, byte[] contentId, byte[] providerId, uint triggeringProcessId, string triggeringProcessImageFileName) { Console.WriteLine($"GetFileStream: `{relativePath}`"); if (!this.FileExists(relativePath)) { return(HResult.FileNotFound); } try { const int bufferSize = 64 * 1024; using (WriteBuffer writeBuffer = this.virtualizationInstance.CreateWriteBuffer(bufferSize)) { ulong writeOffset = 0; FileSystemResult hydrateFileResult = this.HydrateFile( relativePath, bufferSize, (readBuffer, bytesToCopy) => { writeBuffer.Stream.Seek(0, SeekOrigin.Begin); writeBuffer.Stream.Write(readBuffer, 0, (int)bytesToCopy); HResult writeResult = this.virtualizationInstance.WriteFile(streamGuid, writeBuffer, writeOffset, bytesToCopy); if (writeResult != HResult.Ok) { Console.WriteLine("WriteFile faild: " + writeResult); return(false); } writeOffset += bytesToCopy; return(true); }); if (hydrateFileResult != FileSystemResult.Success) { return(HResult.InternalError); } } } catch (IOException e) { Console.WriteLine("IOException in GetFileStream: " + e.Message); return(HResult.InternalError); } catch (UnauthorizedAccessException e) { Console.WriteLine("UnauthorizedAccessException in GetFileStream: " + e.Message); return(HResult.InternalError); } return(HResult.Ok); }
private MessageEncodingStream(S101Message message, WriteBuffer rawBuffer, FramingStream framingStream) { this.unframedBuffer = new WriteBuffer(this.WriteUnframedAsync, Constants.MessageHeaderMaxLength); this.message = message; this.rawBuffer = rawBuffer; this.framingStream = framingStream; }
private static void Write8Bit(WriteBuffer writeBuffer, long value, int shift) { for (; shift >= 0; shift -= 8) { writeBuffer[writeBuffer.Count++] = (byte)((value >> shift) & 0xFF); } }
internal override bool Write(WriteBuffer buf) { Contract.Requires(Statement != null); switch (_state) { case State.WroteNothing: _statementNameBytes = Statement.Length == 0 ? PGUtil.EmptyBuffer : _encoding.GetBytes(Statement); _queryLen = _encoding.GetByteCount(Query); if (buf.WriteSpaceLeft < 1 + 4 + _statementNameBytes.Length + 1) { return false; } var messageLength = 1 + // Message code 4 + // Length _statementNameBytes.Length + 1 + // Null terminator _queryLen + 1 + // Null terminator 2 + // Number of parameters ParameterTypeOIDs.Count * 4; buf.WriteByte(Code); buf.WriteInt32(messageLength - 1); buf.WriteBytesNullTerminated(_statementNameBytes); goto case State.WroteHeader; case State.WroteHeader: _state = State.WroteHeader; if (_queryLen <= buf.WriteSpaceLeft) { buf.WriteString(Query); goto case State.WroteQuery; } if (_queryLen <= buf.Size) { // String can fit entirely in an empty buffer. Flush and retry rather than // going into the partial writing flow below (which requires ToCharArray()) return false; } _queryChars = Query.ToCharArray(); _charPos = 0; goto case State.WritingQuery; case State.WritingQuery: _state = State.WritingQuery; int charsUsed; bool completed; buf.WriteStringChunked(_queryChars, _charPos, _queryChars.Length - _charPos, true, out charsUsed, out completed); if (!completed) { _charPos += charsUsed; return false; } goto case State.WroteQuery; case State.WroteQuery: _state = State.WroteQuery; if (buf.WriteSpaceLeft < 1 + 2) { return false; } buf.WriteByte(0); // Null terminator for the query buf.WriteInt16((short)ParameterTypeOIDs.Count); goto case State.WritingParameterTypes; case State.WritingParameterTypes: _state = State.WritingParameterTypes; for (; _parameterTypePos < ParameterTypeOIDs.Count; _parameterTypePos++) { if (buf.WriteSpaceLeft < 4) { return false; } buf.WriteInt32((int)ParameterTypeOIDs[_parameterTypePos]); } _state = State.WroteAll; return true; default: throw PGUtil.ThrowIfReached(); } }
internal override void WriteFully(WriteBuffer buf) { buf.WriteByte(Code); buf.WriteInt32(4); }
internal override void WriteFully(WriteBuffer buf) { buf.WriteByte((byte)BackendMessageCode.CopyDone); buf.WriteInt32(4); }
bool WriteParameters(WriteBuffer buf, ref DirectBuffer directBuf) { for (; _paramIndex < InputParameters.Count; _paramIndex++) { var param = InputParameters[_paramIndex]; if (!_wroteParamLen) { if (param.Value is DBNull) { if (buf.WriteSpaceLeft < 4) { return false; } buf.WriteInt32(-1); continue; } param.LengthCache?.Rewind(); } var handler = param.Handler; var asChunkingWriter = handler as IChunkingTypeHandler; if (asChunkingWriter != null) { if (!_wroteParamLen) { if (buf.WriteSpaceLeft < 4) { return false; } buf.WriteInt32(param.ValidateAndGetLength()); asChunkingWriter.PrepareWrite(param.Value, buf, param.LengthCache, param); _wroteParamLen = true; } if (!asChunkingWriter.Write(ref directBuf)) { return false; } _wroteParamLen = false; continue; } var len = param.ValidateAndGetLength(); var asSimpleWriter = (ISimpleTypeHandler)handler; if (buf.WriteSpaceLeft < len + 4) { Contract.Assume(buf.Size >= len + 4); return false; } buf.WriteInt32(len); asSimpleWriter.Write(param.Value, buf, param); } return true; }
public bool WriteTo2(WriteBuffer buffer) { // 0. init header // 1. loop on header // 2. loop on Key, if any // 3. loop on Data, if any // 4. done switch (state) { case STATE_INITIAL: PrepareHeader(); state = STATE_WRITE_HEADER; goto case STATE_WRITE_HEADER; case STATE_WRITE_HEADER: writeOffset += buffer.Append(header, writeOffset, headerLength - writeOffset); if (writeOffset < headerLength) return true; if (Key.Length > 0) { writeOffset = 0; state = STATE_WRITE_KEY; goto case STATE_WRITE_KEY; } goto case STATE_PREPARE_BODY; case STATE_WRITE_KEY: writeOffset += buffer.Append(Key.Array, writeOffset, Key.Length - writeOffset); if (writeOffset < Key.Length) return true; goto case STATE_PREPARE_BODY; case STATE_PREPARE_BODY: if (Data.Count > 0) { writeOffset = 0; state = STATE_WRITE_BODY; goto case STATE_WRITE_BODY; } break; case STATE_WRITE_BODY: writeOffset += buffer.Append(Data.Array, Data.Offset + writeOffset, Data.Count - writeOffset); if (writeOffset < Data.Count) return true; break; } state = STATE_DONE; return false; }
/// <summary>See <i>"X.690"</i><cite>X.690</cite>, chapter 8.1.2.</summary> private static void WriteIdentifier(WriteBuffer writeBuffer, EmberId emberId) { if (emberId.Number <= 30) { writeBuffer[writeBuffer.Count++] = GetLeadingOctet(emberId, emberId.Number); } else { writeBuffer[writeBuffer.Count++] = GetLeadingOctet(emberId, 0x1F); Write7Bit(writeBuffer, emberId.Number, Get7BitStartShift(emberId.Number)); } }
internal override void WriteFully(WriteBuffer buf) { buf.WriteBytes(_data, 0, _data.Length); }
/// <summary>See <i>"X.690"</i><cite>X.690</cite>, chapter 8.1.3.</summary> private static void WriteLength(WriteBuffer writeBuffer, int? length, int shift, int lengthLength) { if (lengthLength == 1) { writeBuffer[writeBuffer.Count++] = length.HasValue ? (byte)length : (byte)0x80; } else { writeBuffer[writeBuffer.Count++] = (byte)((lengthLength - 1) | 0x80); Write8Bit(writeBuffer, length.GetValueOrDefault(), shift); } }
/// <summary> /// Bind is a special message in that it supports the "direct buffer" optimization, which allows us to write /// user byte[] data directly to the stream rather than copying it into our buffer. It therefore has its own /// special overload of Write below. /// </summary> /// <param name="buf"></param> /// <returns></returns> internal override bool Write(WriteBuffer buf) { throw new NotSupportedException($"Internal error, call the overload of {nameof(Write)} which accepts a {nameof(DirectBuffer)}"); }
internal override void WriteFully(WriteBuffer buf) { buf.WriteInt32(Length); buf.WriteInt32(80877103); }
protected override void Write(object value, WriteBuffer buf, NpgsqlParameter parameter = null) => DoWrite(value, buf, false);
internal bool Write(WriteBuffer buf, ref DirectBuffer directBuf) { Contract.Requires(Statement != null && Statement.All(c => c < 128)); Contract.Requires(Portal != null && Portal.All(c => c < 128)); switch (_state) { case State.Header: var formatCodesSum = InputParameters.Select(p => p.FormatCode).Sum(c => (int)c); _formatCodeListLength = formatCodesSum == 0 ? 0 : formatCodesSum == InputParameters.Count ? 1 : InputParameters.Count; var headerLength = 1 + // Message code 4 + // Message length Portal.Length + 1 + Statement.Length + 1 + 2; // Number of parameter format codes that follow if (buf.WriteSpaceLeft < headerLength) { Contract.Assume(buf.Size >= headerLength, "Buffer too small for Bind header"); return false; } foreach (var c in InputParameters.Select(p => p.LengthCache).Where(c => c != null)) c.Rewind(); var messageLength = headerLength + 2 * _formatCodeListLength + // List of format codes 2 + // Number of parameters 4 * InputParameters.Count + // Parameter lengths InputParameters.Select(p => p.ValidateAndGetLength()).Sum() + // Parameter values 2 + // Number of result format codes 2 * (UnknownResultTypeList?.Length ?? 1); // Result format codes buf.WriteByte(Code); buf.WriteInt32(messageLength-1); buf.WriteBytesNullTerminated(Encoding.ASCII.GetBytes(Portal)); buf.WriteBytesNullTerminated(Encoding.ASCII.GetBytes(Statement)); buf.WriteInt16(_formatCodeListLength); _paramIndex = 0; _state = State.ParameterFormatCodes; goto case State.ParameterFormatCodes; case State.ParameterFormatCodes: // 0 length implicitly means all-text, 1 means all-binary, >1 means mix-and-match if (_formatCodeListLength == 1) { if (buf.WriteSpaceLeft < 2) return false; buf.WriteInt16((short)FormatCode.Binary); } else if (_formatCodeListLength > 1) for (; _paramIndex < InputParameters.Count; _paramIndex++) { if (buf.WriteSpaceLeft < 2) return false; buf.WriteInt16((short)InputParameters[_paramIndex].FormatCode); } _state = State.ParameterCount; goto case State.ParameterCount; case State.ParameterCount: if (buf.WriteSpaceLeft < 2) return false; buf.WriteInt16(InputParameters.Count); _paramIndex = 0; _state = State.ParameterValues; goto case State.ParameterValues; case State.ParameterValues: if (!WriteParameters(buf, ref directBuf)) return false; _state = State.ResultFormatCodes; goto case State.ResultFormatCodes; case State.ResultFormatCodes: if (UnknownResultTypeList != null) { if (buf.WriteSpaceLeft < 2 + UnknownResultTypeList.Length * 2) return false; buf.WriteInt16(UnknownResultTypeList.Length); foreach (var t in UnknownResultTypeList) buf.WriteInt16(t ? 0 : 1); } else { if (buf.WriteSpaceLeft < 4) return false; buf.WriteInt16(1); buf.WriteInt16(AllResultTypesAreUnknown ? 0 : 1); } _state = State.Done; return true; default: throw PGUtil.ThrowIfReached(); } }
public override void PrepareWrite(object value, WriteBuffer buf, LengthCache lengthCache, NpgsqlParameter parameter = null) { base.PrepareWrite(value, buf, lengthCache, parameter); _value = value; }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////// internal static async Task<FramingStream> CreateAsync( WriteBuffer writeBuffer, CancellationToken cancellationToken) { await writeBuffer.ReserveAsync(1, cancellationToken); return new FramingStream(writeBuffer); }
private FramingStream(WriteBuffer writeBuffer) : base(null, writeBuffer) { writeBuffer[writeBuffer.Count++] = Frame.BeginOfFrame; }
private static void Write7Bit(WriteBuffer writeBuffer, long value, int shift) { for (; shift > 0; shift -= 7) { writeBuffer[writeBuffer.Count++] = (byte)(((value >> shift) & 0x7F) | 0x80); } writeBuffer[writeBuffer.Count++] = (byte)(value & 0x7F); }
protected override Task Write(object value, WriteBuffer buf, LengthCache lengthCache, NpgsqlParameter parameter, bool async, CancellationToken cancellationToken) { if (parameter?.ConvertedValue != null) value = parameter.ConvertedValue; }
internal override void WriteFully(WriteBuffer buf) { buf.WriteByte(Code); buf.WriteInt32(Length - 1); buf.WriteBytes(Password, 0, Password.Length); }