async Task IAsyncBinaryWriter.CopyFromAsync <TArg>(Func <TArg, CancellationToken, ValueTask <ReadOnlyMemory <byte> > > supplier, TArg arg, CancellationToken token) { for (ReadOnlyMemory <byte> source; !(source = await supplier(arg, token).ConfigureAwait(false)).IsEmpty; token.ThrowIfCancellationRequested()) { writer.Write(source.Span); } }
public override void SerializeMessage(InitMessage message, int protocolVersion, NetworkPeerContext peerContext, IBufferWriter <byte> output) { output.WriteUShort((ushort)message.GlobalFeatures.Length, true); output.Write(message.GlobalFeatures); output.WriteUShort((ushort)message.Features.Length, true); output.Write(message.Features); }
//Can we change the ChaCha20Poly1305 input to some kind of ICrypto interface or action with 'Encrypt' and 'Decrypt'? private void Pack(IBufferWriter <byte> output, CryptoDtoHeaderDto header, ChaCha20Poly1305 crypto, ReadOnlySpan <byte> dtoNameBuffer, ReadOnlySpan <byte> dtoBuffer) { lock (bufferLock) { headerBuffer.Clear(); MessagePackSerializer.Serialize(headerBuffer, header); ReadOnlySpan <byte> headerBytes = headerBuffer.WrittenSpan; ushort headerLength = (ushort)headerBytes.Length; BinaryPrimitives.WriteUInt16LittleEndian(headerLengthBytes, headerLength); ushort dtoNameLength = (ushort)dtoNameBuffer.Length; BinaryPrimitives.WriteUInt16LittleEndian(dtoNameLengthBytes, dtoNameLength); ushort dtoLength = (ushort)dtoBuffer.Length; BinaryPrimitives.WriteUInt16LittleEndian(dtoLengthBytes, dtoLength); switch (header.Mode) { case CryptoDtoMode.ChaCha20Poly1305: { int adLength = 2 + headerLength; int aeLength = 2 + dtoNameLength + 2 + dtoLength; // Copy data into associated data buffer adBuffer.Clear(); adBuffer.Write(headerLengthBytes); adBuffer.Write(headerBytes); // Copy data into authenticated encryption buffer aeBuffer.Clear(); aeBuffer.Write(dtoNameLengthBytes); aeBuffer.Write(dtoNameBuffer); aeBuffer.Write(dtoLengthBytes); aeBuffer.Write(dtoBuffer); Span <byte> nonceSpan = new Span <byte>(nonceBytes); BinaryPrimitives.WriteUInt64LittleEndian(nonceSpan.Slice(4), header.Sequence); var adSpan = adBuffer.WrittenSpan; var aeSpan = aeBuffer.WrittenSpan; var cipherTextSpan = cipherText.Span.Slice(0, aeLength); cipherTextSpan.Clear(); Span <byte> tagSpan = tagBuffer; tagSpan.Clear(); crypto.Encrypt(nonceSpan, aeSpan, cipherTextSpan, tagSpan, adSpan); output.Write(adSpan); output.Write(cipherTextSpan); output.Write(tagSpan); break; } default: throw new CryptographicException("Mode not recognised"); } } }
public int Encode(IBufferWriter <byte> writer, IMessage pack) { var len = pack.CalculateSize(); var bytes = BitConverter.GetBytes(len); Array.Reverse(bytes); writer.Write(bytes); writer.Write(pack.ToByteArray()); return(4 + len); }
public void Write(string value) { using (var memoryOwner = _bufferPool.Rent(_encoding.Value.GetMaxByteCount(value.Length))) { int length = _encoding.Value.GetBytes(value.AsSpan(), memoryOwner.Memory.Span); Varint.SetUInt32((uint)length, _bufferWriter); _bufferWriter.Write(memoryOwner.Memory.Span.Slice(0, length)); } }
public void Write(ref HtmlToken token) { if (token.Type == HtmlTokenType.StartTag) { WriteStartTag(token.Name.Span, token.Attributes.Span, token.IsSelfClosing); } else if (token.RawText.Length > 0) { _writer.Write(token.RawText.Span); } }
public void WriteString(ReadOnlySpan <byte> value) { if (value == null) { WriteNull(); return; } WriteInteger(CborMajorType.TextString, (ulong)value.Length); _bufferWriter.Write(value); }
public async Task StreamAsBufferWriter() { IBufferWriter <byte> writer = this.stream; writer.Write(new byte[] { 1, 2, 3 }); writer.Write(new byte[] { 4, 5, 6, 7, 8, 9 }); await this.stream.FlushAsync(this.TimeoutToken); var readBuffer = new byte[10]; int bytesRead = await this.stream.ReadAsync(readBuffer, 0, 10, this.TimeoutToken); Assert.Equal(9, bytesRead); Assert.Equal(Enumerable.Range(1, 9).Select(i => (byte)i), readBuffer.Take(bytesRead)); }
private static bool WriteBulkString(byte[] input, IBufferWriter <byte> output) { output.Write(RedisConstants.BulkStringStart); if (!WriteNumber(input.Length, output)) { return(false); } output.Write(RedisConstants.CrLf); output.Write(input); output.Write(RedisConstants.CrLf); return(true); }
private void WritePartition(OffsetCommitRequest.Topic.Partition message, IBufferWriter <byte> output) { output.WriteInt(message.PartitionId); output.WriteLong(message.CommittedOffset); output.WriteInt(message.CommittedLeaderEpoc); output.Write(message.CommittedMetadata); }
public int Serialize(UInt256 typeInstance, int protocolVersion, IBufferWriter <byte> writer, ProtocolTypeSerializerOptions?options = null) { ReadOnlySpan <byte> span = typeInstance.GetBytes(); writer.Write(span); return(span.Length); }
private void WriteString(IBufferWriter writer, string text, params object[] formatters) { var str = string.Format(text, formatters); var buffer = _encoding.GetBytes(str); writer.Write(buffer, 0, buffer.Length); }
/// <summary> /// Uri编码 /// </summary> /// <param name="chars"></param> /// <param name="bufferWriter"></param> public static void UrlEncode(ReadOnlySpan <char> chars, IBufferWriter <byte> bufferWriter) { if (chars.IsEmpty) { return; } var byteCount = Encoding.UTF8.GetByteCount(chars); var source = chars.Length > 1024 ? new byte[byteCount] : stackalloc byte[byteCount]; Encoding.UTF8.GetBytes(chars, source); var destLength = 0; if (UrlEncodeTest(source, ref destLength) == false) { bufferWriter.Write(source); } else { var destination = bufferWriter.GetSpan(destLength); UrlEncodeCore(source, destination); bufferWriter.Advance(destLength); } }
/// <summary>Recursive method to print out the full stack trace of inner exceptions.</summary> /// <remarks> /// The method uses reverse recursion. The most inner will start to write first. /// </remarks> /// <param name="e">The exception.</param> /// <param name="writer">The buffer writer to receive the stack trace.</param> private static void DumpStackTrace(Exception e, IBufferWriter writer) { if (e.InnerException != null) { DumpStackTrace(e.InnerException, writer); } writer.Write(e.StackTrace.ToString()); }
public static int WriteBytes(this IBufferWriter <byte> writer, byte[] value) { ThrowHelper.ThrowArgumentNullException(nameof(value)); writer.Write(value); return(value.Length); }
/// <summary> /// Writes the contents of string builder to the buffer. /// </summary> /// <param name="writer">The buffer writer.</param> /// <param name="input">The string builder.</param> public static void Write(this IBufferWriter <char> writer, StringBuilder input) { foreach (var chunk in input.GetChunks()) { writer.Write(chunk.Span); } }
public void Serialize(TlvRecord message, IBufferWriter <byte> output) { // for now just fill the buffer output.Write(message.Payload.AsSpan()); // TODO }
public static void Write(this IBufferWriter file, string value) { for (var i = 0; i < value.Length; i++) { file.Write(value[i]); } }
private void WriteCompletionMessage(CompletionMessage completionMessage, IBufferWriter <byte> output) { var protobufCompletionMessage = new CompletionMessageProtobuf { Error = completionMessage.Error ?? "", InvocationId = completionMessage.InvocationId }; if (completionMessage.Headers != null) { protobufCompletionMessage.Headers.Add(completionMessage.Headers); } var result = new ArgumentDescriptor(0, Array.Empty <byte>()); if (completionMessage.Result != null) { result = _argumentSerializer.SerializeArgument(completionMessage.Result); } var packedMessage = MessageDescriptor.PackMessage(HubProtocolConstants.CompletionMessageType, protobufCompletionMessage.ToByteArray(), new List <ArgumentDescriptor> { result }); output.Write(packedMessage); }
/// <summary> /// Writes the sequence of elements to the buffer. /// </summary> /// <typeparam name="T">The type of the elements in the sequence.</typeparam> /// <param name="writer">The buffer writer.</param> /// <param name="value">The sequence of elements to be written.</param> public static void Write <T>(this IBufferWriter <T> writer, ReadOnlySequence <T> value) { foreach (var segment in value) { writer.Write(segment.Span); } }
public static unsafe void Write(this IBufferWriter file, char value) { var b = (byte)value; byte *ptr = &b; file.Write(ptr, 1); }
public void WriteStreamData(uint streamId, ArraySegment <byte> payload) { BinaryPrimitives.WriteUInt32BigEndian(_bufferWriter.GetSpan(4), (uint)PacketType.StreamData); _bufferWriter.Advance(4); BinaryPrimitives.WriteUInt32BigEndian(_bufferWriter.GetSpan(4), streamId); _bufferWriter.Advance(4); _bufferWriter.Write(payload.AsSpan()); }
public int Encode(IBufferWriter <byte> writer, MesMessage pack) { var bytes = Encoding.UTF8.GetBytes(pack.ToString()); var span = new ReadOnlySpan <byte>(bytes); writer.Write(span); return(bytes.Length); }
public void WriteMessage(byte[] message, IBufferWriter <byte> output) { if (message.Length > 1024) { throw new Exception($"{nameof(ByteWriter)}:message to long. Maximum length - 1024"); } output.Write(message); }
public static void WriteLengthPrefix(long length, IBufferWriter <byte> output) { Span <byte> lenBuffer = stackalloc byte[5]; var lenNumBytes = WriteLengthPrefix(length, lenBuffer); output.Write(lenBuffer.Slice(0, lenNumBytes)); }
public static void SerializeString(IBufferWriter <byte> writer, string value) { var encoded = Encoding.UTF8.GetBytes(value); writer.Write(encoded); writer.GetSpan(1)[0] = 0; writer.Advance(1); }
public void WriteMessage(ReadOnlyMemory <byte> message, IBufferWriter <byte> output) { if (message.Length > 1024) { throw new RabbitMQException($"{nameof(ByteWriter)}:message to long. Maximum length - 1024"); } output.Write(message.Span); }
public int Encode(IBufferWriter <byte> writer, HttpResponse pack) { foreach (var memory in pack.Data) { writer.Write(memory.Span); } return((int)pack.Data.Length); }
public static void Write(this IBufferWriter <byte> w, string x) { var span = w.GetSpan(x.Length * sizeof(char) + sizeof(int)); w.Write(x.Length); var body = span.Slice(sizeof(int)); MemoryMarshal.Cast <char, byte>(x.AsSpan()).CopyTo(body); }
public void CopyTo(IBufferWriter <byte> output) { // copy buffer to output // Try to minimize segments in the target writer by hinting at the total size. output.GetSpan(Length); foreach (var segment in AsReadOnlySequence) { output.Write(segment.Span); } }
public static void Write <T>(this IBufferWriter <T> writer, ReadOnlySequence <T> value) { if (value.IsSingleSegment) { writer.Write(value.FirstSpan); } else { WriteSlow(writer, in value); }
/// <summary> /// Serialize a message into something that can be transported over the socket. /// </summary> /// <param name="message">Message to serialize</param> /// <param name="writer">Buffer used to store the message</param> public void Serialize(object message, IBufferWriter writer) { var serializer = new JsonSerializer(); serializer.TypeNameHandling = TypeNameHandling.All; var sb = new StringBuilder(); serializer.Serialize(new JsonTextWriter(new StringWriter(sb)), message); //var str = JsonConvert.SerializeObject(message); var bodyBytes = Encoding.UTF8.GetBytes(sb.ToString()); // version writer.Write(VersionBuffer, 0, VersionBuffer.Length); //length var buffer = BitConverter.GetBytes(bodyBytes.Length); writer.Write(buffer, 0, buffer.Length); //body writer.Write(bodyBytes, 0, bodyBytes.Length); }