diff options
Diffstat (limited to 'msg.go')
-rw-r--r-- | msg.go | 27 |
1 files changed, 21 insertions, 6 deletions
@@ -7,7 +7,10 @@ import "runtime" // The C pointer type for a Msg object type CMsg = *C.msg_t -type msg struct { inner CMsg } +type msg struct { + inner CMsg + autoFree bool +} // Message sent by MsgNetwork type Msg = *msg @@ -18,16 +21,28 @@ type Msg = *msg // "FromC" functions. func MsgFromC(ptr *C.msg_t) Msg { return &msg{ inner: ptr } } +func msgSetFinalizer(res Msg, autoFree bool) { + res.autoFree = autoFree + if res != nil && autoFree { + runtime.SetFinalizer(res, func(self Msg) { self.Free() }) + } +} + // Create a message by taking out all data from src. Notice this is a zero-copy // operation that consumes and invalidates the data in src ("move" semantics) // so that no more operation should be done to src after this function call. -func NewMsgMovedFromByteArray(opcode Opcode, src ByteArray) Msg { - res := &msg{ inner: C.msg_new_moved_from_bytearray(C._opcode_t(opcode), src.inner) } - runtime.SetFinalizer(res, func(self Msg) { self.free() }) +func NewMsgMovedFromByteArray(opcode Opcode, src ByteArray, autoFree bool) Msg { + res := MsgFromC(C.msg_new_moved_from_bytearray(C._opcode_t(opcode), src.inner)) + msgSetFinalizer(res, autoFree) return res } -func (self Msg) free() { C.msg_free(self.inner) } +func (self Msg) Free() { + C.msg_free(self.inner) + if self.autoFree { + runtime.SetFinalizer(self, nil) + } +} // Get the message payload by taking out all data. Notice this is a zero-copy // operation that consumes and invalidates the data in the payload ("move" @@ -35,7 +50,7 @@ func (self Msg) free() { C.msg_free(self.inner) } // this function call. func (self Msg) GetPayloadByMove() DataStream { res := DataStreamFromC(C.msg_consume_payload(self.inner)) - runtime.SetFinalizer(res, func(self DataStream) { self.free() }) + runtime.SetFinalizer(res, func(self DataStream) { self.Free() }) return res } |