resp.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323
  1. // Package resp2 implements the original redis RESP protocol, a plaintext
  2. // protocol which is also binary safe. Redis uses the RESP protocol to
  3. // communicate with its clients, but there's nothing about the protocol which
  4. // ties it to redis, it could be used for almost anything.
  5. //
  6. // See https://redis.io/topics/protocol for more details on the protocol.
  7. package resp2
  8. import (
  9. "bufio"
  10. "bytes"
  11. "encoding"
  12. "fmt"
  13. "io"
  14. "reflect"
  15. "strconv"
  16. "sync"
  17. "errors"
  18. "github.com/mediocregopher/radix/v3/internal/bytesutil"
  19. "github.com/mediocregopher/radix/v3/resp"
  20. )
  21. var delim = []byte{'\r', '\n'}
  22. // prefix enumerates the possible RESP types by enumerating the different
  23. // prefixes a RESP message might start with.
  24. type prefix []byte
  25. // Enumeration of each of RESP's message types, each denoted by the prefix which
  26. // is prepended to messages of that type.
  27. //
  28. // In order to determine the type of a message which is being written to a
  29. // *bufio.Reader, without actually consuming it, one can use the Peek method and
  30. // compare it against these values.
  31. var (
  32. SimpleStringPrefix = []byte{'+'}
  33. ErrorPrefix = []byte{'-'}
  34. IntPrefix = []byte{':'}
  35. BulkStringPrefix = []byte{'$'}
  36. ArrayPrefix = []byte{'*'}
  37. )
  38. // String formats a prefix into a human-readable name for the type it denotes.
  39. func (p prefix) String() string {
  40. pStr := string(p)
  41. switch pStr {
  42. case string(SimpleStringPrefix):
  43. return "simple-string"
  44. case string(ErrorPrefix):
  45. return "error"
  46. case string(IntPrefix):
  47. return "integer"
  48. case string(BulkStringPrefix):
  49. return "bulk-string"
  50. case string(ArrayPrefix):
  51. return "array"
  52. default:
  53. return pStr
  54. }
  55. }
  56. var (
  57. nilBulkString = []byte("$-1\r\n")
  58. nilArray = []byte("*-1\r\n")
  59. emptyArray = []byte("*0\r\n")
  60. )
  61. var bools = [][]byte{
  62. {'0'},
  63. {'1'},
  64. }
  65. ////////////////////////////////////////////////////////////////////////////////
  66. type errUnexpectedPrefix struct {
  67. Prefix []byte
  68. ExpectedPrefix []byte
  69. }
  70. func (e errUnexpectedPrefix) Error() string {
  71. return fmt.Sprintf(
  72. "expected prefix %q, got %q",
  73. prefix(e.ExpectedPrefix).String(),
  74. prefix(e.Prefix).String(),
  75. )
  76. }
  77. // peekAndAssertPrefix will peek at the next incoming redis message and assert
  78. // that it is of the type identified by the given RESP prefix (see the resp2
  79. // package for possible prefices).
  80. //
  81. // If the message is a RESP error (and that wasn't the intended prefix) then it
  82. // will be unmarshaled into a resp2.Error and returned. If the message is of any
  83. // other type (that isn't the intended prefix) it will be discarded and
  84. // errUnexpectedPrefix will be returned.
  85. func peekAndAssertPrefix(br *bufio.Reader, expectedPrefix []byte) error {
  86. b, err := br.Peek(len(expectedPrefix))
  87. if err != nil {
  88. return err
  89. } else if bytes.Equal(b, expectedPrefix) {
  90. return nil
  91. } else if bytes.Equal(b, ErrorPrefix) {
  92. var respErr Error
  93. if err := respErr.UnmarshalRESP(br); err != nil {
  94. return err
  95. }
  96. return resp.ErrDiscarded{Err: respErr}
  97. } else if err := (Any{}).UnmarshalRESP(br); err != nil {
  98. return err
  99. }
  100. return resp.ErrDiscarded{Err: errUnexpectedPrefix{
  101. Prefix: b,
  102. ExpectedPrefix: expectedPrefix,
  103. }}
  104. }
  105. // like peekAndAssertPrefix, but will consume the prefix if it is the correct
  106. // one as well.
  107. func assertBufferedPrefix(br *bufio.Reader, pref []byte) error {
  108. if err := peekAndAssertPrefix(br, pref); err != nil {
  109. return err
  110. }
  111. _, err := br.Discard(len(pref))
  112. return err
  113. }
  114. ////////////////////////////////////////////////////////////////////////////////
  115. // SimpleString represents the simple string type in the RESP protocol.
  116. type SimpleString struct {
  117. S string
  118. }
  119. // MarshalRESP implements the Marshaler method.
  120. func (ss SimpleString) MarshalRESP(w io.Writer) error {
  121. scratch := bytesutil.GetBytes()
  122. *scratch = append(*scratch, SimpleStringPrefix...)
  123. *scratch = append(*scratch, ss.S...)
  124. *scratch = append(*scratch, delim...)
  125. _, err := w.Write(*scratch)
  126. bytesutil.PutBytes(scratch)
  127. return err
  128. }
  129. // UnmarshalRESP implements the Unmarshaler method.
  130. func (ss *SimpleString) UnmarshalRESP(br *bufio.Reader) error {
  131. if err := assertBufferedPrefix(br, SimpleStringPrefix); err != nil {
  132. return err
  133. }
  134. b, err := bytesutil.BufferedBytesDelim(br)
  135. if err != nil {
  136. return err
  137. }
  138. ss.S = string(b)
  139. return nil
  140. }
  141. ////////////////////////////////////////////////////////////////////////////////
  142. // Error represents an error type in the RESP protocol. Note that this only
  143. // represents an actual error message being read/written on the stream, it is
  144. // separate from network or parsing errors. An E value of nil is equivalent to
  145. // an empty error string.
  146. type Error struct {
  147. E error
  148. }
  149. func (e Error) Error() string {
  150. return e.E.Error()
  151. }
  152. // MarshalRESP implements the Marshaler method.
  153. func (e Error) MarshalRESP(w io.Writer) error {
  154. scratch := bytesutil.GetBytes()
  155. *scratch = append(*scratch, ErrorPrefix...)
  156. if e.E != nil {
  157. *scratch = append(*scratch, e.E.Error()...)
  158. }
  159. *scratch = append(*scratch, delim...)
  160. _, err := w.Write(*scratch)
  161. bytesutil.PutBytes(scratch)
  162. return err
  163. }
  164. // UnmarshalRESP implements the Unmarshaler method.
  165. func (e *Error) UnmarshalRESP(br *bufio.Reader) error {
  166. if err := assertBufferedPrefix(br, ErrorPrefix); err != nil {
  167. return err
  168. }
  169. b, err := bytesutil.BufferedBytesDelim(br)
  170. e.E = errors.New(string(b))
  171. return err
  172. }
  173. // As implements the method for the (x)errors.As function.
  174. func (e Error) As(target interface{}) bool {
  175. switch targetT := target.(type) {
  176. case *resp.ErrDiscarded:
  177. targetT.Err = e
  178. return true
  179. default:
  180. return false
  181. }
  182. }
  183. ////////////////////////////////////////////////////////////////////////////////
  184. // Int represents an int type in the RESP protocol.
  185. type Int struct {
  186. I int64
  187. }
  188. // MarshalRESP implements the Marshaler method.
  189. func (i Int) MarshalRESP(w io.Writer) error {
  190. scratch := bytesutil.GetBytes()
  191. *scratch = append(*scratch, IntPrefix...)
  192. *scratch = strconv.AppendInt(*scratch, i.I, 10)
  193. *scratch = append(*scratch, delim...)
  194. _, err := w.Write(*scratch)
  195. bytesutil.PutBytes(scratch)
  196. return err
  197. }
  198. // UnmarshalRESP implements the Unmarshaler method.
  199. func (i *Int) UnmarshalRESP(br *bufio.Reader) error {
  200. if err := assertBufferedPrefix(br, IntPrefix); err != nil {
  201. return err
  202. }
  203. n, err := bytesutil.BufferedIntDelim(br)
  204. i.I = n
  205. return err
  206. }
  207. ////////////////////////////////////////////////////////////////////////////////
  208. // BulkStringBytes represents the bulk string type in the RESP protocol using a
  209. // go byte slice. A B value of nil indicates the nil bulk string message, versus
  210. // a B value of []byte{} which indicates a bulk string of length 0.
  211. type BulkStringBytes struct {
  212. B []byte
  213. // If true then this won't marshal the nil RESP value when B is nil, it will
  214. // marshal as an empty string instead
  215. MarshalNotNil bool
  216. }
  217. // MarshalRESP implements the Marshaler method.
  218. func (b BulkStringBytes) MarshalRESP(w io.Writer) error {
  219. if b.B == nil && !b.MarshalNotNil {
  220. _, err := w.Write(nilBulkString)
  221. return err
  222. }
  223. scratch := bytesutil.GetBytes()
  224. *scratch = append(*scratch, BulkStringPrefix...)
  225. *scratch = strconv.AppendInt(*scratch, int64(len(b.B)), 10)
  226. *scratch = append(*scratch, delim...)
  227. *scratch = append(*scratch, b.B...)
  228. *scratch = append(*scratch, delim...)
  229. _, err := w.Write(*scratch)
  230. bytesutil.PutBytes(scratch)
  231. return err
  232. }
  233. // UnmarshalRESP implements the Unmarshaler method.
  234. func (b *BulkStringBytes) UnmarshalRESP(br *bufio.Reader) error {
  235. if err := assertBufferedPrefix(br, BulkStringPrefix); err != nil {
  236. return err
  237. }
  238. n, err := bytesutil.BufferedIntDelim(br)
  239. nn := int(n)
  240. if err != nil {
  241. return err
  242. } else if n == -1 {
  243. b.B = nil
  244. return nil
  245. } else {
  246. b.B = bytesutil.Expand(b.B, nn)
  247. if b.B == nil {
  248. b.B = []byte{}
  249. }
  250. }
  251. if _, err := io.ReadFull(br, b.B); err != nil {
  252. return err
  253. } else if _, err := bytesutil.BufferedBytesDelim(br); err != nil {
  254. return err
  255. }
  256. return nil
  257. }
  258. ////////////////////////////////////////////////////////////////////////////////
  259. // BulkString represents the bulk string type in the RESP protocol using a go
  260. // string.
  261. type BulkString struct {
  262. S string
  263. }
  264. // MarshalRESP implements the Marshaler method.
  265. func (b BulkString) MarshalRESP(w io.Writer) error {
  266. scratch := bytesutil.GetBytes()
  267. *scratch = append(*scratch, BulkStringPrefix...)
  268. *scratch = strconv.AppendInt(*scratch, int64(len(b.S)), 10)
  269. *scratch = append(*scratch, delim...)
  270. *scratch = append(*scratch, b.S...)
  271. *scratch = append(*scratch, delim...)
  272. _, err := w.Write(*scratch)
  273. bytesutil.PutBytes(scratch)
  274. return err
  275. }
  276. // UnmarshalRESP implements the Unmarshaler method. This treats a Nil bulk
  277. // string message as empty string.
  278. func (b *BulkString) UnmarshalRESP(br *bufio.Reader) error {
  279. if err := assertBufferedPrefix(br, BulkStringPrefix); err != nil {
  280. return err
  281. }
  282. n, err := bytesutil.BufferedIntDelim(br)
  283. if err != nil {
  284. return err
  285. } else if n == -1 {
  286. b.S = ""
  287. return nil
  288. }
  289. scratch := bytesutil.GetBytes()
  290. defer bytesutil.PutBytes(scratch)
  291. *scratch = bytesutil.Expand(*scratch, int(n))
  292. if _, err := io.ReadFull(br, *scratch); err != nil {
  293. return err
  294. } else if _, err := bytesutil.BufferedBytesDelim(br); err != nil {
  295. return err
  296. }
  297. b.S = string(*scratch)
  298. return nil
  299. }
  300. ////////////////////////////////////////////////////////////////////////////////
  301. // BulkReader is like BulkString, but it only supports marshalling and will use
  302. // the given LenReader to do so. If LR is nil then the nil bulk string RESP will
  303. // be written.
  304. type BulkReader struct {
  305. LR resp.LenReader
  306. }
  307. // MarshalRESP implements the Marshaler method.
  308. func (b BulkReader) MarshalRESP(w io.Writer) error {
  309. if b.LR == nil {
  310. _, err := w.Write(nilBulkString)
  311. return err
  312. }
  313. l := b.LR.Len()
  314. scratch := bytesutil.GetBytes()
  315. *scratch = append(*scratch, BulkStringPrefix...)
  316. *scratch = strconv.AppendInt(*scratch, l, 10)
  317. *scratch = append(*scratch, delim...)
  318. _, err := w.Write(*scratch)
  319. bytesutil.PutBytes(scratch)
  320. if err != nil {
  321. return err
  322. }
  323. if _, err := io.CopyN(w, b.LR, l); err != nil {
  324. return err
  325. } else if _, err := w.Write(delim); err != nil {
  326. return err
  327. }
  328. return nil
  329. }
  330. ////////////////////////////////////////////////////////////////////////////////
  331. // ArrayHeader represents the header sent preceding array elements in the RESP
  332. // protocol. It does not actually encompass any elements itself, it only
  333. // declares how many elements will come after it.
  334. //
  335. // An N of -1 may also be used to indicate a nil response, as per the RESP spec.
  336. type ArrayHeader struct {
  337. N int
  338. }
  339. // MarshalRESP implements the Marshaler method.
  340. func (ah ArrayHeader) MarshalRESP(w io.Writer) error {
  341. scratch := bytesutil.GetBytes()
  342. *scratch = append(*scratch, ArrayPrefix...)
  343. *scratch = strconv.AppendInt(*scratch, int64(ah.N), 10)
  344. *scratch = append(*scratch, delim...)
  345. _, err := w.Write(*scratch)
  346. bytesutil.PutBytes(scratch)
  347. return err
  348. }
  349. // UnmarshalRESP implements the Unmarshaler method.
  350. func (ah *ArrayHeader) UnmarshalRESP(br *bufio.Reader) error {
  351. if err := assertBufferedPrefix(br, ArrayPrefix); err != nil {
  352. return err
  353. }
  354. n, err := bytesutil.BufferedIntDelim(br)
  355. ah.N = int(n)
  356. return err
  357. }
  358. ////////////////////////////////////////////////////////////////////////////////
  359. // Array represents an array of RESP elements which will be marshaled as a RESP
  360. // array. If A is Nil then a Nil RESP will be marshaled.
  361. type Array struct {
  362. A []resp.Marshaler
  363. }
  364. // MarshalRESP implements the Marshaler method.
  365. func (a Array) MarshalRESP(w io.Writer) error {
  366. ah := ArrayHeader{N: len(a.A)}
  367. if a.A == nil {
  368. ah.N = -1
  369. }
  370. if err := ah.MarshalRESP(w); err != nil {
  371. return err
  372. }
  373. for _, el := range a.A {
  374. if err := el.MarshalRESP(w); err != nil {
  375. return err
  376. }
  377. }
  378. return nil
  379. }
  380. ////////////////////////////////////////////////////////////////////////////////
  381. func discardArray(br *bufio.Reader, l int) error {
  382. for i := 0; i < l; i++ {
  383. if err := (Any{}).UnmarshalRESP(br); err != nil {
  384. return err
  385. }
  386. }
  387. return nil
  388. }
  389. func discardArrayAfterErr(br *bufio.Reader, left int, err error) error {
  390. // if the last error which occurred didn't discard the message it was on, we
  391. // can't do anything
  392. if !errors.As(err, new(resp.ErrDiscarded)) {
  393. return err
  394. } else if err := discardArray(br, left); err != nil {
  395. return err
  396. }
  397. // The original error was already wrapped in an ErrDiscarded, so just return
  398. // it as it was given
  399. return err
  400. }
  401. ////////////////////////////////////////////////////////////////////////////////
  402. // Any represents any primitive go type, such as integers, floats, strings,
  403. // bools, etc... It also includes encoding.Text(Un)Marshalers and
  404. // encoding.(Un)BinaryMarshalers. It will _not_ marshal resp.Marshalers.
  405. //
  406. // Most things will be treated as bulk strings, except for those that have their
  407. // own corresponding type in the RESP protocol (e.g. ints). strings and []bytes
  408. // will always be encoded as bulk strings, never simple strings.
  409. //
  410. // Arrays and slices will be treated as RESP arrays, and their values will be
  411. // treated as if also wrapped in an Any struct. Maps will be similarly treated,
  412. // but they will be flattened into arrays of their alternating keys/values
  413. // first.
  414. //
  415. // When using UnmarshalRESP the value of I must be a pointer or nil. If it is
  416. // nil then the RESP value will be read and discarded.
  417. //
  418. // If an error type is read in the UnmarshalRESP method then a resp2.Error will
  419. // be returned with that error, and the value of I won't be touched.
  420. type Any struct {
  421. I interface{}
  422. // If true then the MarshalRESP method will marshal all non-array types as
  423. // bulk strings. This primarily effects integers and errors.
  424. MarshalBulkString bool
  425. // If true then no array headers will be sent when MarshalRESP is called.
  426. // For I values which are non-arrays this means no behavior change. For
  427. // arrays and embedded arrays it means only the array elements will be
  428. // written, and an ArrayHeader must have been manually marshalled
  429. // beforehand.
  430. MarshalNoArrayHeaders bool
  431. }
  432. func (a Any) cp(i interface{}) Any {
  433. a.I = i
  434. return a
  435. }
  436. var byteSliceT = reflect.TypeOf([]byte{})
  437. // NumElems returns the number of non-array elements which would be marshalled
  438. // based on I. For example:
  439. //
  440. // Any{I: "foo"}.NumElems() == 1
  441. // Any{I: []string{}}.NumElems() == 0
  442. // Any{I: []string{"foo"}}.NumElems() == 1
  443. // Any{I: []string{"foo", "bar"}}.NumElems() == 2
  444. // Any{I: [][]string{{"foo"}, {"bar", "baz"}, {}}}.NumElems() == 3
  445. //
  446. func (a Any) NumElems() int {
  447. return numElems(reflect.ValueOf(a.I))
  448. }
  449. var (
  450. lenReaderT = reflect.TypeOf(new(resp.LenReader)).Elem()
  451. encodingTextMarshalerT = reflect.TypeOf(new(encoding.TextMarshaler)).Elem()
  452. encodingBinaryMarshalerT = reflect.TypeOf(new(encoding.BinaryMarshaler)).Elem()
  453. )
  454. func numElems(vv reflect.Value) int {
  455. if !vv.IsValid() {
  456. return 1
  457. }
  458. tt := vv.Type()
  459. switch {
  460. case tt.Implements(lenReaderT):
  461. return 1
  462. case tt.Implements(encodingTextMarshalerT):
  463. return 1
  464. case tt.Implements(encodingBinaryMarshalerT):
  465. return 1
  466. }
  467. switch vv.Kind() {
  468. case reflect.Ptr:
  469. return numElems(reflect.Indirect(vv))
  470. case reflect.Slice, reflect.Array:
  471. // NOTE []rune might need extra support here
  472. if vv.Type() == byteSliceT {
  473. return 1
  474. }
  475. l := vv.Len()
  476. var c int
  477. for i := 0; i < l; i++ {
  478. c += numElems(vv.Index(i))
  479. }
  480. return c
  481. case reflect.Map:
  482. kkv := vv.MapKeys()
  483. var c int
  484. for _, kv := range kkv {
  485. c += numElems(kv)
  486. c += numElems(vv.MapIndex(kv))
  487. }
  488. return c
  489. case reflect.Interface:
  490. return numElems(vv.Elem())
  491. case reflect.Struct:
  492. return numElemsStruct(vv, true)
  493. default:
  494. return 1
  495. }
  496. }
  497. // this is separated out of numElems because marshalStruct is only given the
  498. // reflect.Value and needs to know the numElems, so it wouldn't make sense to
  499. // recast to an interface{} to pass into NumElems, it would just get turned into
  500. // a reflect.Value again.
  501. func numElemsStruct(vv reflect.Value, flat bool) int {
  502. tt := vv.Type()
  503. l := vv.NumField()
  504. var c int
  505. for i := 0; i < l; i++ {
  506. ft, fv := tt.Field(i), vv.Field(i)
  507. if ft.Anonymous {
  508. if fv = reflect.Indirect(fv); fv.IsValid() { // fv isn't nil
  509. c += numElemsStruct(fv, flat)
  510. }
  511. continue
  512. } else if ft.PkgPath != "" || ft.Tag.Get("redis") == "-" {
  513. continue // continue
  514. }
  515. c++ // for the key
  516. if flat {
  517. c += numElems(fv)
  518. } else {
  519. c++
  520. }
  521. }
  522. return c
  523. }
  524. // MarshalRESP implements the Marshaler method.
  525. func (a Any) MarshalRESP(w io.Writer) error {
  526. marshalBulk := func(b []byte) error {
  527. bs := BulkStringBytes{B: b, MarshalNotNil: a.MarshalBulkString}
  528. return bs.MarshalRESP(w)
  529. }
  530. switch at := a.I.(type) {
  531. case []byte:
  532. return marshalBulk(at)
  533. case string:
  534. if at == "" {
  535. // special case, we never want string to be nil, but appending empty
  536. // string to a nil []byte would still be a nil bulk string
  537. return BulkStringBytes{MarshalNotNil: true}.MarshalRESP(w)
  538. }
  539. scratch := bytesutil.GetBytes()
  540. defer bytesutil.PutBytes(scratch)
  541. *scratch = append(*scratch, at...)
  542. return marshalBulk(*scratch)
  543. case bool:
  544. b := bools[0]
  545. if at {
  546. b = bools[1]
  547. }
  548. return marshalBulk(b)
  549. case float32:
  550. scratch := bytesutil.GetBytes()
  551. defer bytesutil.PutBytes(scratch)
  552. *scratch = strconv.AppendFloat(*scratch, float64(at), 'f', -1, 32)
  553. return marshalBulk(*scratch)
  554. case float64:
  555. scratch := bytesutil.GetBytes()
  556. defer bytesutil.PutBytes(scratch)
  557. *scratch = strconv.AppendFloat(*scratch, at, 'f', -1, 64)
  558. return marshalBulk(*scratch)
  559. case nil:
  560. return marshalBulk(nil)
  561. case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
  562. at64 := bytesutil.AnyIntToInt64(at)
  563. if a.MarshalBulkString {
  564. scratch := bytesutil.GetBytes()
  565. defer bytesutil.PutBytes(scratch)
  566. *scratch = strconv.AppendInt(*scratch, at64, 10)
  567. return marshalBulk(*scratch)
  568. }
  569. return Int{I: at64}.MarshalRESP(w)
  570. case error:
  571. if a.MarshalBulkString {
  572. scratch := bytesutil.GetBytes()
  573. defer bytesutil.PutBytes(scratch)
  574. *scratch = append(*scratch, at.Error()...)
  575. return marshalBulk(*scratch)
  576. }
  577. return Error{E: at}.MarshalRESP(w)
  578. case resp.LenReader:
  579. return BulkReader{LR: at}.MarshalRESP(w)
  580. case encoding.TextMarshaler:
  581. b, err := at.MarshalText()
  582. if err != nil {
  583. return err
  584. }
  585. return marshalBulk(b)
  586. case encoding.BinaryMarshaler:
  587. b, err := at.MarshalBinary()
  588. if err != nil {
  589. return err
  590. }
  591. return marshalBulk(b)
  592. }
  593. // now we use.... reflection! duhduhduuuuh....
  594. vv := reflect.ValueOf(a.I)
  595. // if it's a pointer we de-reference and try the pointed to value directly
  596. if vv.Kind() == reflect.Ptr {
  597. var ivv reflect.Value
  598. if vv.IsNil() {
  599. ivv = reflect.New(vv.Type().Elem())
  600. } else {
  601. ivv = reflect.Indirect(vv)
  602. }
  603. return a.cp(ivv.Interface()).MarshalRESP(w)
  604. }
  605. // some helper functions
  606. var err error
  607. arrHeader := func(l int) {
  608. if a.MarshalNoArrayHeaders || err != nil {
  609. return
  610. }
  611. err = ArrayHeader{N: l}.MarshalRESP(w)
  612. }
  613. arrVal := func(v interface{}) {
  614. if err != nil {
  615. return
  616. }
  617. err = a.cp(v).MarshalRESP(w)
  618. }
  619. switch vv.Kind() {
  620. case reflect.Slice, reflect.Array:
  621. if vv.IsNil() && !a.MarshalNoArrayHeaders {
  622. _, err := w.Write(nilArray)
  623. return err
  624. }
  625. l := vv.Len()
  626. arrHeader(l)
  627. for i := 0; i < l; i++ {
  628. arrVal(vv.Index(i).Interface())
  629. }
  630. case reflect.Map:
  631. if vv.IsNil() && !a.MarshalNoArrayHeaders {
  632. _, err := w.Write(nilArray)
  633. return err
  634. }
  635. kkv := vv.MapKeys()
  636. arrHeader(len(kkv) * 2)
  637. for _, kv := range kkv {
  638. arrVal(kv.Interface())
  639. arrVal(vv.MapIndex(kv).Interface())
  640. }
  641. case reflect.Struct:
  642. return a.marshalStruct(w, vv, false)
  643. default:
  644. return fmt.Errorf("could not marshal value of type %T", a.I)
  645. }
  646. return err
  647. }
  648. func (a Any) marshalStruct(w io.Writer, vv reflect.Value, inline bool) error {
  649. var err error
  650. if !a.MarshalNoArrayHeaders && !inline {
  651. numElems := numElemsStruct(vv, a.MarshalNoArrayHeaders)
  652. if err = (ArrayHeader{N: numElems}).MarshalRESP(w); err != nil {
  653. return err
  654. }
  655. }
  656. tt := vv.Type()
  657. l := vv.NumField()
  658. for i := 0; i < l; i++ {
  659. ft, fv := tt.Field(i), vv.Field(i)
  660. tag := ft.Tag.Get("redis")
  661. if ft.Anonymous {
  662. if fv = reflect.Indirect(fv); !fv.IsValid() { // fv is nil
  663. continue
  664. } else if err := a.marshalStruct(w, fv, true); err != nil {
  665. return err
  666. }
  667. continue
  668. } else if ft.PkgPath != "" || tag == "-" {
  669. continue // unexported
  670. }
  671. keyName := ft.Name
  672. if tag != "" {
  673. keyName = tag
  674. }
  675. if err := (BulkString{S: keyName}).MarshalRESP(w); err != nil {
  676. return err
  677. } else if err := a.cp(fv.Interface()).MarshalRESP(w); err != nil {
  678. return err
  679. }
  680. }
  681. return nil
  682. }
  683. func saneDefault(prefix byte) interface{} {
  684. // we don't handle ErrorPrefix because that always returns an error and
  685. // doesn't touch I
  686. switch prefix {
  687. case ArrayPrefix[0]:
  688. ii := make([]interface{}, 8)
  689. return &ii
  690. case BulkStringPrefix[0]:
  691. bb := make([]byte, 16)
  692. return &bb
  693. case SimpleStringPrefix[0]:
  694. return new(string)
  695. case IntPrefix[0]:
  696. return new(int64)
  697. }
  698. panic("should never get here")
  699. }
  700. // We use pools for these even though they only get used within
  701. // Any.UnmarshalRESP because of how often they get used. Any return from redis
  702. // which has a simple string or bulk string (the vast majority of them) is going
  703. // to go through one of these.
  704. var (
  705. // RawMessage.UnmarshalInto also uses these.
  706. byteReaderPool = sync.Pool{
  707. New: func() interface{} {
  708. return bytes.NewReader(nil)
  709. },
  710. }
  711. bufioReaderPool = sync.Pool{
  712. New: func() interface{} {
  713. return bufio.NewReader(nil)
  714. },
  715. }
  716. )
  717. // UnmarshalRESP implements the Unmarshaler method.
  718. func (a Any) UnmarshalRESP(br *bufio.Reader) error {
  719. // if I is itself an Unmarshaler just hit that directly
  720. if u, ok := a.I.(resp.Unmarshaler); ok {
  721. return u.UnmarshalRESP(br)
  722. }
  723. b, err := br.Peek(1)
  724. if err != nil {
  725. return err
  726. }
  727. prefix := b[0]
  728. // This is a super special case that _must_ be handled before we actually
  729. // read from the reader. If an *interface{} is given we instead unmarshal
  730. // into a default (created based on the type of th message), then set the
  731. // *interface{} to that
  732. if ai, ok := a.I.(*interface{}); ok && prefix != ErrorPrefix[0] {
  733. innerA := Any{I: saneDefault(prefix)}
  734. if err := innerA.UnmarshalRESP(br); err != nil {
  735. return err
  736. }
  737. *ai = reflect.ValueOf(innerA.I).Elem().Interface()
  738. return nil
  739. }
  740. if _, err = br.Discard(1); err != nil {
  741. return err
  742. }
  743. b, err = bytesutil.BufferedBytesDelim(br)
  744. if err != nil {
  745. return err
  746. }
  747. switch prefix {
  748. case ErrorPrefix[0]:
  749. return Error{E: errors.New(string(b))}
  750. case ArrayPrefix[0]:
  751. l, err := bytesutil.ParseInt(b)
  752. if err != nil {
  753. return err
  754. } else if l == -1 {
  755. return a.unmarshalNil()
  756. }
  757. return a.unmarshalArray(br, l)
  758. case BulkStringPrefix[0]:
  759. l, err := bytesutil.ParseInt(b) // fuck DRY
  760. if err != nil {
  761. return err
  762. } else if l == -1 {
  763. return a.unmarshalNil()
  764. }
  765. // This is a bit of a clusterfuck. Basically:
  766. // - If unmarshal returns a non-Discarded error, return that asap.
  767. // - If discarding the last 2 bytes (in order to discard the full
  768. // message) fails, return that asap
  769. // - Otherwise return the original error, if there was any
  770. if err = a.unmarshalSingle(br, int(l)); err != nil {
  771. if !errors.As(err, new(resp.ErrDiscarded)) {
  772. return err
  773. }
  774. }
  775. if _, discardErr := br.Discard(2); discardErr != nil {
  776. return discardErr
  777. }
  778. return err
  779. case SimpleStringPrefix[0], IntPrefix[0]:
  780. reader := byteReaderPool.Get().(*bytes.Reader)
  781. reader.Reset(b)
  782. err := a.unmarshalSingle(reader, reader.Len())
  783. byteReaderPool.Put(reader)
  784. return err
  785. default:
  786. return fmt.Errorf("unknown type prefix %q", b[0])
  787. }
  788. }
  789. func (a Any) unmarshalSingle(body io.Reader, n int) error {
  790. var (
  791. err error
  792. i int64
  793. ui uint64
  794. )
  795. switch ai := a.I.(type) {
  796. case nil:
  797. // just read it and do nothing
  798. err = bytesutil.ReadNDiscard(body, n)
  799. case *string:
  800. scratch := bytesutil.GetBytes()
  801. *scratch, err = bytesutil.ReadNAppend(body, *scratch, n)
  802. *ai = string(*scratch)
  803. bytesutil.PutBytes(scratch)
  804. case *[]byte:
  805. *ai, err = bytesutil.ReadNAppend(body, (*ai)[:0], n)
  806. case *bool:
  807. ui, err = bytesutil.ReadUint(body, n)
  808. *ai = ui > 0
  809. case *int:
  810. i, err = bytesutil.ReadInt(body, n)
  811. *ai = int(i)
  812. case *int8:
  813. i, err = bytesutil.ReadInt(body, n)
  814. *ai = int8(i)
  815. case *int16:
  816. i, err = bytesutil.ReadInt(body, n)
  817. *ai = int16(i)
  818. case *int32:
  819. i, err = bytesutil.ReadInt(body, n)
  820. *ai = int32(i)
  821. case *int64:
  822. i, err = bytesutil.ReadInt(body, n)
  823. *ai = i
  824. case *uint:
  825. ui, err = bytesutil.ReadUint(body, n)
  826. *ai = uint(ui)
  827. case *uint8:
  828. ui, err = bytesutil.ReadUint(body, n)
  829. *ai = uint8(ui)
  830. case *uint16:
  831. ui, err = bytesutil.ReadUint(body, n)
  832. *ai = uint16(ui)
  833. case *uint32:
  834. ui, err = bytesutil.ReadUint(body, n)
  835. *ai = uint32(ui)
  836. case *uint64:
  837. ui, err = bytesutil.ReadUint(body, n)
  838. *ai = ui
  839. case *float32:
  840. var f float64
  841. f, err = bytesutil.ReadFloat(body, 32, n)
  842. *ai = float32(f)
  843. case *float64:
  844. *ai, err = bytesutil.ReadFloat(body, 64, n)
  845. case io.Writer:
  846. _, err = io.CopyN(ai, body, int64(n))
  847. case encoding.TextUnmarshaler:
  848. scratch := bytesutil.GetBytes()
  849. if *scratch, err = bytesutil.ReadNAppend(body, *scratch, n); err != nil {
  850. break
  851. }
  852. err = ai.UnmarshalText(*scratch)
  853. bytesutil.PutBytes(scratch)
  854. case encoding.BinaryUnmarshaler:
  855. scratch := bytesutil.GetBytes()
  856. if *scratch, err = bytesutil.ReadNAppend(body, *scratch, n); err != nil {
  857. break
  858. }
  859. err = ai.UnmarshalBinary(*scratch)
  860. bytesutil.PutBytes(scratch)
  861. default:
  862. scratch := bytesutil.GetBytes()
  863. if *scratch, err = bytesutil.ReadNAppend(body, *scratch, n); err != nil {
  864. break
  865. }
  866. err = resp.ErrDiscarded{
  867. Err: fmt.Errorf("can't unmarshal into %T, message body was: %q", a.I, *scratch),
  868. }
  869. bytesutil.PutBytes(scratch)
  870. }
  871. return err
  872. }
  873. func (a Any) unmarshalNil() error {
  874. vv := reflect.ValueOf(a.I)
  875. if vv.Kind() != reflect.Ptr || !vv.Elem().CanSet() {
  876. // If the type in I can't be set then just ignore it. This is kind of
  877. // weird but it's what encoding/json does in the same circumstance
  878. return nil
  879. }
  880. vve := vv.Elem()
  881. vve.Set(reflect.Zero(vve.Type()))
  882. return nil
  883. }
  884. func (a Any) unmarshalArray(br *bufio.Reader, l int64) error {
  885. if a.I == nil {
  886. return discardArray(br, int(l))
  887. }
  888. size := int(l)
  889. v := reflect.ValueOf(a.I)
  890. if v.Kind() != reflect.Ptr {
  891. err := resp.ErrDiscarded{
  892. Err: fmt.Errorf("can't unmarshal array into %T", a.I),
  893. }
  894. return discardArrayAfterErr(br, int(l), err)
  895. }
  896. v = reflect.Indirect(v)
  897. switch v.Kind() {
  898. case reflect.Slice:
  899. if size > v.Cap() || v.IsNil() {
  900. newV := reflect.MakeSlice(v.Type(), size, size)
  901. // we copy only because there might be some preset values in there
  902. // already that we're intended to decode into,
  903. // e.g. []interface{}{int8(0), ""}
  904. reflect.Copy(newV, v)
  905. v.Set(newV)
  906. } else if size != v.Len() {
  907. v.SetLen(size)
  908. }
  909. for i := 0; i < size; i++ {
  910. ai := Any{I: v.Index(i).Addr().Interface()}
  911. if err := ai.UnmarshalRESP(br); err != nil {
  912. return discardArrayAfterErr(br, int(l)-i-1, err)
  913. }
  914. }
  915. return nil
  916. case reflect.Map:
  917. if size%2 != 0 {
  918. err := resp.ErrDiscarded{Err: errors.New("cannot decode redis array with odd number of elements into map")}
  919. return discardArrayAfterErr(br, int(l), err)
  920. } else if v.IsNil() {
  921. v.Set(reflect.MakeMapWithSize(v.Type(), size/2))
  922. }
  923. var kvs reflect.Value
  924. if size > 0 && canShareReflectValue(v.Type().Key()) {
  925. kvs = reflect.New(v.Type().Key())
  926. }
  927. var vvs reflect.Value
  928. if size > 0 && canShareReflectValue(v.Type().Elem()) {
  929. vvs = reflect.New(v.Type().Elem())
  930. }
  931. for i := 0; i < size; i += 2 {
  932. kv := kvs
  933. if !kv.IsValid() {
  934. kv = reflect.New(v.Type().Key())
  935. }
  936. if err := (Any{I: kv.Interface()}).UnmarshalRESP(br); err != nil {
  937. return discardArrayAfterErr(br, int(l)-i-1, err)
  938. }
  939. vv := vvs
  940. if !vv.IsValid() {
  941. vv = reflect.New(v.Type().Elem())
  942. }
  943. if err := (Any{I: vv.Interface()}).UnmarshalRESP(br); err != nil {
  944. return discardArrayAfterErr(br, int(l)-i-2, err)
  945. }
  946. v.SetMapIndex(kv.Elem(), vv.Elem())
  947. }
  948. return nil
  949. case reflect.Struct:
  950. if size%2 != 0 {
  951. err := resp.ErrDiscarded{Err: errors.New("cannot decode redis array with odd number of elements into struct")}
  952. return discardArrayAfterErr(br, int(l), err)
  953. }
  954. structFields := getStructFields(v.Type())
  955. var field BulkStringBytes
  956. for i := 0; i < size; i += 2 {
  957. var structField structField
  958. var ok bool
  959. prefix, err := br.Peek(1)
  960. switch {
  961. case err != nil:
  962. return discardArrayAfterErr(br, int(l)-i, err)
  963. case bytes.Equal(prefix, SimpleStringPrefix):
  964. var field SimpleString
  965. if err := field.UnmarshalRESP(br); err != nil {
  966. return discardArrayAfterErr(br, int(l)-i-1, err)
  967. }
  968. structField, ok = structFields[field.S]
  969. case bytes.Equal(prefix, BulkStringPrefix):
  970. if err := field.UnmarshalRESP(br); err != nil {
  971. return discardArrayAfterErr(br, int(l)-i-1, err)
  972. }
  973. structField, ok = structFields[string(field.B)] // no allocation, since Go 1.3
  974. default:
  975. var err error = errUnexpectedPrefix{Prefix: prefix, ExpectedPrefix: BulkStringPrefix}
  976. err = resp.ErrDiscarded{Err: err}
  977. return discardArrayAfterErr(br, int(l)-i, err)
  978. }
  979. var vv reflect.Value
  980. if ok {
  981. vv = getStructField(v, structField.indices)
  982. }
  983. if !ok || !vv.IsValid() {
  984. // discard the value
  985. if err := (Any{}).UnmarshalRESP(br); err != nil {
  986. return discardArrayAfterErr(br, int(l)-i-2, err)
  987. }
  988. } else if err := (Any{I: vv.Interface()}).UnmarshalRESP(br); err != nil {
  989. return discardArrayAfterErr(br, int(l)-i-2, err)
  990. }
  991. }
  992. return nil
  993. default:
  994. err := resp.ErrDiscarded{Err: fmt.Errorf("cannot decode redis array into %v", v.Type())}
  995. return discardArrayAfterErr(br, int(l), err)
  996. }
  997. }
  998. func canShareReflectValue(ty reflect.Type) bool {
  999. switch ty.Kind() {
  1000. case reflect.Bool,
  1001. reflect.Int,
  1002. reflect.Int8,
  1003. reflect.Int16,
  1004. reflect.Int32,
  1005. reflect.Int64,
  1006. reflect.Uint,
  1007. reflect.Uint8,
  1008. reflect.Uint16,
  1009. reflect.Uint32,
  1010. reflect.Uint64,
  1011. reflect.Uintptr,
  1012. reflect.Float32,
  1013. reflect.Float64,
  1014. reflect.Complex64,
  1015. reflect.Complex128,
  1016. reflect.String:
  1017. return true
  1018. default:
  1019. return false
  1020. }
  1021. }
  1022. type structField struct {
  1023. name string
  1024. fromTag bool // from a tag overwrites a field name
  1025. indices []int
  1026. }
  1027. // encoding/json uses a similar pattern for unmarshaling into structs.
  1028. var structFieldsCache sync.Map // aka map[reflect.Type]map[string]structField
  1029. func getStructFields(t reflect.Type) map[string]structField {
  1030. if mV, ok := structFieldsCache.Load(t); ok {
  1031. return mV.(map[string]structField)
  1032. }
  1033. getIndices := func(parents []int, i int) []int {
  1034. indices := make([]int, len(parents), len(parents)+1)
  1035. copy(indices, parents)
  1036. indices = append(indices, i)
  1037. return indices
  1038. }
  1039. m := map[string]structField{}
  1040. var populateFrom func(reflect.Type, []int)
  1041. populateFrom = func(t reflect.Type, parents []int) {
  1042. if t.Kind() == reflect.Ptr {
  1043. t = t.Elem()
  1044. }
  1045. l := t.NumField()
  1046. // first get all fields which aren't embedded structs
  1047. for i := 0; i < l; i++ {
  1048. ft := t.Field(i)
  1049. if ft.Anonymous || ft.PkgPath != "" {
  1050. continue
  1051. }
  1052. key, fromTag := ft.Name, false
  1053. if tag := ft.Tag.Get("redis"); tag != "" && tag != "-" {
  1054. key, fromTag = tag, true
  1055. }
  1056. if m[key].fromTag {
  1057. continue
  1058. }
  1059. m[key] = structField{
  1060. name: key,
  1061. fromTag: fromTag,
  1062. indices: getIndices(parents, i),
  1063. }
  1064. }
  1065. // then find all embedded structs and descend into them
  1066. for i := 0; i < l; i++ {
  1067. ft := t.Field(i)
  1068. if !ft.Anonymous {
  1069. continue
  1070. }
  1071. populateFrom(ft.Type, getIndices(parents, i))
  1072. }
  1073. }
  1074. populateFrom(t, []int{})
  1075. structFieldsCache.LoadOrStore(t, m)
  1076. return m
  1077. }
  1078. // v must be setable. Always returns a Kind() == reflect.Ptr, unless it returns
  1079. // the zero Value, which means a setable value couldn't be gotten.
  1080. func getStructField(v reflect.Value, ii []int) reflect.Value {
  1081. if len(ii) == 0 {
  1082. return v.Addr()
  1083. }
  1084. i, ii := ii[0], ii[1:]
  1085. iv := v.Field(i)
  1086. if iv.Kind() == reflect.Ptr && iv.IsNil() {
  1087. // If the field is a pointer to an unexported type then it won't be
  1088. // settable, though if the user pre-sets the value it will be (I think).
  1089. if !iv.CanSet() {
  1090. return reflect.Value{}
  1091. }
  1092. iv.Set(reflect.New(iv.Type().Elem()))
  1093. }
  1094. iv = reflect.Indirect(iv)
  1095. return getStructField(iv, ii)
  1096. }
  1097. ////////////////////////////////////////////////////////////////////////////////
  1098. // RawMessage is a Marshaler/Unmarshaler which will capture the exact raw bytes
  1099. // of a RESP message. When Marshaling the exact bytes of the RawMessage will be
  1100. // written as-is. When Unmarshaling the bytes of a single RESP message will be
  1101. // read into the RawMessage's bytes.
  1102. type RawMessage []byte
  1103. // MarshalRESP implements the Marshaler method.
  1104. func (rm RawMessage) MarshalRESP(w io.Writer) error {
  1105. _, err := w.Write(rm)
  1106. return err
  1107. }
  1108. // UnmarshalRESP implements the Unmarshaler method.
  1109. func (rm *RawMessage) UnmarshalRESP(br *bufio.Reader) error {
  1110. *rm = (*rm)[:0]
  1111. return rm.unmarshal(br)
  1112. }
  1113. func (rm *RawMessage) unmarshal(br *bufio.Reader) error {
  1114. b, err := br.ReadSlice('\n')
  1115. if err != nil {
  1116. return err
  1117. }
  1118. *rm = append(*rm, b...)
  1119. if len(b) < 3 {
  1120. return errors.New("malformed data read")
  1121. }
  1122. body := b[1 : len(b)-2]
  1123. switch b[0] {
  1124. case ArrayPrefix[0]:
  1125. l, err := bytesutil.ParseInt(body)
  1126. if err != nil {
  1127. return err
  1128. } else if l == -1 {
  1129. return nil
  1130. }
  1131. for i := 0; i < int(l); i++ {
  1132. if err := rm.unmarshal(br); err != nil {
  1133. return err
  1134. }
  1135. }
  1136. return nil
  1137. case BulkStringPrefix[0]:
  1138. l, err := bytesutil.ParseInt(body) // fuck DRY
  1139. if err != nil {
  1140. return err
  1141. } else if l == -1 {
  1142. return nil
  1143. }
  1144. *rm, err = bytesutil.ReadNAppend(br, *rm, int(l+2))
  1145. return err
  1146. case ErrorPrefix[0], SimpleStringPrefix[0], IntPrefix[0]:
  1147. return nil
  1148. default:
  1149. return fmt.Errorf("unknown type prefix %q", b[0])
  1150. }
  1151. }
  1152. // UnmarshalInto is a shortcut for wrapping this RawMessage in a *bufio.Reader
  1153. // and passing that into the given Unmarshaler's UnmarshalRESP method. Any error
  1154. // from calling UnmarshalRESP is returned, and the RawMessage is unaffected in
  1155. // all cases.
  1156. func (rm RawMessage) UnmarshalInto(u resp.Unmarshaler) error {
  1157. r := byteReaderPool.Get().(*bytes.Reader)
  1158. r.Reset(rm)
  1159. br := bufioReaderPool.Get().(*bufio.Reader)
  1160. br.Reset(r)
  1161. err := u.UnmarshalRESP(br)
  1162. bufioReaderPool.Put(br)
  1163. byteReaderPool.Put(r)
  1164. return err
  1165. }
  1166. // IsNil returns true if the contents of RawMessage are one of the nil values.
  1167. func (rm RawMessage) IsNil() bool {
  1168. return bytes.Equal(rm, nilBulkString) || bytes.Equal(rm, nilArray)
  1169. }
  1170. // IsEmptyArray returns true if the contents of RawMessage is empty array value.
  1171. func (rm RawMessage) IsEmptyArray() bool {
  1172. return bytes.Equal(rm, emptyArray)
  1173. }