userdata.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package fasthttp
  2. import (
  3. "io"
  4. )
  5. type userDataKV struct {
  6. key interface{}
  7. value interface{}
  8. }
  9. type userData []userDataKV
  10. func (d *userData) Set(key interface{}, value interface{}) {
  11. if b, ok := key.([]byte); ok {
  12. key = string(b)
  13. }
  14. args := *d
  15. n := len(args)
  16. for i := 0; i < n; i++ {
  17. kv := &args[i]
  18. if kv.key == key {
  19. kv.value = value
  20. return
  21. }
  22. }
  23. if value == nil {
  24. return
  25. }
  26. c := cap(args)
  27. if c > n {
  28. args = args[:n+1]
  29. kv := &args[n]
  30. kv.key = key
  31. kv.value = value
  32. *d = args
  33. return
  34. }
  35. kv := userDataKV{}
  36. kv.key = key
  37. kv.value = value
  38. args = append(args, kv)
  39. *d = args
  40. }
  41. func (d *userData) SetBytes(key []byte, value interface{}) {
  42. d.Set(key, value)
  43. }
  44. func (d *userData) Get(key interface{}) interface{} {
  45. if b, ok := key.([]byte); ok {
  46. key = b2s(b)
  47. }
  48. args := *d
  49. n := len(args)
  50. for i := 0; i < n; i++ {
  51. kv := &args[i]
  52. if kv.key == key {
  53. return kv.value
  54. }
  55. }
  56. return nil
  57. }
  58. func (d *userData) GetBytes(key []byte) interface{} {
  59. return d.Get(key)
  60. }
  61. func (d *userData) Reset() {
  62. args := *d
  63. n := len(args)
  64. for i := 0; i < n; i++ {
  65. v := args[i].value
  66. if vc, ok := v.(io.Closer); ok {
  67. vc.Close()
  68. }
  69. }
  70. *d = (*d)[:0]
  71. }
  72. func (d *userData) Remove(key interface{}) {
  73. if b, ok := key.([]byte); ok {
  74. key = b2s(b)
  75. }
  76. args := *d
  77. n := len(args)
  78. for i := 0; i < n; i++ {
  79. kv := &args[i]
  80. if kv.key == key {
  81. n--
  82. args[i], args[n] = args[n], args[i]
  83. args[n].value = nil
  84. args = args[:n]
  85. *d = args
  86. return
  87. }
  88. }
  89. }
  90. func (d *userData) RemoveBytes(key []byte) {
  91. d.Remove(key)
  92. }