From 7e959294274af78c99eb2c87b5df8d12cba156a2 Mon Sep 17 00:00:00 2001 From: Redmomn <109732988+Redmomn@users.noreply.github.com> Date: Fri, 28 Jun 2024 18:23:08 +0800 Subject: [PATCH] feat: add writer func --- utils/binary/builder.go | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/utils/binary/builder.go b/utils/binary/builder.go index 8076d755..883135ab 100644 --- a/utils/binary/builder.go +++ b/utils/binary/builder.go @@ -25,6 +25,36 @@ type Builder struct { io.ReaderFrom } +// NewWriterF from https://github.com/Mrs4s/MiraiGo/blob/master/binary/writer.go +func NewWriterF(f func(writer *Builder)) []byte { + w := SelectBuilder(nil) + f(w) + b := make([]byte, w.Len()) + copy(b, w.ToBytes()) + w.put() + return b +} + +// OpenWriterF must call func cl to close from https://github.com/Mrs4s/MiraiGo/blob/master/binary/writer.go +func OpenWriterF(f func(builder *Builder)) (b []byte, cl func()) { + w := SelectBuilder(nil) + f(w) + return w.ToBytes(), w.put +} + +// ToBytes from https://github.com/Mrs4s/MiraiGo/blob/master/binary/writer.go +func ToBytes(i any) []byte { + return NewWriterF(func(w *Builder) { + // TODO: more types + switch t := i.(type) { + case int16: + w.WriteU16(uint16(t)) + case int32: + w.WriteU32(uint32(t)) + } + }) +} + // NewBuilder with finalizer of itself. // // Be sure to use all data before builder is GCed.