/// <inheritdoc/> public override void WriteString(string value, UTF8Encoding encoding) { if (value == null) { throw new ArgumentNullException("value"); } if (encoding == null) { throw new ArgumentNullException("encoding"); } ThrowIfDisposed(); using var rentedSegment = encoding.GetBytesUsingThreadStaticBuffer(value); var segment = rentedSegment.Segment; WriteInt32(segment.Count + 1); _stream.Write(segment.Array, 0, segment.Count); _stream.WriteByte(0); }
/// <inheritdoc/> public override void WriteString(string value, UTF8Encoding encoding) { ThrowIfDisposed(); var maxLength = encoding.GetMaxByteCount(value.Length) + 5; PrepareToWrite(maxLength); int actualLength; var segment = _buffer.AccessBackingBytes(_position); if (segment.Count >= maxLength) { actualLength = encoding.GetBytes(value, 0, value.Length, segment.Array, segment.Offset + 4); var lengthPlusOne = actualLength + 1; segment.Array[segment.Offset] = (byte)lengthPlusOne; segment.Array[segment.Offset + 1] = (byte)(lengthPlusOne >> 8); segment.Array[segment.Offset + 2] = (byte)(lengthPlusOne >> 16); segment.Array[segment.Offset + 3] = (byte)(lengthPlusOne >> 24); segment.Array[segment.Offset + 4 + actualLength] = 0; } else { using var rentedSegmentEncoded = encoding.GetBytesUsingThreadStaticBuffer(value); var bytes = rentedSegmentEncoded.Segment.Array; actualLength = rentedSegmentEncoded.Segment.Count; var lengthPlusOneBytes = BitConverter.GetBytes(actualLength + 1); _buffer.SetBytes(_position, lengthPlusOneBytes, 0, 4); _buffer.SetBytes(_position + 4, bytes, 0, actualLength); _buffer.SetByte(_position + 4 + actualLength, 0); } SetPositionAfterWrite(_position + actualLength + 5); }