|
|
@@ -1,34 +1,86 @@
|
|
|
package network
|
|
|
|
|
|
import (
|
|
|
- "bytes"
|
|
|
+ "encoding/binary"
|
|
|
"io"
|
|
|
)
|
|
|
|
|
|
-// ReadBigEndianString 大端读取字符串 TODO 考虑改为一个网络字节序得写入和读取器
|
|
|
-func ReadBigEndianString(bigEndianBytes []byte) (string, error) {
|
|
|
- // 使用bytes.Buffer来模拟一个io.Reader
|
|
|
- reader := bytes.NewReader(bigEndianBytes)
|
|
|
+type DataReader struct {
|
|
|
+ r io.Reader
|
|
|
+}
|
|
|
+
|
|
|
+func NewDataReader(r io.Reader) *DataReader {
|
|
|
+ return &DataReader{r: r}
|
|
|
+}
|
|
|
|
|
|
- // 初始化一个buffer,用于存放读取的字符串
|
|
|
- var buffer []byte
|
|
|
+func (reader *DataReader) Byte() (byte, error) {
|
|
|
+ var b byte
|
|
|
|
|
|
- // 使用binary.Read以大端模式读取字符串
|
|
|
- // 因为字符串可能包含\x00,所以需要读取到\x00为止
|
|
|
- for {
|
|
|
- b := make([]byte, 1)
|
|
|
+ err := binary.Read(reader.r, binary.BigEndian, &b)
|
|
|
+ if err != nil {
|
|
|
+ return 0, err
|
|
|
+ }
|
|
|
|
|
|
- _, err := reader.Read(b)
|
|
|
- if err != nil && err != io.EOF {
|
|
|
- return "", err
|
|
|
- }
|
|
|
+ return b, nil
|
|
|
+}
|
|
|
+
|
|
|
+func (reader *DataReader) Bytes(bytesLen int) ([]byte, error) {
|
|
|
+ retBytes := make([]byte, bytesLen)
|
|
|
+ err := binary.Read(reader.r, binary.BigEndian, retBytes)
|
|
|
+ if err != nil {
|
|
|
+ return nil, err
|
|
|
+ }
|
|
|
|
|
|
- if b[0] == 0 {
|
|
|
- break
|
|
|
- }
|
|
|
+ return retBytes, nil
|
|
|
+}
|
|
|
+
|
|
|
+func (reader *DataReader) Uint8() (uint8, error) {
|
|
|
+ var b uint8
|
|
|
+
|
|
|
+ err := binary.Read(reader.r, binary.BigEndian, &b)
|
|
|
+ if err != nil {
|
|
|
+ return 0, err
|
|
|
+ }
|
|
|
+
|
|
|
+ return b, nil
|
|
|
+}
|
|
|
+
|
|
|
+func (reader *DataReader) Uint16() (uint16, error) {
|
|
|
+ retBytes := make([]byte, 2)
|
|
|
+ _, err := reader.r.Read(retBytes)
|
|
|
+ if err != nil {
|
|
|
+ return 0, err
|
|
|
+ }
|
|
|
+
|
|
|
+ return binary.BigEndian.Uint16(retBytes), nil
|
|
|
+}
|
|
|
+
|
|
|
+func (reader *DataReader) Uint32() (uint32, error) {
|
|
|
+ retBytes := make([]byte, 4)
|
|
|
+ _, err := reader.r.Read(retBytes)
|
|
|
+ if err != nil {
|
|
|
+ return 0, err
|
|
|
+ }
|
|
|
+
|
|
|
+ return binary.BigEndian.Uint32(retBytes), nil
|
|
|
+}
|
|
|
+
|
|
|
+func (reader *DataReader) Uint64() (uint64, error) {
|
|
|
+ retBytes := make([]byte, 8)
|
|
|
+ _, err := reader.r.Read(retBytes)
|
|
|
+ if err != nil {
|
|
|
+ return 0, err
|
|
|
+ }
|
|
|
+
|
|
|
+ return binary.BigEndian.Uint64(retBytes), nil
|
|
|
+}
|
|
|
|
|
|
- buffer = append(buffer, b...)
|
|
|
+func (reader *DataReader) String(bytesLen int) (string, error) {
|
|
|
+ retBytes := make([]byte, bytesLen)
|
|
|
+ err := binary.Read(reader.r, binary.BigEndian, retBytes)
|
|
|
+ if err != nil {
|
|
|
+ return "", err
|
|
|
}
|
|
|
|
|
|
- return string(buffer), nil
|
|
|
+ return string(retBytes), nil
|
|
|
}
|