buffer.go 6.9 KB

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