mirror of
https://github.com/xjasonlyu/tun2socks.git
synced 2025-10-07 17:51:16 +08:00
fix buffer pool
This commit is contained in:
23
core/buffer_pool.go
Normal file
23
core/buffer_pool.go
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
package core
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
const defaultBufferSize = 2 * 1024
|
||||||
|
|
||||||
|
var bufPool = sync.Pool{New: func() interface{} { return make([]byte, defaultBufferSize) }}
|
||||||
|
|
||||||
|
func newBytes(size int) []byte {
|
||||||
|
if size <= defaultBufferSize {
|
||||||
|
return bufPool.Get().([]byte)
|
||||||
|
} else {
|
||||||
|
return make([]byte, size)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func freeBytes(b []byte) {
|
||||||
|
if len(b) >= defaultBufferSize {
|
||||||
|
bufPool.Put(b)
|
||||||
|
}
|
||||||
|
}
|
@@ -19,10 +19,10 @@ func output(p *C.struct_pbuf) C.err_t {
|
|||||||
buf := (*[1 << 30]byte)(unsafe.Pointer(p.payload))[:totlen:totlen]
|
buf := (*[1 << 30]byte)(unsafe.Pointer(p.payload))[:totlen:totlen]
|
||||||
OutputFn(buf[:totlen])
|
OutputFn(buf[:totlen])
|
||||||
} else {
|
} else {
|
||||||
buf := NewBytes(totlen)
|
buf := newBytes(totlen)
|
||||||
C.pbuf_copy_partial(p, unsafe.Pointer(&buf[0]), p.tot_len, 0) // data copy here!
|
C.pbuf_copy_partial(p, unsafe.Pointer(&buf[0]), p.tot_len, 0) // data copy here!
|
||||||
OutputFn(buf[:totlen])
|
OutputFn(buf[:totlen])
|
||||||
FreeBytes(buf)
|
freeBytes(buf)
|
||||||
}
|
}
|
||||||
return C.ERR_OK
|
return C.ERR_OK
|
||||||
}
|
}
|
||||||
|
@@ -81,8 +81,8 @@ func tcpRecvFn(arg unsafe.Pointer, tpcb *C.struct_tcp_pcb, p *C.struct_pbuf, err
|
|||||||
if p.tot_len == p.len {
|
if p.tot_len == p.len {
|
||||||
buf = (*[1 << 30]byte)(unsafe.Pointer(p.payload))[:totlen:totlen]
|
buf = (*[1 << 30]byte)(unsafe.Pointer(p.payload))[:totlen:totlen]
|
||||||
} else {
|
} else {
|
||||||
buf = NewBytes(totlen)
|
buf = newBytes(totlen)
|
||||||
defer FreeBytes(buf)
|
defer freeBytes(buf)
|
||||||
C.pbuf_copy_partial(p, unsafe.Pointer(&buf[0]), p.tot_len, 0)
|
C.pbuf_copy_partial(p, unsafe.Pointer(&buf[0]), p.tot_len, 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -53,8 +53,8 @@ func udpRecvFn(arg unsafe.Pointer, pcb *C.struct_udp_pcb, p *C.struct_pbuf, addr
|
|||||||
if p.tot_len == p.len {
|
if p.tot_len == p.len {
|
||||||
buf = (*[1 << 30]byte)(unsafe.Pointer(p.payload))[:totlen:totlen]
|
buf = (*[1 << 30]byte)(unsafe.Pointer(p.payload))[:totlen:totlen]
|
||||||
} else {
|
} else {
|
||||||
buf = NewBytes(totlen)
|
buf = newBytes(totlen)
|
||||||
defer FreeBytes(buf)
|
defer freeBytes(buf)
|
||||||
C.pbuf_copy_partial(p, unsafe.Pointer(&buf[0]), p.tot_len, 0)
|
C.pbuf_copy_partial(p, unsafe.Pointer(&buf[0]), p.tot_len, 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user