github.com/LagrangeDev/LagrangeGo@v0.0.0-20240512064304-ad4a85e10cb4/utils/binary/utils.go (about) 1 package binary 2 3 // from https://github.com/Mrs4s/MiraiGo/blob/master/binary/utils.go 4 5 import ( 6 "bytes" 7 "compress/gzip" 8 "compress/zlib" 9 "encoding/binary" 10 "net" 11 ) 12 13 type GzipWriter struct { 14 w *gzip.Writer 15 buf *bytes.Buffer 16 } 17 18 func (w *GzipWriter) Write(p []byte) (int, error) { 19 return w.w.Write(p) 20 } 21 22 func (w *GzipWriter) Close() error { 23 return w.w.Close() 24 } 25 26 func (w *GzipWriter) Bytes() []byte { 27 return w.buf.Bytes() 28 } 29 30 func ZlibUncompress(src []byte) []byte { 31 b := bytes.NewReader(src) 32 var out bytes.Buffer 33 r, _ := zlib.NewReader(b) 34 defer r.Close() 35 _, _ = out.ReadFrom(r) 36 return out.Bytes() 37 } 38 39 func ZlibCompress(data []byte) []byte { 40 zw := acquireZlibWriter() 41 _, _ = zw.w.Write(data) 42 _ = zw.w.Close() 43 ret := make([]byte, len(zw.buf.Bytes())) 44 copy(ret, zw.buf.Bytes()) 45 releaseZlibWriter(zw) 46 return ret 47 } 48 49 func GZipCompress(data []byte) []byte { 50 gw := AcquireGzipWriter() 51 _, _ = gw.Write(data) 52 _ = gw.Close() 53 ret := make([]byte, len(gw.buf.Bytes())) 54 copy(ret, gw.buf.Bytes()) 55 ReleaseGzipWriter(gw) 56 return ret 57 } 58 59 func GZipUncompress(src []byte) []byte { 60 b := bytes.NewReader(src) 61 var out bytes.Buffer 62 r, _ := gzip.NewReader(b) 63 defer r.Close() 64 _, _ = out.ReadFrom(r) 65 return out.Bytes() 66 } 67 68 func UInt32ToIPV4Address(i uint32) string { 69 ip := net.IP{0, 0, 0, 0} 70 binary.LittleEndian.PutUint32(ip, i) 71 return ip.String() 72 }