buffer.go 5.8 KB

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