HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Packet Read\Write

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
packetwriteread

Problem

Is this a good method to Read\Write packets

```
using System.Text;

namespace namespace
{
public unsafe class DataPacket
{
public DataPacket(byte[] buffer)
{
_buffer = new byte[buffer.Length];
System.Buffer.BlockCopy(buffer, 0, _buffer, 0, buffer.Length);
}

public DataPacket(ushort size, ushort type)
{
_buffer = new byte[size];
WriteUInt16(size, 0);
WriteUInt16(type, 2);
}

private readonly byte[] _buffer;
protected byte[] Buffer
{
get
{
return _buffer;
}
}

public byte* Ptr
{
get
{
fixed (byte* ptr = Buffer)
return ptr;
}
}

public ushort Size
{
get
{
return ReadUInt16(0);
}
set
{
WriteUInt16(value, 0);
}
}

public ushort Type
{
get
{
return ReadUInt16(2);
}
set
{
WriteUInt16(value, 2);
}
}

public void WriteSByte(sbyte value, int offset)
{
((sbyte)(Ptr + offset)) = value;
}
public void WriteInt16(short value, int offset)
{
((short)(Ptr + offset)) = value;
}
public void WriteInt32(int value, int offset)
{
((int)(Ptr + offset)) = value;
}
public void WriteInt64(long value, int offset)
{
((long)(Ptr + offset)) = value;
}
public void WriteByte(byte value, int offset)
{
(*(Ptr + offset)) = value;
}
public void WriteUInt16(ushort value, int offset)
{
((ushort)(Ptr + offset)) = value;
}
public void

Solution

At first glance, I can see several problem with this code (why are you even using pointers? what happens with non-ASCII characters in WriteString()?). But my main issue is that BinaryReader and BinaryWriter do something very similar, so you're kind of reinventing the wheel.

Context

StackExchange Code Review Q#15720, answer score: 4

Revisions (0)

No revisions yet.