args.go 14 KB

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