args.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  1. package fasthttp
  2. import (
  3. "bytes"
  4. "errors"
  5. "io"
  6. "iter"
  7. "sort"
  8. "sync"
  9. )
  10. const (
  11. argsNoValue = true
  12. argsHasValue = false
  13. )
  14. // AcquireArgs returns an empty Args object from the pool.
  15. //
  16. // The returned Args may be returned to the pool with ReleaseArgs
  17. // when no longer needed. This allows reducing GC load.
  18. func AcquireArgs() *Args {
  19. return argsPool.Get().(*Args)
  20. }
  21. // ReleaseArgs returns the object acquired via AcquireArgs to the pool.
  22. //
  23. // Do not access the released Args object, otherwise data races may occur.
  24. func ReleaseArgs(a *Args) {
  25. a.Reset()
  26. argsPool.Put(a)
  27. }
  28. var argsPool = &sync.Pool{
  29. New: func() any {
  30. return &Args{}
  31. },
  32. }
  33. // Args represents query arguments.
  34. //
  35. // It is forbidden copying Args instances. Create new instances instead
  36. // and use CopyTo().
  37. //
  38. // Args instance MUST NOT be used from concurrently running goroutines.
  39. type Args struct {
  40. noCopy noCopy
  41. args []argsKV
  42. buf []byte
  43. }
  44. type argsKV struct {
  45. key []byte
  46. value []byte
  47. noValue bool
  48. }
  49. // Reset clears query args.
  50. func (a *Args) Reset() {
  51. a.args = a.args[:0]
  52. }
  53. // CopyTo copies all args to dst.
  54. func (a *Args) CopyTo(dst *Args) {
  55. dst.args = copyArgs(dst.args, a.args)
  56. }
  57. // All returns an iterator over key-value pairs from args.
  58. //
  59. // The key and value may invalid outside the iteration loop.
  60. // Make copies if you need to use them after the loop ends.
  61. func (a *Args) All() iter.Seq2[[]byte, []byte] {
  62. return func(yield func([]byte, []byte) bool) {
  63. for i := range a.args {
  64. if !yield(a.args[i].key, a.args[i].value) {
  65. break
  66. }
  67. }
  68. }
  69. }
  70. // VisitAll calls f for each existing arg.
  71. //
  72. // f must not retain references to key and value after returning.
  73. // Make key and/or value copies if you need storing them after returning.
  74. //
  75. // Deprecated: Use All instead.
  76. func (a *Args) VisitAll(f func(key, value []byte)) {
  77. a.All()(func(key, value []byte) bool {
  78. f(key, value)
  79. return true
  80. })
  81. }
  82. // Len returns the number of query args.
  83. func (a *Args) Len() int {
  84. return len(a.args)
  85. }
  86. // Parse parses the given string containing query args.
  87. func (a *Args) Parse(s string) {
  88. a.buf = append(a.buf[:0], s...)
  89. a.ParseBytes(a.buf)
  90. }
  91. // ParseBytes parses the given b containing query args.
  92. func (a *Args) ParseBytes(b []byte) {
  93. a.Reset()
  94. var s argsScanner
  95. s.b = b
  96. var kv *argsKV
  97. a.args, kv = allocArg(a.args)
  98. for s.next(kv) {
  99. if len(kv.key) > 0 || len(kv.value) > 0 {
  100. a.args, kv = allocArg(a.args)
  101. }
  102. }
  103. a.args = releaseArg(a.args)
  104. }
  105. // String returns string representation of query args.
  106. func (a *Args) String() string {
  107. return string(a.QueryString())
  108. }
  109. // QueryString returns query string for the args.
  110. //
  111. // The returned value is valid until the Args is reused or released (ReleaseArgs).
  112. // Do not store references to the returned value. Make copies instead.
  113. func (a *Args) QueryString() []byte {
  114. a.buf = a.AppendBytes(a.buf[:0])
  115. return a.buf
  116. }
  117. // Sort sorts Args by key and then value using 'f' as comparison function.
  118. //
  119. // For example args.Sort(bytes.Compare).
  120. func (a *Args) Sort(f func(x, y []byte) int) {
  121. sort.SliceStable(a.args, func(i, j int) bool {
  122. n := f(a.args[i].key, a.args[j].key)
  123. if n == 0 {
  124. return f(a.args[i].value, a.args[j].value) == -1
  125. }
  126. return n == -1
  127. })
  128. }
  129. // AppendBytes appends query string to dst and returns the extended dst.
  130. func (a *Args) AppendBytes(dst []byte) []byte {
  131. for i, n := 0, len(a.args); i < n; i++ {
  132. kv := &a.args[i]
  133. dst = AppendQuotedArg(dst, kv.key)
  134. if !kv.noValue {
  135. dst = append(dst, '=')
  136. if len(kv.value) > 0 {
  137. dst = AppendQuotedArg(dst, kv.value)
  138. }
  139. }
  140. if i+1 < n {
  141. dst = append(dst, '&')
  142. }
  143. }
  144. return dst
  145. }
  146. // WriteTo writes query string to w.
  147. //
  148. // WriteTo implements io.WriterTo interface.
  149. func (a *Args) WriteTo(w io.Writer) (int64, error) {
  150. n, err := w.Write(a.QueryString())
  151. return int64(n), err
  152. }
  153. // Del deletes argument with the given key from query args.
  154. func (a *Args) Del(key string) {
  155. a.args = delAllArgsStable(a.args, key)
  156. }
  157. // DelBytes deletes argument with the given key from query args.
  158. func (a *Args) DelBytes(key []byte) {
  159. a.args = delAllArgsStable(a.args, b2s(key))
  160. }
  161. // Add adds 'key=value' argument.
  162. //
  163. // Multiple values for the same key may be added.
  164. func (a *Args) Add(key, value string) {
  165. a.args = appendArg(a.args, key, value, argsHasValue)
  166. }
  167. // AddBytesK adds 'key=value' argument.
  168. //
  169. // Multiple values for the same key may be added.
  170. func (a *Args) AddBytesK(key []byte, value string) {
  171. a.args = appendArg(a.args, b2s(key), value, argsHasValue)
  172. }
  173. // AddBytesV adds 'key=value' argument.
  174. //
  175. // Multiple values for the same key may be added.
  176. func (a *Args) AddBytesV(key string, value []byte) {
  177. a.args = appendArg(a.args, key, b2s(value), argsHasValue)
  178. }
  179. // AddBytesKV adds 'key=value' argument.
  180. //
  181. // Multiple values for the same key may be added.
  182. func (a *Args) AddBytesKV(key, value []byte) {
  183. a.args = appendArg(a.args, b2s(key), b2s(value), argsHasValue)
  184. }
  185. // AddNoValue adds only 'key' as argument without the '='.
  186. //
  187. // Multiple values for the same key may be added.
  188. func (a *Args) AddNoValue(key string) {
  189. a.args = appendArg(a.args, key, "", argsNoValue)
  190. }
  191. // AddBytesKNoValue adds only 'key' as argument without the '='.
  192. //
  193. // Multiple values for the same key may be added.
  194. func (a *Args) AddBytesKNoValue(key []byte) {
  195. a.args = appendArg(a.args, b2s(key), "", argsNoValue)
  196. }
  197. // Set sets 'key=value' argument.
  198. func (a *Args) Set(key, value string) {
  199. a.args = setArg(a.args, key, value, argsHasValue)
  200. }
  201. // SetBytesK sets 'key=value' argument.
  202. func (a *Args) SetBytesK(key []byte, value string) {
  203. a.args = setArg(a.args, b2s(key), value, argsHasValue)
  204. }
  205. // SetBytesV sets 'key=value' argument.
  206. func (a *Args) SetBytesV(key string, value []byte) {
  207. a.args = setArg(a.args, key, b2s(value), argsHasValue)
  208. }
  209. // SetBytesKV sets 'key=value' argument.
  210. func (a *Args) SetBytesKV(key, value []byte) {
  211. a.args = setArgBytes(a.args, key, value, argsHasValue)
  212. }
  213. // SetNoValue sets only 'key' as argument without the '='.
  214. //
  215. // Only key in argument, like key1&key2.
  216. func (a *Args) SetNoValue(key string) {
  217. a.args = setArg(a.args, key, "", argsNoValue)
  218. }
  219. // SetBytesKNoValue sets 'key' argument.
  220. func (a *Args) SetBytesKNoValue(key []byte) {
  221. a.args = setArg(a.args, b2s(key), "", argsNoValue)
  222. }
  223. // Peek returns query arg value for the given key.
  224. //
  225. // The returned value is valid until the Args is reused or released (ReleaseArgs).
  226. // Do not store references to the returned value. Make copies instead.
  227. func (a *Args) Peek(key string) []byte {
  228. return peekArgStr(a.args, key)
  229. }
  230. // PeekBytes returns query arg value for the given key.
  231. //
  232. // The returned value is valid until the Args is reused or released (ReleaseArgs).
  233. // Do not store references to the returned value. Make copies instead.
  234. func (a *Args) PeekBytes(key []byte) []byte {
  235. return peekArgBytes(a.args, key)
  236. }
  237. // PeekMulti returns all the arg values for the given key.
  238. func (a *Args) PeekMulti(key string) [][]byte {
  239. var values [][]byte
  240. for k, v := range a.All() {
  241. if string(k) == key {
  242. values = append(values, v)
  243. }
  244. }
  245. return values
  246. }
  247. // PeekMultiBytes returns all the arg values for the given key.
  248. func (a *Args) PeekMultiBytes(key []byte) [][]byte {
  249. return a.PeekMulti(b2s(key))
  250. }
  251. // Has returns true if the given key exists in Args.
  252. func (a *Args) Has(key string) bool {
  253. return hasArg(a.args, key)
  254. }
  255. // HasBytes returns true if the given key exists in Args.
  256. func (a *Args) HasBytes(key []byte) bool {
  257. return hasArg(a.args, b2s(key))
  258. }
  259. // ErrNoArgValue is returned when Args value with the given key is missing.
  260. var ErrNoArgValue = errors.New("no Args value for the given key")
  261. // GetUint returns uint value for the given key.
  262. func (a *Args) GetUint(key string) (int, error) {
  263. value := a.Peek(key)
  264. if len(value) == 0 {
  265. return -1, ErrNoArgValue
  266. }
  267. return ParseUint(value)
  268. }
  269. // SetUint sets uint value for the given key.
  270. func (a *Args) SetUint(key string, value int) {
  271. a.buf = AppendUint(a.buf[:0], value)
  272. a.SetBytesV(key, a.buf)
  273. }
  274. // SetUintBytes sets uint value for the given key.
  275. func (a *Args) SetUintBytes(key []byte, value int) {
  276. a.SetUint(b2s(key), value)
  277. }
  278. // GetUintOrZero returns uint value for the given key.
  279. //
  280. // Zero (0) is returned on error.
  281. func (a *Args) GetUintOrZero(key string) int {
  282. n, err := a.GetUint(key)
  283. if err != nil {
  284. n = 0
  285. }
  286. return n
  287. }
  288. // GetUfloat returns ufloat value for the given key.
  289. func (a *Args) GetUfloat(key string) (float64, error) {
  290. value := a.Peek(key)
  291. if len(value) == 0 {
  292. return -1, ErrNoArgValue
  293. }
  294. return ParseUfloat(value)
  295. }
  296. // GetUfloatOrZero returns ufloat value for the given key.
  297. //
  298. // Zero (0) is returned on error.
  299. func (a *Args) GetUfloatOrZero(key string) float64 {
  300. f, err := a.GetUfloat(key)
  301. if err != nil {
  302. f = 0
  303. }
  304. return f
  305. }
  306. // GetBool returns boolean value for the given key.
  307. //
  308. // true is returned for "1", "t", "T", "true", "TRUE", "True", "y", "yes", "Y", "YES", "Yes",
  309. // otherwise false is returned.
  310. func (a *Args) GetBool(key string) bool {
  311. switch string(a.Peek(key)) {
  312. // Support the same true cases as strconv.ParseBool
  313. // See: https://github.com/golang/go/blob/4e1b11e2c9bdb0ddea1141eed487be1a626ff5be/src/strconv/atob.go#L12
  314. // and Y and Yes versions.
  315. case "1", "t", "T", "true", "TRUE", "True", "y", "yes", "Y", "YES", "Yes":
  316. return true
  317. default:
  318. return false
  319. }
  320. }
  321. func copyArgs(dst, src []argsKV) []argsKV {
  322. if cap(dst) < len(src) {
  323. tmp := make([]argsKV, len(src))
  324. dstLen := len(dst)
  325. dst = dst[:cap(dst)] // copy all of dst.
  326. copy(tmp, dst)
  327. for i := dstLen; i < len(tmp); i++ {
  328. // Make sure nothing is nil.
  329. tmp[i].key = []byte{}
  330. tmp[i].value = []byte{}
  331. }
  332. dst = tmp
  333. }
  334. n := len(src)
  335. dst = dst[:n]
  336. for i := 0; i < n; i++ {
  337. dstKV := &dst[i]
  338. srcKV := &src[i]
  339. dstKV.key = append(dstKV.key[:0], srcKV.key...)
  340. if srcKV.noValue {
  341. dstKV.value = dstKV.value[:0]
  342. } else {
  343. dstKV.value = append(dstKV.value[:0], srcKV.value...)
  344. }
  345. dstKV.noValue = srcKV.noValue
  346. }
  347. return dst
  348. }
  349. func delAllArgsStable(args []argsKV, key string) []argsKV {
  350. for i, n := 0, len(args); i < n; i++ {
  351. kv := &args[i]
  352. if key == string(kv.key) {
  353. tmp := *kv
  354. copy(args[i:], args[i+1:])
  355. n--
  356. i--
  357. args[n] = tmp
  358. args = args[:n]
  359. }
  360. }
  361. return args
  362. }
  363. func delAllArgs(args []argsKV, key string) []argsKV {
  364. n := len(args)
  365. for i := 0; i < n; i++ {
  366. if key == string(args[i].key) {
  367. args[i], args[n-1] = args[n-1], args[i]
  368. n--
  369. i--
  370. }
  371. }
  372. return args[:n]
  373. }
  374. func setArgBytes(h []argsKV, key, value []byte, noValue bool) []argsKV {
  375. return setArg(h, b2s(key), b2s(value), noValue)
  376. }
  377. func setArg(h []argsKV, key, value string, noValue bool) []argsKV {
  378. n := len(h)
  379. for i := 0; i < n; i++ {
  380. kv := &h[i]
  381. if key == string(kv.key) {
  382. if noValue {
  383. kv.value = kv.value[:0]
  384. } else {
  385. kv.value = append(kv.value[:0], value...)
  386. }
  387. kv.noValue = noValue
  388. return h
  389. }
  390. }
  391. return appendArg(h, key, value, noValue)
  392. }
  393. func appendArgBytes(h []argsKV, key, value []byte, noValue bool) []argsKV {
  394. return appendArg(h, b2s(key), b2s(value), noValue)
  395. }
  396. func appendArg(args []argsKV, key, value string, noValue bool) []argsKV {
  397. var kv *argsKV
  398. args, kv = allocArg(args)
  399. kv.key = append(kv.key[:0], key...)
  400. if noValue {
  401. kv.value = kv.value[:0]
  402. } else {
  403. kv.value = append(kv.value[:0], value...)
  404. }
  405. kv.noValue = noValue
  406. return args
  407. }
  408. func allocArg(h []argsKV) ([]argsKV, *argsKV) {
  409. n := len(h)
  410. if cap(h) > n {
  411. h = h[:n+1]
  412. } else {
  413. h = append(h, argsKV{
  414. value: []byte{},
  415. })
  416. }
  417. return h, &h[n]
  418. }
  419. func releaseArg(h []argsKV) []argsKV {
  420. return h[:len(h)-1]
  421. }
  422. func hasArg(h []argsKV, key string) bool {
  423. for i, n := 0, len(h); i < n; i++ {
  424. kv := &h[i]
  425. if key == string(kv.key) {
  426. return true
  427. }
  428. }
  429. return false
  430. }
  431. func peekArgBytes(h []argsKV, k []byte) []byte {
  432. for i, n := 0, len(h); i < n; i++ {
  433. kv := &h[i]
  434. if bytes.Equal(kv.key, k) {
  435. return kv.value
  436. }
  437. }
  438. return nil
  439. }
  440. func peekArgStr(h []argsKV, k string) []byte {
  441. for i, n := 0, len(h); i < n; i++ {
  442. kv := &h[i]
  443. if string(kv.key) == k {
  444. return kv.value
  445. }
  446. }
  447. return nil
  448. }
  449. type argsScanner struct {
  450. b []byte
  451. }
  452. func (s *argsScanner) next(kv *argsKV) bool {
  453. if len(s.b) == 0 {
  454. return false
  455. }
  456. kv.noValue = argsHasValue
  457. isKey := true
  458. k := 0
  459. for i, c := range s.b {
  460. switch c {
  461. case '=':
  462. if isKey {
  463. isKey = false
  464. kv.key = decodeArgAppend(kv.key[:0], s.b[:i])
  465. k = i + 1
  466. }
  467. case '&':
  468. if isKey {
  469. kv.key = decodeArgAppend(kv.key[:0], s.b[:i])
  470. kv.value = kv.value[:0]
  471. kv.noValue = argsNoValue
  472. } else {
  473. kv.value = decodeArgAppend(kv.value[:0], s.b[k:i])
  474. }
  475. s.b = s.b[i+1:]
  476. return true
  477. }
  478. }
  479. if isKey {
  480. kv.key = decodeArgAppend(kv.key[:0], s.b)
  481. kv.value = kv.value[:0]
  482. kv.noValue = argsNoValue
  483. } else {
  484. kv.value = decodeArgAppend(kv.value[:0], s.b[k:])
  485. }
  486. s.b = s.b[len(s.b):]
  487. return true
  488. }
  489. func decodeArgAppend(dst, src []byte) []byte {
  490. idxPercent := bytes.IndexByte(src, '%')
  491. idxPlus := bytes.IndexByte(src, '+')
  492. if idxPercent == -1 && idxPlus == -1 {
  493. // fast path: src doesn't contain encoded chars
  494. return append(dst, src...)
  495. }
  496. var idx int
  497. switch {
  498. case idxPercent == -1:
  499. idx = idxPlus
  500. case idxPlus == -1:
  501. idx = idxPercent
  502. case idxPercent > idxPlus:
  503. idx = idxPlus
  504. default:
  505. idx = idxPercent
  506. }
  507. dst = append(dst, src[:idx]...)
  508. // slow path
  509. for i := idx; i < len(src); i++ {
  510. c := src[i]
  511. switch c {
  512. case '%':
  513. if i+2 >= len(src) {
  514. return append(dst, src[i:]...)
  515. }
  516. x2 := hex2intTable[src[i+2]]
  517. x1 := hex2intTable[src[i+1]]
  518. if x1 == 16 || x2 == 16 {
  519. dst = append(dst, '%')
  520. } else {
  521. dst = append(dst, x1<<4|x2)
  522. i += 2
  523. }
  524. case '+':
  525. dst = append(dst, ' ')
  526. default:
  527. dst = append(dst, c)
  528. }
  529. }
  530. return dst
  531. }
  532. // decodeArgAppendNoPlus is almost identical to decodeArgAppend, but it doesn't
  533. // substitute '+' with ' '.
  534. //
  535. // The function is copy-pasted from decodeArgAppend due to the performance
  536. // reasons only.
  537. func decodeArgAppendNoPlus(dst, src []byte) []byte {
  538. idx := bytes.IndexByte(src, '%')
  539. if idx < 0 {
  540. // fast path: src doesn't contain encoded chars
  541. return append(dst, src...)
  542. }
  543. dst = append(dst, src[:idx]...)
  544. // slow path
  545. for i := idx; i < len(src); i++ {
  546. c := src[i]
  547. if c == '%' {
  548. if i+2 >= len(src) {
  549. return append(dst, src[i:]...)
  550. }
  551. x2 := hex2intTable[src[i+2]]
  552. x1 := hex2intTable[src[i+1]]
  553. if x1 == 16 || x2 == 16 {
  554. dst = append(dst, '%')
  555. } else {
  556. dst = append(dst, x1<<4|x2)
  557. i += 2
  558. }
  559. } else {
  560. dst = append(dst, c)
  561. }
  562. }
  563. return dst
  564. }
  565. func peekAllArgBytesToDst(dst [][]byte, h []argsKV, k []byte) [][]byte {
  566. for i, n := 0, len(h); i < n; i++ {
  567. kv := &h[i]
  568. if bytes.Equal(kv.key, k) {
  569. dst = append(dst, kv.value)
  570. }
  571. }
  572. return dst
  573. }