public static void Write(this Stream stream, string obj) { BSDebug.TraceStart("WriteString", stream.Position); const int useBufferFrom = 7; var length = obj.Length; var bytesLength = length * sizeof(char); // Write length stream.Write(length); if (length < useBufferFrom) { unsafe { fixed(char *objPtr = obj) { var valueBytePtr = (byte *)objPtr; for (int i = 0; i < bytesLength; i++) { stream.WriteByte(valueBytePtr[i]); } } } } else { var buffer = Buffers.Get(bytesLength); unsafe { // It work faster but unfortunately available only from .net framework 4.6 //fixed (char* valuePtr = value) // fixed (byte* bufferPtr = buffer) // Buffer.MemoryCopy(valuePtr, bufferPtr, buffer.Length, usedLength); fixed(void *objPtr = obj) Marshal.Copy(new IntPtr(objPtr), buffer, 0, bytesLength); } // Write data stream.Write(buffer, 0, bytesLength); } BSDebug.TraceEnd("WriteString", stream.Position); }
public static void Write(this Stream stream, string obj) { BSDebug.TraceStart("WriteString", stream.Position); const int useBufferFrom = 4; var length = obj.Length; var bytesLength = length * sizeof(char); // Write length stream.Write(length); if (length < useBufferFrom) { unsafe { fixed(char *objPtr = obj) { var objBytePtr = (byte *)objPtr; for (var i = 0; i < bytesLength; i++) { stream.WriteByte(objBytePtr[i]); } } } } else { var buffer = Buffers.Get(bytesLength); unsafe { fixed(char *valuePtr = obj) fixed(byte *bufferPtr = buffer) Buffer.MemoryCopy(valuePtr, bufferPtr, buffer.Length, bytesLength); } // Write data stream.Write(buffer, 0, bytesLength); } BSDebug.TraceEnd("WriteString", stream.Position); }
public static string ReadString(this Stream stream) { BSDebug.TraceStart("ReadString", stream.Position); var length = stream.ReadInt32(); var bufferLength = length * sizeof(char); var buffer = Buffers.Get(bufferLength); stream.Read(buffer, 0, bufferLength); BSDebug.TraceEnd("ReadString", stream.Position); unsafe { fixed(byte *bufferPtr = buffer) { var bufferCharPtr = (char *)bufferPtr; return(new string(bufferCharPtr, 0, length)); } } }