5 namespace ByteFX
.Data
.MySqlClient
8 /// Summary description for Packet.
10 internal class Packet
: MemoryStream
15 public static int NULL_LEN
=-1;
16 private int shortLen
= 2;
17 private int intLen
= 3;
18 private int longLen
= 4;
19 private bool longInts
= false;
21 public Packet(bool longInts
) : base()
26 public Packet(byte[] bytes
, bool longInts
) : base(bytes
.Length
)
28 this.Write( bytes
, 0, bytes
.Length
);
35 get { return longInts; }
47 public int CompleteLength
49 get { return completeLen; }
50 set { completeLen = value; }
55 get { return sequence; }
56 set { sequence = value; }
59 public Encoding Encoding
61 set { encoding = value; }
62 get { return encoding; }
71 public byte this[int index
]
77 byte b
= (byte)ReadByte();
85 get { return (int)base.Length; }
88 public bool IsLastPacket()
90 return (Length
== 1 && this[0] == 0xfe);
93 public void Append( Packet p
)
95 long oldPos
= Position
;
97 this.Write( p
.GetBuffer(), 0, p
.Length
);
101 public Packet
ReadPacket()
103 if (! HasMoreData
) return null;
105 int len
= this.ReadInteger(3);
106 byte seq
= (byte)this.ReadByte();
107 byte[] buf
= new byte[ len
];
108 this.Read( buf
, 0, len
);
109 Packet p
= new Packet( buf
, LongInts
);
111 p
.Encoding
= this.Encoding
;
115 public int ReadNBytes()
117 byte c
= (byte)ReadByte();
118 if (c
< 1 || c
> 4) throw new MySqlException("Unexpected byte count received");
119 return ReadInteger((int)c
);
122 public string ReadLenString()
124 long len
= ReadLenInteger();
126 byte[] buffer
= new Byte
[len
];
127 Read(buffer
, 0, (int)len
);
128 return encoding
.GetString( buffer
, 0, (int)len
);
135 /// <param name="v"></param>
136 /// <param name="numbytes"></param>
137 public void WriteInteger( int v
, int numbytes
)
141 if (numbytes
< 1 || numbytes
> 4)
142 throw new ArgumentOutOfRangeException("Wrong byte count for WriteInteger");
144 for (int x
=0; x
< numbytes
; x
++)
146 WriteByte( (byte)(val
&0xff) );
154 /// <param name="numbytes"></param>
155 /// <returns></returns>
156 public int ReadInteger(int numbytes
)
160 for (int x
=0; x
< numbytes
; x
++)
172 /// <returns></returns>
173 public long ReadLenInteger()
175 byte c
= (byte)ReadByte();
179 case 251 : return NULL_LEN
;
180 case 252 : return ReadInteger(shortLen
);
181 case 253 : return ReadInteger(intLen
);
182 case 254 : return ReadInteger(longLen
);
187 public bool HasMoreData
189 get { return Position < Length; }
192 #region String Functions
193 public string ReadString()
195 System
.Text
.StringBuilder sb
= new System
.Text
.StringBuilder();
197 while ( HasMoreData
)
199 byte b
= (byte)ReadByte();
201 sb
.Append( Convert
.ToChar( b
));
204 return sb
.ToString();
207 public void WriteString(string v
, Encoding encoding
)
209 WriteStringNoNull(v
, encoding
);
213 public void WriteStringNoNull(string v
, Encoding encoding
)
215 byte[] bytes
= encoding
.GetBytes(v
);
216 Write(bytes
, 0, bytes
.Length
);