buffer.go 6.2 KB

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