Skip to content

Commit

Permalink
feat: add writer func
Browse files Browse the repository at this point in the history
  • Loading branch information
Redmomn committed Jun 28, 2024
1 parent be848f1 commit 7e95929
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions utils/binary/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down

0 comments on commit 7e95929

Please sign in to comment.