1
0
mirror of https://github.com/fumiama/WireGold.git synced 2026-06-12 04:43:22 +08:00

feat: impl. new protol design & new head

This commit is contained in:
源文雨
2025-03-12 22:20:02 +09:00
parent 60209117b7
commit f4fd9b1423
49 changed files with 1643 additions and 1137 deletions

45
internal/bin/data.go Normal file
View File

@@ -0,0 +1,45 @@
package bin
import (
"encoding/binary"
"reflect"
"unsafe"
)
// IsLittleEndian judge by binary packet.
var IsLittleEndian = reflect.ValueOf(&binary.NativeEndian).Elem().Field(0).Type().String() == "binary.littleEndian"
// slice is the runtime representation of a slice.
// It cannot be used safely or portably and its representation may
// change in a later release.
//
// Unlike reflect.SliceHeader, its Data field is sufficient to guarantee the
// data it references will not be garbage collected.
type slice struct {
data unsafe.Pointer
len int
cap int
}
// BytesToString 没有内存开销的转换
func BytesToString(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}
// StringToBytes 没有内存开销的转换
func StringToBytes(s string) (b []byte) {
bh := (*slice)(unsafe.Pointer(&b))
sh := (*slice)(unsafe.Pointer(&s)) // 不要访问 sh.cap
bh.data = sh.data
bh.len = sh.len
bh.cap = sh.len
return b
}
func IsNilInterface(x any) bool {
return x == nil || reflect.ValueOf(x).IsZero()
}
func IsNonNilInterface(x any) bool {
return !IsNilInterface(x)
}

10
internal/bin/pool.go Normal file
View File

@@ -0,0 +1,10 @@
package bin
import (
"github.com/fumiama/orbyte/pbuf"
)
// SelectWriter 从池中取出一个 Writer
func SelectWriter() *Writer {
return (*Writer)(pbuf.NewBuffer(nil))
}

66
internal/bin/writer.go Normal file
View File

@@ -0,0 +1,66 @@
package bin
// https://github.com/Mrs4s/MiraiGo/blob/master/binary/writer.go
import (
"encoding/binary"
"github.com/fumiama/orbyte/pbuf"
)
// Writer 写入
type Writer pbuf.OBuffer
func NewWriterF(f func(writer *Writer)) pbuf.Bytes {
w := SelectWriter()
f(w)
return w.ToBytes()
}
func (w *Writer) P(f func(*pbuf.Buffer)) *Writer {
(*pbuf.OBuffer)(w).P(f)
return w
}
func (w *Writer) Write(b []byte) (n int, err error) {
w.P(func(buf *pbuf.Buffer) {
n, err = buf.Write(b)
})
return
}
func (w *Writer) WriteByte(b byte) (err error) {
w.P(func(buf *pbuf.Buffer) {
err = buf.WriteByte(b)
})
return
}
func (w *Writer) WriteString(s string) (n int, err error) {
w.P(func(buf *pbuf.Buffer) {
n, err = buf.WriteString(s)
})
return
}
func (w *Writer) WriteUInt16(v uint16) {
b := make([]byte, 2)
binary.LittleEndian.PutUint16(b, v)
w.Write(b)
}
func (w *Writer) WriteUInt32(v uint32) {
b := make([]byte, 4)
binary.LittleEndian.PutUint32(b, v)
w.Write(b)
}
func (w *Writer) WriteUInt64(v uint64) {
b := make([]byte, 8)
binary.LittleEndian.PutUint64(b, v)
w.Write(b)
}
func (w *Writer) ToBytes() pbuf.Bytes {
return pbuf.BufferItemToBytes((*pbuf.OBuffer)(w))
}