buffer.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. package buf
  2. import (
  3. "io"
  4. "github.com/xtls/xray-core/common/bytespool"
  5. "github.com/xtls/xray-core/common/errors"
  6. "github.com/xtls/xray-core/common/net"
  7. )
  8. const (
  9. // Size of a regular buffer.
  10. Size = 8192
  11. )
  12. var zero = [Size * 10]byte{0}
  13. var pool = bytespool.GetPool(Size)
  14. // ownership represents the data owner of the buffer.
  15. type ownership uint8
  16. const (
  17. managed ownership = iota
  18. unmanaged
  19. bytespools
  20. )
  21. // Buffer is a recyclable allocation of a byte array. Buffer.Release() recycles
  22. // the buffer into an internal buffer pool, in order to recreate a buffer more
  23. // quickly.
  24. type Buffer struct {
  25. v []byte
  26. start int32
  27. end int32
  28. ownership ownership
  29. UDP *net.Destination
  30. }
  31. // New creates a Buffer with 0 length and 8K capacity, managed.
  32. func New() *Buffer {
  33. buf := pool.Get().([]byte)
  34. if cap(buf) >= Size {
  35. buf = buf[:Size]
  36. } else {
  37. buf = make([]byte, Size)
  38. }
  39. return &Buffer{
  40. v: buf,
  41. }
  42. }
  43. // NewExisted creates a standard size Buffer with an existed bytearray, managed.
  44. func NewExisted(b []byte) *Buffer {
  45. if cap(b) < Size {
  46. panic("Invalid buffer")
  47. }
  48. oLen := len(b)
  49. if oLen < Size {
  50. b = b[:Size]
  51. }
  52. return &Buffer{
  53. v: b,
  54. end: int32(oLen),
  55. }
  56. }
  57. // FromBytes creates a Buffer with an existed bytearray, unmanaged.
  58. func FromBytes(b []byte) *Buffer {
  59. return &Buffer{
  60. v: b,
  61. end: int32(len(b)),
  62. ownership: unmanaged,
  63. }
  64. }
  65. // StackNew creates a new Buffer object on stack, managed.
  66. // This method is for buffers that is released in the same function.
  67. func StackNew() Buffer {
  68. buf := pool.Get().([]byte)
  69. if cap(buf) >= Size {
  70. buf = buf[:Size]
  71. } else {
  72. buf = make([]byte, Size)
  73. }
  74. return Buffer{
  75. v: buf,
  76. }
  77. }
  78. // NewWithSize creates a Buffer with 0 length and capacity with at least the given size, bytespool's.
  79. func NewWithSize(size int32) *Buffer {
  80. return &Buffer{
  81. v: bytespool.Alloc(size),
  82. ownership: bytespools,
  83. }
  84. }
  85. // Release recycles the buffer into an internal buffer pool.
  86. func (b *Buffer) Release() {
  87. if b == nil || b.v == nil || b.ownership == unmanaged {
  88. return
  89. }
  90. p := b.v
  91. b.v = nil
  92. b.Clear()
  93. switch b.ownership {
  94. case managed:
  95. if cap(p) == Size {
  96. pool.Put(p)
  97. }
  98. case bytespools:
  99. bytespool.Free(p)
  100. }
  101. b.UDP = nil
  102. }
  103. // Clear clears the content of the buffer, results an empty buffer with
  104. // Len() = 0.
  105. func (b *Buffer) Clear() {
  106. b.start = 0
  107. b.end = 0
  108. }
  109. // Byte returns the bytes at index.
  110. func (b *Buffer) Byte(index int32) byte {
  111. return b.v[b.start+index]
  112. }
  113. // SetByte sets the byte value at index.
  114. func (b *Buffer) SetByte(index int32, value byte) {
  115. b.v[b.start+index] = value
  116. }
  117. // Bytes returns the content bytes of this Buffer.
  118. func (b *Buffer) Bytes() []byte {
  119. return b.v[b.start:b.end]
  120. }
  121. // Extend increases the buffer size by n bytes, and returns the extended part.
  122. // It panics if result size is larger than buf.Size.
  123. func (b *Buffer) Extend(n int32) []byte {
  124. end := b.end + n
  125. if end > int32(len(b.v)) {
  126. panic("extending out of bound")
  127. }
  128. ext := b.v[b.end:end]
  129. b.end = end
  130. copy(ext, zero[:])
  131. return ext
  132. }
  133. // BytesRange returns a slice of this buffer with given from and to boundary.
  134. func (b *Buffer) BytesRange(from, to int32) []byte {
  135. if from < 0 {
  136. from += b.Len()
  137. }
  138. if to < 0 {
  139. to += b.Len()
  140. }
  141. return b.v[b.start+from : b.start+to]
  142. }
  143. // BytesFrom returns a slice of this Buffer starting from the given position.
  144. func (b *Buffer) BytesFrom(from int32) []byte {
  145. if from < 0 {
  146. from += b.Len()
  147. }
  148. return b.v[b.start+from : b.end]
  149. }
  150. // BytesTo returns a slice of this Buffer from start to the given position.
  151. func (b *Buffer) BytesTo(to int32) []byte {
  152. if to < 0 {
  153. to += b.Len()
  154. }
  155. if to < 0 {
  156. to = 0
  157. }
  158. return b.v[b.start : b.start+to]
  159. }
  160. // Check makes sure that 0 <= b.start <= b.end.
  161. func (b *Buffer) Check() {
  162. if b.start < 0 {
  163. b.start = 0
  164. }
  165. if b.end < 0 {
  166. b.end = 0
  167. }
  168. if b.start > b.end {
  169. b.start = b.end
  170. }
  171. }
  172. // Resize cuts the buffer at the given position.
  173. func (b *Buffer) Resize(from, to int32) {
  174. oldEnd := b.end
  175. if from < 0 {
  176. from += b.Len()
  177. }
  178. if to < 0 {
  179. to += b.Len()
  180. }
  181. if to < from {
  182. panic("Invalid slice")
  183. }
  184. b.end = b.start + to
  185. b.start += from
  186. b.Check()
  187. if b.end > oldEnd {
  188. copy(b.v[oldEnd:b.end], zero[:])
  189. }
  190. }
  191. // Advance cuts the buffer at the given position.
  192. func (b *Buffer) Advance(from int32) {
  193. if from < 0 {
  194. from += b.Len()
  195. }
  196. b.start += from
  197. b.Check()
  198. }
  199. // Len returns the length of the buffer content.
  200. func (b *Buffer) Len() int32 {
  201. if b == nil {
  202. return 0
  203. }
  204. return b.end - b.start
  205. }
  206. // Cap returns the capacity of the buffer content.
  207. func (b *Buffer) Cap() int32 {
  208. if b == nil {
  209. return 0
  210. }
  211. return int32(len(b.v))
  212. }
  213. // IsEmpty returns true if the buffer is empty.
  214. func (b *Buffer) IsEmpty() bool {
  215. return b.Len() == 0
  216. }
  217. // IsFull returns true if the buffer has no more room to grow.
  218. func (b *Buffer) IsFull() bool {
  219. return b != nil && b.end == int32(len(b.v))
  220. }
  221. // Write implements Write method in io.Writer.
  222. func (b *Buffer) Write(data []byte) (int, error) {
  223. nBytes := copy(b.v[b.end:], data)
  224. b.end += int32(nBytes)
  225. return nBytes, nil
  226. }
  227. // WriteByte writes a single byte into the buffer.
  228. func (b *Buffer) WriteByte(v byte) error {
  229. if b.IsFull() {
  230. return errors.New("buffer full")
  231. }
  232. b.v[b.end] = v
  233. b.end++
  234. return nil
  235. }
  236. // WriteString implements io.StringWriter.
  237. func (b *Buffer) WriteString(s string) (int, error) {
  238. return b.Write([]byte(s))
  239. }
  240. // ReadByte implements io.ByteReader
  241. func (b *Buffer) ReadByte() (byte, error) {
  242. if b.start == b.end {
  243. return 0, io.EOF
  244. }
  245. nb := b.v[b.start]
  246. b.start++
  247. return nb, nil
  248. }
  249. // ReadBytes implements bufio.Reader.ReadBytes
  250. func (b *Buffer) ReadBytes(length int32) ([]byte, error) {
  251. if b.end-b.start < length {
  252. return nil, io.EOF
  253. }
  254. nb := b.v[b.start : b.start+length]
  255. b.start += length
  256. return nb, nil
  257. }
  258. // Read implements io.Reader.Read().
  259. func (b *Buffer) Read(data []byte) (int, error) {
  260. if b.Len() == 0 {
  261. return 0, io.EOF
  262. }
  263. nBytes := copy(data, b.v[b.start:b.end])
  264. if int32(nBytes) == b.Len() {
  265. b.Clear()
  266. } else {
  267. b.start += int32(nBytes)
  268. }
  269. return nBytes, nil
  270. }
  271. // ReadFrom implements io.ReaderFrom.
  272. func (b *Buffer) ReadFrom(reader io.Reader) (int64, error) {
  273. n, err := reader.Read(b.v[b.end:])
  274. b.end += int32(n)
  275. return int64(n), err
  276. }
  277. // ReadFullFrom reads exact size of bytes from given reader, or until error occurs.
  278. func (b *Buffer) ReadFullFrom(reader io.Reader, size int32) (int64, error) {
  279. end := b.end + size
  280. if end > int32(len(b.v)) {
  281. v := end
  282. return 0, errors.New("out of bound: ", v)
  283. }
  284. n, err := io.ReadFull(reader, b.v[b.end:end])
  285. b.end += int32(n)
  286. return int64(n), err
  287. }
  288. // String returns the string form of this Buffer.
  289. func (b *Buffer) String() string {
  290. return string(b.Bytes())
  291. }