Created
July 24, 2019 07:29
-
-
Save acidsound/d1f8b6cbe9608a954f97bae6395100b8 to your computer and use it in GitHub Desktop.
gencode example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io" | |
"time" | |
"unsafe" | |
) | |
var ( | |
_ = unsafe.Sizeof(0) | |
_ = io.ReadFull | |
_ = time.Now() | |
) | |
type Pubsub struct { | |
isSubscribe bool | |
topic string | |
payload []byte | |
} | |
func (d *Pubsub) Size() (s uint64) { | |
{ | |
l := uint64(len(d.topic)) | |
{ | |
t := l | |
for t >= 0x80 { | |
t >>= 7 | |
s++ | |
} | |
s++ | |
} | |
s += l | |
} | |
{ | |
l := uint64(len(d.payload)) | |
{ | |
t := l | |
for t >= 0x80 { | |
t >>= 7 | |
s++ | |
} | |
s++ | |
} | |
s += l | |
} | |
s += 1 | |
return | |
} | |
func (d *Pubsub) Marshal(buf []byte) ([]byte, error) { | |
size := d.Size() | |
{ | |
if uint64(cap(buf)) >= size { | |
buf = buf[:size] | |
} else { | |
buf = make([]byte, size) | |
} | |
} | |
i := uint64(0) | |
{ | |
if d.isSubscribe { | |
buf[0] = 1 | |
} else { | |
buf[0] = 0 | |
} | |
} | |
{ | |
l := uint64(len(d.topic)) | |
{ | |
t := uint64(l) | |
for t >= 0x80 { | |
buf[i+1] = byte(t) | 0x80 | |
t >>= 7 | |
i++ | |
} | |
buf[i+1] = byte(t) | |
i++ | |
} | |
copy(buf[i+1:], d.topic) | |
i += l | |
} | |
{ | |
l := uint64(len(d.payload)) | |
{ | |
t := uint64(l) | |
for t >= 0x80 { | |
buf[i+1] = byte(t) | 0x80 | |
t >>= 7 | |
i++ | |
} | |
buf[i+1] = byte(t) | |
i++ | |
} | |
copy(buf[i+1:], d.payload) | |
i += l | |
} | |
return buf[:i+1], nil | |
} | |
func (d *Pubsub) Unmarshal(buf []byte) (uint64, error) { | |
i := uint64(0) | |
{ | |
d.isSubscribe = buf[i+0] == 1 | |
} | |
{ | |
l := uint64(0) | |
{ | |
bs := uint8(7) | |
t := uint64(buf[i+1] & 0x7F) | |
for buf[i+1]&0x80 == 0x80 { | |
i++ | |
t |= uint64(buf[i+1]&0x7F) << bs | |
bs += 7 | |
} | |
i++ | |
l = t | |
} | |
d.topic = string(buf[i+1 : i+1+l]) | |
i += l | |
} | |
{ | |
l := uint64(0) | |
{ | |
bs := uint8(7) | |
t := uint64(buf[i+1] & 0x7F) | |
for buf[i+1]&0x80 == 0x80 { | |
i++ | |
t |= uint64(buf[i+1]&0x7F) << bs | |
bs += 7 | |
} | |
i++ | |
l = t | |
} | |
if uint64(cap(d.payload)) >= l { | |
d.payload = d.payload[:l] | |
} else { | |
d.payload = make([]byte, l) | |
} | |
copy(d.payload, buf[i+1:]) | |
i += l | |
} | |
return i + 1, nil | |
} | |
func main() { | |
pub:=Pubsub{isSubscribe:true, topic: "carLong/Lat", payload:[]byte("stringingingdingdong")} | |
buf, _ := pub.Marshal(nil) | |
fmt.Println(pub.Size(), buf) | |
newPub :=Pubsub{} | |
newPub.Unmarshal(buf) | |
fmt.Println(newPub) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment