Files
v2ray_simple/utils/pool.go
hahafool a1a15770d2 修订代码, 文档.
令tls随机证书的国别和组织等信息随机化,在证书文件不存在时不退出程序, 而是使用随机证书继续运行。
不再提供 现成的 证书。
2022-04-22 12:40:23 +08:00

111 lines
2.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package utils
import (
"bytes"
"sync"
)
var (
mtuPool sync.Pool //专门储存 长度为 MTU 的 []byte
// packetPool 专门储存 长度为 MaxPacketLen 的 []byte
//
// 参考对比: tcp默认是 16k范围是1k128k;
// 而 udp则最大还不到 64k (65535208);
// io.Copy 内部默认buffer大小为 32k;
// 总之 我们64k已经够了
packetPool sync.Pool
bufPool sync.Pool //储存 *bytes.Buffer
)
const (
//即 Maximum transmission unit, 参照的是 Ethernet v2 的MTU;
MTU int = 1500
//注意wifi信号MTU是 2304我们并未考虑wifi,主要是因为就算用wifi传, 早晚还是要经过以太网,除非两个wifi设备互传
// https://en.wikipedia.org/wiki/Maximum_transmission_unit
//本作设定的最大包 长度大小64k
MaxPacketLen = 64 * 1024
)
func init() {
mtuPool = sync.Pool{
New: func() interface{} {
return make([]byte, MTU)
},
}
packetPool = sync.Pool{
New: func() interface{} {
return make([]byte, MaxPacketLen)
},
}
bufPool = sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
},
}
}
//从Pool中获取一个 *bytes.Buffer
func GetBuf() *bytes.Buffer {
return bufPool.Get().(*bytes.Buffer)
}
//将 buf 放回 Pool
func PutBuf(buf *bytes.Buffer) {
buf.Reset()
bufPool.Put(buf)
}
//建议在 Read net.Conn 时, 使用 GetPacket函数 获取到足够大的 []byteMaxBufLen
func GetPacket() []byte {
return packetPool.Get().([]byte)
}
// 放回用 GetPacket 获取的 []byte
func PutPacket(bs []byte) {
c := cap(bs)
if c < MaxPacketLen {
if c >= MTU {
mtuPool.Put(bs[:MTU])
}
return
}
packetPool.Put(bs[:MaxPacketLen])
}
// 从Pool中获取一个 MTU 长度的 []byte
func GetMTU() []byte {
return mtuPool.Get().([]byte)
}
// 从pool中获取 []byte, 根据给出长度不同来源于的Pool会不同.
func GetBytes(size int) []byte {
if size <= MTU {
bs := mtuPool.Get().([]byte)
return bs[:size]
}
return GetPacket()[:size]
}
// 根据bs长度 选择放入各种pool中, 只有 cap(bs)>=MTU 才会被处理
func PutBytes(bs []byte) {
c := cap(bs)
if c < MTU {
return
} else if c < MaxPacketLen {
mtuPool.Put(bs[:MTU])
} else {
packetPool.Put(bs[:MaxPacketLen])
}
}