encode.go 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299
  1. // Copyright (c) Faye Amacker. All rights reserved.
  2. // Licensed under the MIT License. See LICENSE in the project root for license information.
  3. package cbor
  4. import (
  5. "bytes"
  6. "encoding"
  7. "encoding/binary"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "math"
  12. "math/big"
  13. "math/rand"
  14. "reflect"
  15. "sort"
  16. "strconv"
  17. "sync"
  18. "time"
  19. "github.com/x448/float16"
  20. )
  21. // Marshal returns the CBOR encoding of v using default encoding options.
  22. // See EncOptions for encoding options.
  23. //
  24. // Marshal uses the following encoding rules:
  25. //
  26. // If value implements the Marshaler interface, Marshal calls its
  27. // MarshalCBOR method.
  28. //
  29. // If value implements encoding.BinaryMarshaler, Marhsal calls its
  30. // MarshalBinary method and encode it as CBOR byte string.
  31. //
  32. // Boolean values encode as CBOR booleans (type 7).
  33. //
  34. // Positive integer values encode as CBOR positive integers (type 0).
  35. //
  36. // Negative integer values encode as CBOR negative integers (type 1).
  37. //
  38. // Floating point values encode as CBOR floating points (type 7).
  39. //
  40. // String values encode as CBOR text strings (type 3).
  41. //
  42. // []byte values encode as CBOR byte strings (type 2).
  43. //
  44. // Array and slice values encode as CBOR arrays (type 4).
  45. //
  46. // Map values encode as CBOR maps (type 5).
  47. //
  48. // Struct values encode as CBOR maps (type 5). Each exported struct field
  49. // becomes a pair with field name encoded as CBOR text string (type 3) and
  50. // field value encoded based on its type. See struct tag option "keyasint"
  51. // to encode field name as CBOR integer (type 0 and 1). Also see struct
  52. // tag option "toarray" for special field "_" to encode struct values as
  53. // CBOR array (type 4).
  54. //
  55. // Marshal supports format string stored under the "cbor" key in the struct
  56. // field's tag. CBOR format string can specify the name of the field,
  57. // "omitempty", "omitzero" and "keyasint" options, and special case "-" for
  58. // field omission. If "cbor" key is absent, Marshal uses "json" key.
  59. // When using the "json" key, the "omitzero" option is honored when building
  60. // with Go 1.24+ to match stdlib encoding/json behavior.
  61. //
  62. // Struct field name is treated as integer if it has "keyasint" option in
  63. // its format string. The format string must specify an integer as its
  64. // field name.
  65. //
  66. // Special struct field "_" is used to specify struct level options, such as
  67. // "toarray". "toarray" option enables Go struct to be encoded as CBOR array.
  68. // "omitempty" and "omitzero" are disabled by "toarray" to ensure that the
  69. // same number of elements are encoded every time.
  70. //
  71. // Anonymous struct fields are marshaled as if their exported fields
  72. // were fields in the outer struct. Marshal follows the same struct fields
  73. // visibility rules used by JSON encoding package.
  74. //
  75. // time.Time values encode as text strings specified in RFC3339 or numerical
  76. // representation of seconds since January 1, 1970 UTC depending on
  77. // EncOptions.Time setting. Also See EncOptions.TimeTag to encode
  78. // time.Time as CBOR tag with tag number 0 or 1.
  79. //
  80. // big.Int values encode as CBOR integers (type 0 and 1) if values fit.
  81. // Otherwise, big.Int values encode as CBOR bignums (tag 2 and 3). See
  82. // EncOptions.BigIntConvert to always encode big.Int values as CBOR
  83. // bignums.
  84. //
  85. // Pointer values encode as the value pointed to.
  86. //
  87. // Interface values encode as the value stored in the interface.
  88. //
  89. // Nil slice/map/pointer/interface values encode as CBOR nulls (type 7).
  90. //
  91. // Values of other types cannot be encoded in CBOR. Attempting
  92. // to encode such a value causes Marshal to return an UnsupportedTypeError.
  93. func Marshal(v any) ([]byte, error) {
  94. return defaultEncMode.Marshal(v)
  95. }
  96. // MarshalToBuffer encodes v into provided buffer (instead of using built-in buffer pool)
  97. // and uses default encoding options.
  98. //
  99. // NOTE: Unlike Marshal, the buffer provided to MarshalToBuffer can contain
  100. // partially encoded data if error is returned.
  101. //
  102. // See Marshal for more details.
  103. func MarshalToBuffer(v any, buf *bytes.Buffer) error {
  104. return defaultEncMode.MarshalToBuffer(v, buf)
  105. }
  106. // Marshaler is the interface implemented by types that can marshal themselves
  107. // into valid CBOR.
  108. type Marshaler interface {
  109. MarshalCBOR() ([]byte, error)
  110. }
  111. // MarshalerError represents error from checking encoded CBOR data item
  112. // returned from MarshalCBOR for well-formedness and some very limited tag validation.
  113. type MarshalerError struct {
  114. typ reflect.Type
  115. err error
  116. }
  117. func (e *MarshalerError) Error() string {
  118. return "cbor: error calling MarshalCBOR for type " +
  119. e.typ.String() +
  120. ": " + e.err.Error()
  121. }
  122. func (e *MarshalerError) Unwrap() error {
  123. return e.err
  124. }
  125. type TranscodeError struct {
  126. err error
  127. rtype reflect.Type
  128. sourceFormat, targetFormat string
  129. }
  130. func (e TranscodeError) Error() string {
  131. return "cbor: cannot transcode from " + e.sourceFormat + " to " + e.targetFormat + ": " + e.err.Error()
  132. }
  133. func (e TranscodeError) Unwrap() error {
  134. return e.err
  135. }
  136. // UnsupportedTypeError is returned by Marshal when attempting to encode value
  137. // of an unsupported type.
  138. type UnsupportedTypeError struct {
  139. Type reflect.Type
  140. }
  141. func (e *UnsupportedTypeError) Error() string {
  142. return "cbor: unsupported type: " + e.Type.String()
  143. }
  144. // UnsupportedValueError is returned by Marshal when attempting to encode an
  145. // unsupported value.
  146. type UnsupportedValueError struct {
  147. msg string
  148. }
  149. func (e *UnsupportedValueError) Error() string {
  150. return "cbor: unsupported value: " + e.msg
  151. }
  152. // SortMode identifies supported sorting order.
  153. type SortMode int
  154. const (
  155. // SortNone encodes map pairs and struct fields in an arbitrary order.
  156. SortNone SortMode = 0
  157. // SortLengthFirst causes map keys or struct fields to be sorted such that:
  158. // - If two keys have different lengths, the shorter one sorts earlier;
  159. // - If two keys have the same length, the one with the lower value in
  160. // (byte-wise) lexical order sorts earlier.
  161. // It is used in "Canonical CBOR" encoding in RFC 7049 3.9.
  162. SortLengthFirst SortMode = 1
  163. // SortBytewiseLexical causes map keys or struct fields to be sorted in the
  164. // bytewise lexicographic order of their deterministic CBOR encodings.
  165. // It is used in "CTAP2 Canonical CBOR" and "Core Deterministic Encoding"
  166. // in RFC 7049bis.
  167. SortBytewiseLexical SortMode = 2
  168. // SortShuffle encodes map pairs and struct fields in a shuffled
  169. // order. This mode does not guarantee an unbiased permutation, but it
  170. // does guarantee that the runtime of the shuffle algorithm used will be
  171. // constant.
  172. SortFastShuffle SortMode = 3
  173. // SortCanonical is used in "Canonical CBOR" encoding in RFC 7049 3.9.
  174. SortCanonical SortMode = SortLengthFirst
  175. // SortCTAP2 is used in "CTAP2 Canonical CBOR".
  176. SortCTAP2 SortMode = SortBytewiseLexical
  177. // SortCoreDeterministic is used in "Core Deterministic Encoding" in RFC 7049bis.
  178. SortCoreDeterministic SortMode = SortBytewiseLexical
  179. maxSortMode SortMode = 4
  180. )
  181. func (sm SortMode) valid() bool {
  182. return sm >= 0 && sm < maxSortMode
  183. }
  184. // StringMode specifies how to encode Go string values.
  185. type StringMode int
  186. const (
  187. // StringToTextString encodes Go string to CBOR text string (major type 3).
  188. StringToTextString StringMode = iota
  189. // StringToByteString encodes Go string to CBOR byte string (major type 2).
  190. StringToByteString
  191. )
  192. func (st StringMode) cborType() (cborType, error) {
  193. switch st {
  194. case StringToTextString:
  195. return cborTypeTextString, nil
  196. case StringToByteString:
  197. return cborTypeByteString, nil
  198. }
  199. return 0, errors.New("cbor: invalid StringType " + strconv.Itoa(int(st)))
  200. }
  201. // ShortestFloatMode specifies which floating-point format should
  202. // be used as the shortest possible format for CBOR encoding.
  203. // It is not used for encoding Infinity and NaN values.
  204. type ShortestFloatMode int
  205. const (
  206. // ShortestFloatNone makes float values encode without any conversion.
  207. // This is the default for ShortestFloatMode in v1.
  208. // E.g. a float32 in Go will encode to CBOR float32. And
  209. // a float64 in Go will encode to CBOR float64.
  210. ShortestFloatNone ShortestFloatMode = iota
  211. // ShortestFloat16 specifies float16 as the shortest form that preserves value.
  212. // E.g. if float64 can convert to float32 while preserving value, then
  213. // encoding will also try to convert float32 to float16. So a float64 might
  214. // encode as CBOR float64, float32 or float16 depending on the value.
  215. ShortestFloat16
  216. maxShortestFloat
  217. )
  218. func (sfm ShortestFloatMode) valid() bool {
  219. return sfm >= 0 && sfm < maxShortestFloat
  220. }
  221. // NaNConvertMode specifies how to encode NaN and overrides ShortestFloatMode.
  222. // ShortestFloatMode is not used for encoding Infinity and NaN values.
  223. type NaNConvertMode int
  224. const (
  225. // NaNConvert7e00 always encodes NaN to 0xf97e00 (CBOR float16 = 0x7e00).
  226. NaNConvert7e00 NaNConvertMode = iota
  227. // NaNConvertNone never modifies or converts NaN to other representations
  228. // (float64 NaN stays float64, etc. even if it can use float16 without losing
  229. // any bits).
  230. NaNConvertNone
  231. // NaNConvertPreserveSignal converts NaN to the smallest form that preserves
  232. // value (quiet bit + payload) as described in RFC 7049bis Draft 12.
  233. NaNConvertPreserveSignal
  234. // NaNConvertQuiet always forces quiet bit = 1 and shortest form that preserves
  235. // NaN payload.
  236. NaNConvertQuiet
  237. // NaNConvertReject returns UnsupportedValueError on attempts to encode a NaN value.
  238. NaNConvertReject
  239. maxNaNConvert
  240. )
  241. func (ncm NaNConvertMode) valid() bool {
  242. return ncm >= 0 && ncm < maxNaNConvert
  243. }
  244. // InfConvertMode specifies how to encode Infinity and overrides ShortestFloatMode.
  245. // ShortestFloatMode is not used for encoding Infinity and NaN values.
  246. type InfConvertMode int
  247. const (
  248. // InfConvertFloat16 always converts Inf to lossless IEEE binary16 (float16).
  249. InfConvertFloat16 InfConvertMode = iota
  250. // InfConvertNone never converts (used by CTAP2 Canonical CBOR).
  251. InfConvertNone
  252. // InfConvertReject returns UnsupportedValueError on attempts to encode an infinite value.
  253. InfConvertReject
  254. maxInfConvert
  255. )
  256. func (icm InfConvertMode) valid() bool {
  257. return icm >= 0 && icm < maxInfConvert
  258. }
  259. // TimeMode specifies how to encode time.Time values in compliance with RFC 8949 (CBOR):
  260. // - Section 3.4.1: Standard Date/Time String
  261. // - Section 3.4.2: Epoch-Based Date/Time
  262. // For more info, see:
  263. // - https://www.rfc-editor.org/rfc/rfc8949.html
  264. // NOTE: User applications that prefer to encode time with fractional seconds to an integer
  265. // (instead of floating point or text string) can use a CBOR tag number not assigned by IANA:
  266. // 1. Define a user-defined type in Go with just a time.Time or int64 as its data.
  267. // 2. Implement the cbor.Marshaler and cbor.Unmarshaler interface for that user-defined type
  268. // to encode or decode the tagged data item with an enclosed integer content.
  269. type TimeMode int
  270. const (
  271. // TimeUnix causes time.Time to encode to a CBOR time (tag 1) with an integer content
  272. // representing seconds elapsed (with 1-second precision) since UNIX Epoch UTC.
  273. // The TimeUnix option is location independent and has a clear precision guarantee.
  274. TimeUnix TimeMode = iota
  275. // TimeUnixMicro causes time.Time to encode to a CBOR time (tag 1) with a floating point content
  276. // representing seconds elapsed (with up to 1-microsecond precision) since UNIX Epoch UTC.
  277. // NOTE: The floating point content is encoded to the shortest floating-point encoding that preserves
  278. // the 64-bit floating point value. I.e., the floating point encoding can be IEEE 764:
  279. // binary64, binary32, or binary16 depending on the content's value.
  280. TimeUnixMicro
  281. // TimeUnixDynamic causes time.Time to encode to a CBOR time (tag 1) with either an integer content or
  282. // a floating point content, depending on the content's value. This option is equivalent to dynamically
  283. // choosing TimeUnix if time.Time doesn't have fractional seconds, and using TimeUnixMicro if time.Time
  284. // has fractional seconds.
  285. TimeUnixDynamic
  286. // TimeRFC3339 causes time.Time to encode to a CBOR time (tag 0) with a text string content
  287. // representing the time using 1-second precision in RFC3339 format. If the time.Time has a
  288. // non-UTC timezone then a "localtime - UTC" numeric offset will be included as specified in RFC3339.
  289. // NOTE: User applications can avoid including the RFC3339 numeric offset by:
  290. // - providing a time.Time value set to UTC, or
  291. // - using the TimeUnix, TimeUnixMicro, or TimeUnixDynamic option instead of TimeRFC3339.
  292. TimeRFC3339
  293. // TimeRFC3339Nano causes time.Time to encode to a CBOR time (tag 0) with a text string content
  294. // representing the time using 1-nanosecond precision in RFC3339 format. If the time.Time has a
  295. // non-UTC timezone then a "localtime - UTC" numeric offset will be included as specified in RFC3339.
  296. // NOTE: User applications can avoid including the RFC3339 numeric offset by:
  297. // - providing a time.Time value set to UTC, or
  298. // - using the TimeUnix, TimeUnixMicro, or TimeUnixDynamic option instead of TimeRFC3339Nano.
  299. TimeRFC3339Nano
  300. maxTimeMode
  301. )
  302. func (tm TimeMode) valid() bool {
  303. return tm >= 0 && tm < maxTimeMode
  304. }
  305. // BigIntConvertMode specifies how to encode big.Int values.
  306. type BigIntConvertMode int
  307. const (
  308. // BigIntConvertShortest makes big.Int encode to CBOR integer if value fits.
  309. // E.g. if big.Int value can be converted to CBOR integer while preserving
  310. // value, encoder will encode it to CBOR integer (major type 0 or 1).
  311. BigIntConvertShortest BigIntConvertMode = iota
  312. // BigIntConvertNone makes big.Int encode to CBOR bignum (tag 2 or 3) without
  313. // converting it to another CBOR type.
  314. BigIntConvertNone
  315. // BigIntConvertReject returns an UnsupportedTypeError instead of marshaling a big.Int.
  316. BigIntConvertReject
  317. maxBigIntConvert
  318. )
  319. func (bim BigIntConvertMode) valid() bool {
  320. return bim >= 0 && bim < maxBigIntConvert
  321. }
  322. // NilContainersMode specifies how to encode nil slices and maps.
  323. type NilContainersMode int
  324. const (
  325. // NilContainerAsNull encodes nil slices and maps as CBOR null.
  326. // This is the default.
  327. NilContainerAsNull NilContainersMode = iota
  328. // NilContainerAsEmpty encodes nil slices and maps as
  329. // empty container (CBOR bytestring, array, or map).
  330. NilContainerAsEmpty
  331. maxNilContainersMode
  332. )
  333. func (m NilContainersMode) valid() bool {
  334. return m >= 0 && m < maxNilContainersMode
  335. }
  336. // OmitEmptyMode specifies how to encode struct fields with omitempty tag.
  337. // The default behavior omits if field value would encode as empty CBOR value.
  338. type OmitEmptyMode int
  339. const (
  340. // OmitEmptyCBORValue specifies that struct fields tagged with "omitempty"
  341. // should be omitted from encoding if the field would be encoded as an empty
  342. // CBOR value, such as CBOR false, 0, 0.0, nil, empty byte, empty string,
  343. // empty array, or empty map.
  344. OmitEmptyCBORValue OmitEmptyMode = iota
  345. // OmitEmptyGoValue specifies that struct fields tagged with "omitempty"
  346. // should be omitted from encoding if the field has an empty Go value,
  347. // defined as false, 0, 0.0, a nil pointer, a nil interface value, and
  348. // any empty array, slice, map, or string.
  349. // This behavior is the same as the current (aka v1) encoding/json package
  350. // included in Go.
  351. OmitEmptyGoValue
  352. maxOmitEmptyMode
  353. )
  354. func (om OmitEmptyMode) valid() bool {
  355. return om >= 0 && om < maxOmitEmptyMode
  356. }
  357. // FieldNameMode specifies the CBOR type to use when encoding struct field names.
  358. type FieldNameMode int
  359. const (
  360. // FieldNameToTextString encodes struct fields to CBOR text string (major type 3).
  361. FieldNameToTextString FieldNameMode = iota
  362. // FieldNameToTextString encodes struct fields to CBOR byte string (major type 2).
  363. FieldNameToByteString
  364. maxFieldNameMode
  365. )
  366. func (fnm FieldNameMode) valid() bool {
  367. return fnm >= 0 && fnm < maxFieldNameMode
  368. }
  369. // ByteSliceLaterFormatMode specifies which later format conversion hint (CBOR tag 21-23)
  370. // to include (if any) when encoding Go byte slice to CBOR byte string. The encoder will
  371. // always encode unmodified bytes from the byte slice and just wrap it within
  372. // CBOR tag 21, 22, or 23 if specified.
  373. // See "Expected Later Encoding for CBOR-to-JSON Converters" in RFC 8949 Section 3.4.5.2.
  374. type ByteSliceLaterFormatMode int
  375. const (
  376. // ByteSliceLaterFormatNone encodes unmodified bytes from Go byte slice to CBOR byte string (major type 2)
  377. // without adding CBOR tag 21, 22, or 23.
  378. ByteSliceLaterFormatNone ByteSliceLaterFormatMode = iota
  379. // ByteSliceLaterFormatBase64URL encodes unmodified bytes from Go byte slice to CBOR byte string (major type 2)
  380. // inside CBOR tag 21 (expected later conversion to base64url encoding, see RFC 8949 Section 3.4.5.2).
  381. ByteSliceLaterFormatBase64URL
  382. // ByteSliceLaterFormatBase64 encodes unmodified bytes from Go byte slice to CBOR byte string (major type 2)
  383. // inside CBOR tag 22 (expected later conversion to base64 encoding, see RFC 8949 Section 3.4.5.2).
  384. ByteSliceLaterFormatBase64
  385. // ByteSliceLaterFormatBase16 encodes unmodified bytes from Go byte slice to CBOR byte string (major type 2)
  386. // inside CBOR tag 23 (expected later conversion to base16 encoding, see RFC 8949 Section 3.4.5.2).
  387. ByteSliceLaterFormatBase16
  388. )
  389. func (bsefm ByteSliceLaterFormatMode) encodingTag() (uint64, error) {
  390. switch bsefm {
  391. case ByteSliceLaterFormatNone:
  392. return 0, nil
  393. case ByteSliceLaterFormatBase64URL:
  394. return tagNumExpectedLaterEncodingBase64URL, nil
  395. case ByteSliceLaterFormatBase64:
  396. return tagNumExpectedLaterEncodingBase64, nil
  397. case ByteSliceLaterFormatBase16:
  398. return tagNumExpectedLaterEncodingBase16, nil
  399. }
  400. return 0, errors.New("cbor: invalid ByteSliceLaterFormat " + strconv.Itoa(int(bsefm)))
  401. }
  402. // ByteArrayMode specifies how to encode byte arrays.
  403. type ByteArrayMode int
  404. const (
  405. // ByteArrayToByteSlice encodes byte arrays the same way that a byte slice with identical
  406. // length and contents is encoded.
  407. ByteArrayToByteSlice ByteArrayMode = iota
  408. // ByteArrayToArray encodes byte arrays to the CBOR array type with one unsigned integer
  409. // item for each byte in the array.
  410. ByteArrayToArray
  411. maxByteArrayMode
  412. )
  413. func (bam ByteArrayMode) valid() bool {
  414. return bam >= 0 && bam < maxByteArrayMode
  415. }
  416. // BinaryMarshalerMode specifies how to encode types that implement encoding.BinaryMarshaler.
  417. type BinaryMarshalerMode int
  418. const (
  419. // BinaryMarshalerByteString encodes the output of MarshalBinary to a CBOR byte string.
  420. BinaryMarshalerByteString BinaryMarshalerMode = iota
  421. // BinaryMarshalerNone does not recognize BinaryMarshaler implementations during encode.
  422. BinaryMarshalerNone
  423. maxBinaryMarshalerMode
  424. )
  425. func (bmm BinaryMarshalerMode) valid() bool {
  426. return bmm >= 0 && bmm < maxBinaryMarshalerMode
  427. }
  428. // TextMarshalerMode specifies how to encode types that implement encoding.TextMarshaler.
  429. type TextMarshalerMode int
  430. const (
  431. // TextMarshalerNone does not recognize TextMarshaler implementations during encode.
  432. // This is the default behavior.
  433. TextMarshalerNone TextMarshalerMode = iota
  434. // TextMarshalerTextString encodes the output of MarshalText to a CBOR text string.
  435. TextMarshalerTextString
  436. maxTextMarshalerMode
  437. )
  438. func (tmm TextMarshalerMode) valid() bool {
  439. return tmm >= 0 && tmm < maxTextMarshalerMode
  440. }
  441. // EncOptions specifies encoding options.
  442. type EncOptions struct {
  443. // Sort specifies sorting order.
  444. Sort SortMode
  445. // ShortestFloat specifies the shortest floating-point encoding that preserves
  446. // the value being encoded.
  447. ShortestFloat ShortestFloatMode
  448. // NaNConvert specifies how to encode NaN and it overrides ShortestFloatMode.
  449. NaNConvert NaNConvertMode
  450. // InfConvert specifies how to encode Inf and it overrides ShortestFloatMode.
  451. InfConvert InfConvertMode
  452. // BigIntConvert specifies how to encode big.Int values.
  453. BigIntConvert BigIntConvertMode
  454. // Time specifies how to encode time.Time.
  455. Time TimeMode
  456. // TimeTag allows time.Time to be encoded with a tag number.
  457. // RFC3339 format gets tag number 0, and numeric epoch time tag number 1.
  458. TimeTag EncTagMode
  459. // IndefLength specifies whether to allow indefinite length CBOR items.
  460. IndefLength IndefLengthMode
  461. // NilContainers specifies how to encode nil slices and maps.
  462. NilContainers NilContainersMode
  463. // TagsMd specifies whether to allow CBOR tags (major type 6).
  464. TagsMd TagsMode
  465. // OmitEmptyMode specifies how to encode struct fields with omitempty tag.
  466. OmitEmpty OmitEmptyMode
  467. // String specifies which CBOR type to use when encoding Go strings.
  468. // - CBOR text string (major type 3) is default
  469. // - CBOR byte string (major type 2)
  470. String StringMode
  471. // FieldName specifies the CBOR type to use when encoding struct field names.
  472. FieldName FieldNameMode
  473. // ByteSliceLaterFormat specifies which later format conversion hint (CBOR tag 21-23)
  474. // to include (if any) when encoding Go byte slice to CBOR byte string. The encoder will
  475. // always encode unmodified bytes from the byte slice and just wrap it within
  476. // CBOR tag 21, 22, or 23 if specified.
  477. // See "Expected Later Encoding for CBOR-to-JSON Converters" in RFC 8949 Section 3.4.5.2.
  478. ByteSliceLaterFormat ByteSliceLaterFormatMode
  479. // ByteArray specifies how to encode byte arrays.
  480. ByteArray ByteArrayMode
  481. // BinaryMarshaler specifies how to encode types that implement encoding.BinaryMarshaler.
  482. BinaryMarshaler BinaryMarshalerMode
  483. // TextMarshaler specifies how to encode types that implement encoding.TextMarshaler.
  484. TextMarshaler TextMarshalerMode
  485. // JSONMarshalerTranscoder sets the transcoding scheme used to marshal types that implement
  486. // json.Marshaler but do not also implement cbor.Marshaler. If nil, encoding behavior is not
  487. // influenced by whether or not a type implements json.Marshaler.
  488. JSONMarshalerTranscoder Transcoder
  489. }
  490. // CanonicalEncOptions returns EncOptions for "Canonical CBOR" encoding,
  491. // defined in RFC 7049 Section 3.9 with the following rules:
  492. //
  493. // 1. "Integers must be as small as possible."
  494. // 2. "The expression of lengths in major types 2 through 5 must be as short as possible."
  495. // 3. The keys in every map must be sorted in length-first sorting order.
  496. // See SortLengthFirst for details.
  497. // 4. "Indefinite-length items must be made into definite-length items."
  498. // 5. "If a protocol allows for IEEE floats, then additional canonicalization rules might
  499. // need to be added. One example rule might be to have all floats start as a 64-bit
  500. // float, then do a test conversion to a 32-bit float; if the result is the same numeric
  501. // value, use the shorter value and repeat the process with a test conversion to a
  502. // 16-bit float. (This rule selects 16-bit float for positive and negative Infinity
  503. // as well.) Also, there are many representations for NaN. If NaN is an allowed value,
  504. // it must always be represented as 0xf97e00."
  505. func CanonicalEncOptions() EncOptions {
  506. return EncOptions{
  507. Sort: SortCanonical,
  508. ShortestFloat: ShortestFloat16,
  509. NaNConvert: NaNConvert7e00,
  510. InfConvert: InfConvertFloat16,
  511. IndefLength: IndefLengthForbidden,
  512. }
  513. }
  514. // CTAP2EncOptions returns EncOptions for "CTAP2 Canonical CBOR" encoding,
  515. // defined in CTAP specification, with the following rules:
  516. //
  517. // 1. "Integers must be encoded as small as possible."
  518. // 2. "The representations of any floating-point values are not changed."
  519. // 3. "The expression of lengths in major types 2 through 5 must be as short as possible."
  520. // 4. "Indefinite-length items must be made into definite-length items.""
  521. // 5. The keys in every map must be sorted in bytewise lexicographic order.
  522. // See SortBytewiseLexical for details.
  523. // 6. "Tags as defined in Section 2.4 in [RFC7049] MUST NOT be present."
  524. func CTAP2EncOptions() EncOptions {
  525. return EncOptions{
  526. Sort: SortCTAP2,
  527. ShortestFloat: ShortestFloatNone,
  528. NaNConvert: NaNConvertNone,
  529. InfConvert: InfConvertNone,
  530. IndefLength: IndefLengthForbidden,
  531. TagsMd: TagsForbidden,
  532. }
  533. }
  534. // CoreDetEncOptions returns EncOptions for "Core Deterministic" encoding,
  535. // defined in RFC 7049bis with the following rules:
  536. //
  537. // 1. "Preferred serialization MUST be used. In particular, this means that arguments
  538. // (see Section 3) for integers, lengths in major types 2 through 5, and tags MUST
  539. // be as short as possible"
  540. // "Floating point values also MUST use the shortest form that preserves the value"
  541. // 2. "Indefinite-length items MUST NOT appear."
  542. // 3. "The keys in every map MUST be sorted in the bytewise lexicographic order of
  543. // their deterministic encodings."
  544. func CoreDetEncOptions() EncOptions {
  545. return EncOptions{
  546. Sort: SortCoreDeterministic,
  547. ShortestFloat: ShortestFloat16,
  548. NaNConvert: NaNConvert7e00,
  549. InfConvert: InfConvertFloat16,
  550. IndefLength: IndefLengthForbidden,
  551. }
  552. }
  553. // PreferredUnsortedEncOptions returns EncOptions for "Preferred Serialization" encoding,
  554. // defined in RFC 7049bis with the following rules:
  555. //
  556. // 1. "The preferred serialization always uses the shortest form of representing the argument
  557. // (Section 3);"
  558. // 2. "it also uses the shortest floating-point encoding that preserves the value being
  559. // encoded (see Section 5.5)."
  560. // "The preferred encoding for a floating-point value is the shortest floating-point encoding
  561. // that preserves its value, e.g., 0xf94580 for the number 5.5, and 0xfa45ad9c00 for the
  562. // number 5555.5, unless the CBOR-based protocol specifically excludes the use of the shorter
  563. // floating-point encodings. For NaN values, a shorter encoding is preferred if zero-padding
  564. // the shorter significand towards the right reconstitutes the original NaN value (for many
  565. // applications, the single NaN encoding 0xf97e00 will suffice)."
  566. // 3. "Definite length encoding is preferred whenever the length is known at the time the
  567. // serialization of the item starts."
  568. func PreferredUnsortedEncOptions() EncOptions {
  569. return EncOptions{
  570. Sort: SortNone,
  571. ShortestFloat: ShortestFloat16,
  572. NaNConvert: NaNConvert7e00,
  573. InfConvert: InfConvertFloat16,
  574. }
  575. }
  576. // EncMode returns EncMode with immutable options and no tags (safe for concurrency).
  577. func (opts EncOptions) EncMode() (EncMode, error) { //nolint:gocritic // ignore hugeParam
  578. return opts.encMode()
  579. }
  580. // UserBufferEncMode returns UserBufferEncMode with immutable options and no tags (safe for concurrency).
  581. func (opts EncOptions) UserBufferEncMode() (UserBufferEncMode, error) { //nolint:gocritic // ignore hugeParam
  582. return opts.encMode()
  583. }
  584. // EncModeWithTags returns EncMode with options and tags that are both immutable (safe for concurrency).
  585. func (opts EncOptions) EncModeWithTags(tags TagSet) (EncMode, error) { //nolint:gocritic // ignore hugeParam
  586. return opts.UserBufferEncModeWithTags(tags)
  587. }
  588. // UserBufferEncModeWithTags returns UserBufferEncMode with options and tags that are both immutable (safe for concurrency).
  589. func (opts EncOptions) UserBufferEncModeWithTags(tags TagSet) (UserBufferEncMode, error) { //nolint:gocritic // ignore hugeParam
  590. if opts.TagsMd == TagsForbidden {
  591. return nil, errors.New("cbor: cannot create EncMode with TagSet when TagsMd is TagsForbidden")
  592. }
  593. if tags == nil {
  594. return nil, errors.New("cbor: cannot create EncMode with nil value as TagSet")
  595. }
  596. em, err := opts.encMode()
  597. if err != nil {
  598. return nil, err
  599. }
  600. // Copy tags
  601. ts := tagSet(make(map[reflect.Type]*tagItem))
  602. syncTags := tags.(*syncTagSet)
  603. syncTags.RLock()
  604. for contentType, tag := range syncTags.t {
  605. if tag.opts.EncTag != EncTagNone {
  606. ts[contentType] = tag
  607. }
  608. }
  609. syncTags.RUnlock()
  610. if len(ts) > 0 {
  611. em.tags = ts
  612. }
  613. return em, nil
  614. }
  615. // EncModeWithSharedTags returns EncMode with immutable options and mutable shared tags (safe for concurrency).
  616. func (opts EncOptions) EncModeWithSharedTags(tags TagSet) (EncMode, error) { //nolint:gocritic // ignore hugeParam
  617. return opts.UserBufferEncModeWithSharedTags(tags)
  618. }
  619. // UserBufferEncModeWithSharedTags returns UserBufferEncMode with immutable options and mutable shared tags (safe for concurrency).
  620. func (opts EncOptions) UserBufferEncModeWithSharedTags(tags TagSet) (UserBufferEncMode, error) { //nolint:gocritic // ignore hugeParam
  621. if opts.TagsMd == TagsForbidden {
  622. return nil, errors.New("cbor: cannot create EncMode with TagSet when TagsMd is TagsForbidden")
  623. }
  624. if tags == nil {
  625. return nil, errors.New("cbor: cannot create EncMode with nil value as TagSet")
  626. }
  627. em, err := opts.encMode()
  628. if err != nil {
  629. return nil, err
  630. }
  631. em.tags = tags
  632. return em, nil
  633. }
  634. func (opts EncOptions) encMode() (*encMode, error) { //nolint:gocritic // ignore hugeParam
  635. if !opts.Sort.valid() {
  636. return nil, errors.New("cbor: invalid SortMode " + strconv.Itoa(int(opts.Sort)))
  637. }
  638. if !opts.ShortestFloat.valid() {
  639. return nil, errors.New("cbor: invalid ShortestFloatMode " + strconv.Itoa(int(opts.ShortestFloat)))
  640. }
  641. if !opts.NaNConvert.valid() {
  642. return nil, errors.New("cbor: invalid NaNConvertMode " + strconv.Itoa(int(opts.NaNConvert)))
  643. }
  644. if !opts.InfConvert.valid() {
  645. return nil, errors.New("cbor: invalid InfConvertMode " + strconv.Itoa(int(opts.InfConvert)))
  646. }
  647. if !opts.BigIntConvert.valid() {
  648. return nil, errors.New("cbor: invalid BigIntConvertMode " + strconv.Itoa(int(opts.BigIntConvert)))
  649. }
  650. if !opts.Time.valid() {
  651. return nil, errors.New("cbor: invalid TimeMode " + strconv.Itoa(int(opts.Time)))
  652. }
  653. if !opts.TimeTag.valid() {
  654. return nil, errors.New("cbor: invalid TimeTag " + strconv.Itoa(int(opts.TimeTag)))
  655. }
  656. if !opts.IndefLength.valid() {
  657. return nil, errors.New("cbor: invalid IndefLength " + strconv.Itoa(int(opts.IndefLength)))
  658. }
  659. if !opts.NilContainers.valid() {
  660. return nil, errors.New("cbor: invalid NilContainers " + strconv.Itoa(int(opts.NilContainers)))
  661. }
  662. if !opts.TagsMd.valid() {
  663. return nil, errors.New("cbor: invalid TagsMd " + strconv.Itoa(int(opts.TagsMd)))
  664. }
  665. if opts.TagsMd == TagsForbidden && opts.TimeTag == EncTagRequired {
  666. return nil, errors.New("cbor: cannot set TagsMd to TagsForbidden when TimeTag is EncTagRequired")
  667. }
  668. if !opts.OmitEmpty.valid() {
  669. return nil, errors.New("cbor: invalid OmitEmpty " + strconv.Itoa(int(opts.OmitEmpty)))
  670. }
  671. stringMajorType, err := opts.String.cborType()
  672. if err != nil {
  673. return nil, err
  674. }
  675. if !opts.FieldName.valid() {
  676. return nil, errors.New("cbor: invalid FieldName " + strconv.Itoa(int(opts.FieldName)))
  677. }
  678. byteSliceLaterEncodingTag, err := opts.ByteSliceLaterFormat.encodingTag()
  679. if err != nil {
  680. return nil, err
  681. }
  682. if !opts.ByteArray.valid() {
  683. return nil, errors.New("cbor: invalid ByteArray " + strconv.Itoa(int(opts.ByteArray)))
  684. }
  685. if !opts.BinaryMarshaler.valid() {
  686. return nil, errors.New("cbor: invalid BinaryMarshaler " + strconv.Itoa(int(opts.BinaryMarshaler)))
  687. }
  688. if !opts.TextMarshaler.valid() {
  689. return nil, errors.New("cbor: invalid TextMarshaler " + strconv.Itoa(int(opts.TextMarshaler)))
  690. }
  691. em := encMode{
  692. sort: opts.Sort,
  693. shortestFloat: opts.ShortestFloat,
  694. nanConvert: opts.NaNConvert,
  695. infConvert: opts.InfConvert,
  696. bigIntConvert: opts.BigIntConvert,
  697. time: opts.Time,
  698. timeTag: opts.TimeTag,
  699. indefLength: opts.IndefLength,
  700. nilContainers: opts.NilContainers,
  701. tagsMd: opts.TagsMd,
  702. omitEmpty: opts.OmitEmpty,
  703. stringType: opts.String,
  704. stringMajorType: stringMajorType,
  705. fieldName: opts.FieldName,
  706. byteSliceLaterFormat: opts.ByteSliceLaterFormat,
  707. byteSliceLaterEncodingTag: byteSliceLaterEncodingTag,
  708. byteArray: opts.ByteArray,
  709. binaryMarshaler: opts.BinaryMarshaler,
  710. textMarshaler: opts.TextMarshaler,
  711. jsonMarshalerTranscoder: opts.JSONMarshalerTranscoder,
  712. }
  713. return &em, nil
  714. }
  715. // EncMode is the main interface for CBOR encoding.
  716. type EncMode interface {
  717. Marshal(v any) ([]byte, error)
  718. NewEncoder(w io.Writer) *Encoder
  719. EncOptions() EncOptions
  720. }
  721. // UserBufferEncMode is an interface for CBOR encoding, which extends EncMode by
  722. // adding MarshalToBuffer to support user specified buffer rather than encoding
  723. // into the built-in buffer pool.
  724. type UserBufferEncMode interface {
  725. EncMode
  726. MarshalToBuffer(v any, buf *bytes.Buffer) error
  727. // This private method is to prevent users implementing
  728. // this interface and so future additions to it will
  729. // not be breaking changes.
  730. // See https://go.dev/blog/module-compatibility
  731. unexport()
  732. }
  733. type encMode struct {
  734. tags tagProvider
  735. sort SortMode
  736. shortestFloat ShortestFloatMode
  737. nanConvert NaNConvertMode
  738. infConvert InfConvertMode
  739. bigIntConvert BigIntConvertMode
  740. time TimeMode
  741. timeTag EncTagMode
  742. indefLength IndefLengthMode
  743. nilContainers NilContainersMode
  744. tagsMd TagsMode
  745. omitEmpty OmitEmptyMode
  746. stringType StringMode
  747. stringMajorType cborType
  748. fieldName FieldNameMode
  749. byteSliceLaterFormat ByteSliceLaterFormatMode
  750. byteSliceLaterEncodingTag uint64
  751. byteArray ByteArrayMode
  752. binaryMarshaler BinaryMarshalerMode
  753. textMarshaler TextMarshalerMode
  754. jsonMarshalerTranscoder Transcoder
  755. }
  756. var defaultEncMode, _ = EncOptions{}.encMode()
  757. // These four decoding modes are used by getMarshalerDecMode.
  758. // maxNestedLevels, maxArrayElements, and maxMapPairs are
  759. // set to max allowed limits to avoid rejecting Marshaler
  760. // output that would have been the allowable output of a
  761. // non-Marshaler object that exceeds default limits.
  762. var (
  763. marshalerForbidIndefLengthForbidTagsDecMode = decMode{
  764. maxNestedLevels: maxMaxNestedLevels,
  765. maxArrayElements: maxMaxArrayElements,
  766. maxMapPairs: maxMaxMapPairs,
  767. indefLength: IndefLengthForbidden,
  768. tagsMd: TagsForbidden,
  769. }
  770. marshalerAllowIndefLengthForbidTagsDecMode = decMode{
  771. maxNestedLevels: maxMaxNestedLevels,
  772. maxArrayElements: maxMaxArrayElements,
  773. maxMapPairs: maxMaxMapPairs,
  774. indefLength: IndefLengthAllowed,
  775. tagsMd: TagsForbidden,
  776. }
  777. marshalerForbidIndefLengthAllowTagsDecMode = decMode{
  778. maxNestedLevels: maxMaxNestedLevels,
  779. maxArrayElements: maxMaxArrayElements,
  780. maxMapPairs: maxMaxMapPairs,
  781. indefLength: IndefLengthForbidden,
  782. tagsMd: TagsAllowed,
  783. }
  784. marshalerAllowIndefLengthAllowTagsDecMode = decMode{
  785. maxNestedLevels: maxMaxNestedLevels,
  786. maxArrayElements: maxMaxArrayElements,
  787. maxMapPairs: maxMaxMapPairs,
  788. indefLength: IndefLengthAllowed,
  789. tagsMd: TagsAllowed,
  790. }
  791. )
  792. // getMarshalerDecMode returns one of four existing decoding modes
  793. // which can be reused (safe for parallel use) for the purpose of
  794. // checking if data returned by Marshaler is well-formed.
  795. func getMarshalerDecMode(indefLength IndefLengthMode, tagsMd TagsMode) *decMode {
  796. switch {
  797. case indefLength == IndefLengthAllowed && tagsMd == TagsAllowed:
  798. return &marshalerAllowIndefLengthAllowTagsDecMode
  799. case indefLength == IndefLengthAllowed && tagsMd == TagsForbidden:
  800. return &marshalerAllowIndefLengthForbidTagsDecMode
  801. case indefLength == IndefLengthForbidden && tagsMd == TagsAllowed:
  802. return &marshalerForbidIndefLengthAllowTagsDecMode
  803. case indefLength == IndefLengthForbidden && tagsMd == TagsForbidden:
  804. return &marshalerForbidIndefLengthForbidTagsDecMode
  805. default:
  806. // This should never happen, unless we add new options to
  807. // IndefLengthMode or TagsMode without updating this function.
  808. return &decMode{
  809. maxNestedLevels: maxMaxNestedLevels,
  810. maxArrayElements: maxMaxArrayElements,
  811. maxMapPairs: maxMaxMapPairs,
  812. indefLength: indefLength,
  813. tagsMd: tagsMd,
  814. }
  815. }
  816. }
  817. // EncOptions returns user specified options used to create this EncMode.
  818. func (em *encMode) EncOptions() EncOptions {
  819. return EncOptions{
  820. Sort: em.sort,
  821. ShortestFloat: em.shortestFloat,
  822. NaNConvert: em.nanConvert,
  823. InfConvert: em.infConvert,
  824. BigIntConvert: em.bigIntConvert,
  825. Time: em.time,
  826. TimeTag: em.timeTag,
  827. IndefLength: em.indefLength,
  828. NilContainers: em.nilContainers,
  829. TagsMd: em.tagsMd,
  830. OmitEmpty: em.omitEmpty,
  831. String: em.stringType,
  832. FieldName: em.fieldName,
  833. ByteSliceLaterFormat: em.byteSliceLaterFormat,
  834. ByteArray: em.byteArray,
  835. BinaryMarshaler: em.binaryMarshaler,
  836. TextMarshaler: em.textMarshaler,
  837. JSONMarshalerTranscoder: em.jsonMarshalerTranscoder,
  838. }
  839. }
  840. func (em *encMode) unexport() {}
  841. func (em *encMode) encTagBytes(t reflect.Type) []byte {
  842. if em.tags != nil {
  843. if tagItem := em.tags.getTagItemFromType(t); tagItem != nil {
  844. return tagItem.cborTagNum
  845. }
  846. }
  847. return nil
  848. }
  849. // Marshal returns the CBOR encoding of v using em encoding mode.
  850. //
  851. // See the documentation for Marshal for details.
  852. func (em *encMode) Marshal(v any) ([]byte, error) {
  853. e := getEncodeBuffer()
  854. if err := encode(e, em, reflect.ValueOf(v)); err != nil {
  855. putEncodeBuffer(e)
  856. return nil, err
  857. }
  858. buf := make([]byte, e.Len())
  859. copy(buf, e.Bytes())
  860. putEncodeBuffer(e)
  861. return buf, nil
  862. }
  863. // MarshalToBuffer encodes v into provided buffer (instead of using built-in buffer pool)
  864. // and uses em encoding mode.
  865. //
  866. // NOTE: Unlike Marshal, the buffer provided to MarshalToBuffer can contain
  867. // partially encoded data if error is returned.
  868. //
  869. // See Marshal for more details.
  870. func (em *encMode) MarshalToBuffer(v any, buf *bytes.Buffer) error {
  871. if buf == nil {
  872. return fmt.Errorf("cbor: encoding buffer provided by user is nil")
  873. }
  874. return encode(buf, em, reflect.ValueOf(v))
  875. }
  876. // NewEncoder returns a new encoder that writes to w using em EncMode.
  877. func (em *encMode) NewEncoder(w io.Writer) *Encoder {
  878. return &Encoder{w: w, em: em}
  879. }
  880. // encodeBufferPool caches unused bytes.Buffer objects for later reuse.
  881. var encodeBufferPool = sync.Pool{
  882. New: func() any {
  883. e := new(bytes.Buffer)
  884. e.Grow(32) // TODO: make this configurable
  885. return e
  886. },
  887. }
  888. func getEncodeBuffer() *bytes.Buffer {
  889. return encodeBufferPool.Get().(*bytes.Buffer)
  890. }
  891. func putEncodeBuffer(e *bytes.Buffer) {
  892. e.Reset()
  893. encodeBufferPool.Put(e)
  894. }
  895. type encodeFunc func(e *bytes.Buffer, em *encMode, v reflect.Value) error
  896. type isEmptyFunc func(em *encMode, v reflect.Value) (empty bool, err error)
  897. type isZeroFunc func(v reflect.Value) (zero bool, err error)
  898. func encode(e *bytes.Buffer, em *encMode, v reflect.Value) error {
  899. if !v.IsValid() {
  900. // v is zero value
  901. e.Write(cborNil)
  902. return nil
  903. }
  904. vt := v.Type()
  905. f, _, _ := getEncodeFunc(vt)
  906. if f == nil {
  907. return &UnsupportedTypeError{vt}
  908. }
  909. return f(e, em, v)
  910. }
  911. func encodeBool(e *bytes.Buffer, em *encMode, v reflect.Value) error {
  912. if b := em.encTagBytes(v.Type()); b != nil {
  913. e.Write(b)
  914. }
  915. b := cborFalse
  916. if v.Bool() {
  917. b = cborTrue
  918. }
  919. e.Write(b)
  920. return nil
  921. }
  922. func encodeInt(e *bytes.Buffer, em *encMode, v reflect.Value) error {
  923. if b := em.encTagBytes(v.Type()); b != nil {
  924. e.Write(b)
  925. }
  926. i := v.Int()
  927. if i >= 0 {
  928. encodeHead(e, byte(cborTypePositiveInt), uint64(i))
  929. return nil
  930. }
  931. i = i*(-1) - 1
  932. encodeHead(e, byte(cborTypeNegativeInt), uint64(i))
  933. return nil
  934. }
  935. func encodeUint(e *bytes.Buffer, em *encMode, v reflect.Value) error {
  936. if b := em.encTagBytes(v.Type()); b != nil {
  937. e.Write(b)
  938. }
  939. encodeHead(e, byte(cborTypePositiveInt), v.Uint())
  940. return nil
  941. }
  942. func encodeFloat(e *bytes.Buffer, em *encMode, v reflect.Value) error {
  943. if b := em.encTagBytes(v.Type()); b != nil {
  944. e.Write(b)
  945. }
  946. f64 := v.Float()
  947. if math.IsNaN(f64) {
  948. return encodeNaN(e, em, v)
  949. }
  950. if math.IsInf(f64, 0) {
  951. return encodeInf(e, em, v)
  952. }
  953. fopt := em.shortestFloat
  954. if v.Kind() == reflect.Float64 && (fopt == ShortestFloatNone || cannotFitFloat32(f64)) {
  955. // Encode float64
  956. // Don't use encodeFloat64() because it cannot be inlined.
  957. const argumentSize = 8
  958. const headSize = 1 + argumentSize
  959. var scratch [headSize]byte
  960. scratch[0] = byte(cborTypePrimitives) | byte(additionalInformationAsFloat64)
  961. binary.BigEndian.PutUint64(scratch[1:], math.Float64bits(f64))
  962. e.Write(scratch[:])
  963. return nil
  964. }
  965. f32 := float32(f64)
  966. if fopt == ShortestFloat16 {
  967. var f16 float16.Float16
  968. p := float16.PrecisionFromfloat32(f32)
  969. if p == float16.PrecisionExact {
  970. // Roundtrip float32->float16->float32 test isn't needed.
  971. f16 = float16.Fromfloat32(f32)
  972. } else if p == float16.PrecisionUnknown {
  973. // Try roundtrip float32->float16->float32 to determine if float32 can fit into float16.
  974. f16 = float16.Fromfloat32(f32)
  975. if f16.Float32() == f32 {
  976. p = float16.PrecisionExact
  977. }
  978. }
  979. if p == float16.PrecisionExact {
  980. // Encode float16
  981. // Don't use encodeFloat16() because it cannot be inlined.
  982. const argumentSize = 2
  983. const headSize = 1 + argumentSize
  984. var scratch [headSize]byte
  985. scratch[0] = byte(cborTypePrimitives) | additionalInformationAsFloat16
  986. binary.BigEndian.PutUint16(scratch[1:], uint16(f16))
  987. e.Write(scratch[:])
  988. return nil
  989. }
  990. }
  991. // Encode float32
  992. // Don't use encodeFloat32() because it cannot be inlined.
  993. const argumentSize = 4
  994. const headSize = 1 + argumentSize
  995. var scratch [headSize]byte
  996. scratch[0] = byte(cborTypePrimitives) | additionalInformationAsFloat32
  997. binary.BigEndian.PutUint32(scratch[1:], math.Float32bits(f32))
  998. e.Write(scratch[:])
  999. return nil
  1000. }
  1001. func encodeInf(e *bytes.Buffer, em *encMode, v reflect.Value) error {
  1002. f64 := v.Float()
  1003. switch em.infConvert {
  1004. case InfConvertReject:
  1005. return &UnsupportedValueError{msg: "floating-point infinity"}
  1006. case InfConvertFloat16:
  1007. if f64 > 0 {
  1008. e.Write(cborPositiveInfinity)
  1009. } else {
  1010. e.Write(cborNegativeInfinity)
  1011. }
  1012. return nil
  1013. }
  1014. if v.Kind() == reflect.Float64 {
  1015. return encodeFloat64(e, f64)
  1016. }
  1017. return encodeFloat32(e, float32(f64))
  1018. }
  1019. func encodeNaN(e *bytes.Buffer, em *encMode, v reflect.Value) error {
  1020. switch em.nanConvert {
  1021. case NaNConvert7e00:
  1022. e.Write(cborNaN)
  1023. return nil
  1024. case NaNConvertNone:
  1025. if v.Kind() == reflect.Float64 {
  1026. return encodeFloat64(e, v.Float())
  1027. }
  1028. f32 := float32NaNFromReflectValue(v)
  1029. return encodeFloat32(e, f32)
  1030. case NaNConvertReject:
  1031. return &UnsupportedValueError{msg: "floating-point NaN"}
  1032. default: // NaNConvertPreserveSignal, NaNConvertQuiet
  1033. if v.Kind() == reflect.Float64 {
  1034. f64 := v.Float()
  1035. f64bits := math.Float64bits(f64)
  1036. if em.nanConvert == NaNConvertQuiet && f64bits&(1<<51) == 0 {
  1037. f64bits |= 1 << 51 // Set quiet bit = 1
  1038. f64 = math.Float64frombits(f64bits)
  1039. }
  1040. // The lower 29 bits are dropped when converting from float64 to float32.
  1041. if f64bits&0x1fffffff != 0 {
  1042. // Encode NaN as float64 because dropped coef bits from float64 to float32 are not all 0s.
  1043. return encodeFloat64(e, f64)
  1044. }
  1045. // Create float32 from float64 manually because float32(f64) always turns on NaN's quiet bits.
  1046. sign := uint32(f64bits>>32) & (1 << 31)
  1047. exp := uint32(0x7f800000)
  1048. coef := uint32((f64bits & 0xfffffffffffff) >> 29)
  1049. f32bits := sign | exp | coef
  1050. f32 := math.Float32frombits(f32bits)
  1051. // The lower 13 bits are dropped when converting from float32 to float16.
  1052. if f32bits&0x1fff != 0 {
  1053. // Encode NaN as float32 because dropped coef bits from float32 to float16 are not all 0s.
  1054. return encodeFloat32(e, f32)
  1055. }
  1056. // Encode NaN as float16
  1057. f16, _ := float16.FromNaN32ps(f32) // Ignore err because it only returns error when f32 is not a NaN.
  1058. return encodeFloat16(e, f16)
  1059. }
  1060. f32 := float32NaNFromReflectValue(v)
  1061. f32bits := math.Float32bits(f32)
  1062. if em.nanConvert == NaNConvertQuiet && f32bits&(1<<22) == 0 {
  1063. f32bits |= 1 << 22 // Set quiet bit = 1
  1064. f32 = math.Float32frombits(f32bits)
  1065. }
  1066. // The lower 13 bits are dropped coef bits when converting from float32 to float16.
  1067. if f32bits&0x1fff != 0 {
  1068. // Encode NaN as float32 because dropped coef bits from float32 to float16 are not all 0s.
  1069. return encodeFloat32(e, f32)
  1070. }
  1071. f16, _ := float16.FromNaN32ps(f32) // Ignore err because it only returns error when f32 is not a NaN.
  1072. return encodeFloat16(e, f16)
  1073. }
  1074. }
  1075. func encodeFloat16(e *bytes.Buffer, f16 float16.Float16) error {
  1076. const argumentSize = 2
  1077. const headSize = 1 + argumentSize
  1078. var scratch [headSize]byte
  1079. scratch[0] = byte(cborTypePrimitives) | additionalInformationAsFloat16
  1080. binary.BigEndian.PutUint16(scratch[1:], uint16(f16))
  1081. e.Write(scratch[:])
  1082. return nil
  1083. }
  1084. func encodeFloat32(e *bytes.Buffer, f32 float32) error {
  1085. const argumentSize = 4
  1086. const headSize = 1 + argumentSize
  1087. var scratch [headSize]byte
  1088. scratch[0] = byte(cborTypePrimitives) | additionalInformationAsFloat32
  1089. binary.BigEndian.PutUint32(scratch[1:], math.Float32bits(f32))
  1090. e.Write(scratch[:])
  1091. return nil
  1092. }
  1093. func encodeFloat64(e *bytes.Buffer, f64 float64) error {
  1094. const argumentSize = 8
  1095. const headSize = 1 + argumentSize
  1096. var scratch [headSize]byte
  1097. scratch[0] = byte(cborTypePrimitives) | additionalInformationAsFloat64
  1098. binary.BigEndian.PutUint64(scratch[1:], math.Float64bits(f64))
  1099. e.Write(scratch[:])
  1100. return nil
  1101. }
  1102. func encodeByteString(e *bytes.Buffer, em *encMode, v reflect.Value) error {
  1103. vk := v.Kind()
  1104. if vk == reflect.Slice && v.IsNil() && em.nilContainers == NilContainerAsNull {
  1105. e.Write(cborNil)
  1106. return nil
  1107. }
  1108. if vk == reflect.Slice && v.Type().Elem().Kind() == reflect.Uint8 && em.byteSliceLaterEncodingTag != 0 {
  1109. encodeHead(e, byte(cborTypeTag), em.byteSliceLaterEncodingTag)
  1110. }
  1111. if b := em.encTagBytes(v.Type()); b != nil {
  1112. e.Write(b)
  1113. }
  1114. slen := v.Len()
  1115. if slen == 0 {
  1116. return e.WriteByte(byte(cborTypeByteString))
  1117. }
  1118. encodeHead(e, byte(cborTypeByteString), uint64(slen))
  1119. if vk == reflect.Array {
  1120. for i := 0; i < slen; i++ {
  1121. e.WriteByte(byte(v.Index(i).Uint()))
  1122. }
  1123. return nil
  1124. }
  1125. e.Write(v.Bytes())
  1126. return nil
  1127. }
  1128. func encodeString(e *bytes.Buffer, em *encMode, v reflect.Value) error {
  1129. if b := em.encTagBytes(v.Type()); b != nil {
  1130. e.Write(b)
  1131. }
  1132. s := v.String()
  1133. encodeHead(e, byte(em.stringMajorType), uint64(len(s)))
  1134. e.WriteString(s)
  1135. return nil
  1136. }
  1137. type arrayEncodeFunc struct {
  1138. f encodeFunc
  1139. }
  1140. func (ae arrayEncodeFunc) encode(e *bytes.Buffer, em *encMode, v reflect.Value) error {
  1141. if em.byteArray == ByteArrayToByteSlice && v.Type().Elem().Kind() == reflect.Uint8 {
  1142. return encodeByteString(e, em, v)
  1143. }
  1144. if v.Kind() == reflect.Slice && v.IsNil() && em.nilContainers == NilContainerAsNull {
  1145. e.Write(cborNil)
  1146. return nil
  1147. }
  1148. if b := em.encTagBytes(v.Type()); b != nil {
  1149. e.Write(b)
  1150. }
  1151. alen := v.Len()
  1152. if alen == 0 {
  1153. return e.WriteByte(byte(cborTypeArray))
  1154. }
  1155. encodeHead(e, byte(cborTypeArray), uint64(alen))
  1156. for i := 0; i < alen; i++ {
  1157. if err := ae.f(e, em, v.Index(i)); err != nil {
  1158. return err
  1159. }
  1160. }
  1161. return nil
  1162. }
  1163. // encodeKeyValueFunc encodes key/value pairs in map (v).
  1164. // If kvs is provided (having the same length as v), length of encoded key and value are stored in kvs.
  1165. // kvs is used for canonical encoding of map.
  1166. type encodeKeyValueFunc func(e *bytes.Buffer, em *encMode, v reflect.Value, kvs []keyValue) error
  1167. type mapEncodeFunc struct {
  1168. e encodeKeyValueFunc
  1169. }
  1170. func (me mapEncodeFunc) encode(e *bytes.Buffer, em *encMode, v reflect.Value) error {
  1171. if v.IsNil() && em.nilContainers == NilContainerAsNull {
  1172. e.Write(cborNil)
  1173. return nil
  1174. }
  1175. if b := em.encTagBytes(v.Type()); b != nil {
  1176. e.Write(b)
  1177. }
  1178. mlen := v.Len()
  1179. if mlen == 0 {
  1180. return e.WriteByte(byte(cborTypeMap))
  1181. }
  1182. encodeHead(e, byte(cborTypeMap), uint64(mlen))
  1183. if em.sort == SortNone || em.sort == SortFastShuffle || mlen <= 1 {
  1184. return me.e(e, em, v, nil)
  1185. }
  1186. kvsp := getKeyValues(v.Len()) // for sorting keys
  1187. defer putKeyValues(kvsp)
  1188. kvs := *kvsp
  1189. kvBeginOffset := e.Len()
  1190. if err := me.e(e, em, v, kvs); err != nil {
  1191. return err
  1192. }
  1193. kvTotalLen := e.Len() - kvBeginOffset
  1194. // Use the capacity at the tail of the encode buffer as a staging area to rearrange the
  1195. // encoded pairs into sorted order.
  1196. e.Grow(kvTotalLen)
  1197. tmp := e.Bytes()[e.Len() : e.Len()+kvTotalLen] // Can use e.AvailableBuffer() in Go 1.21+.
  1198. dst := e.Bytes()[kvBeginOffset:]
  1199. if em.sort == SortBytewiseLexical {
  1200. sort.Sort(&bytewiseKeyValueSorter{kvs: kvs, data: dst})
  1201. } else {
  1202. sort.Sort(&lengthFirstKeyValueSorter{kvs: kvs, data: dst})
  1203. }
  1204. // This is where the encoded bytes are actually rearranged in the output buffer to reflect
  1205. // the desired order.
  1206. sortedOffset := 0
  1207. for _, kv := range kvs {
  1208. copy(tmp[sortedOffset:], dst[kv.offset:kv.nextOffset])
  1209. sortedOffset += kv.nextOffset - kv.offset
  1210. }
  1211. copy(dst, tmp[:kvTotalLen])
  1212. return nil
  1213. }
  1214. // keyValue is the position of an encoded pair in a buffer. All offsets are zero-based and relative
  1215. // to the first byte of the first encoded pair.
  1216. type keyValue struct {
  1217. offset int
  1218. valueOffset int
  1219. nextOffset int
  1220. }
  1221. type bytewiseKeyValueSorter struct {
  1222. kvs []keyValue
  1223. data []byte
  1224. }
  1225. func (x *bytewiseKeyValueSorter) Len() int {
  1226. return len(x.kvs)
  1227. }
  1228. func (x *bytewiseKeyValueSorter) Swap(i, j int) {
  1229. x.kvs[i], x.kvs[j] = x.kvs[j], x.kvs[i]
  1230. }
  1231. func (x *bytewiseKeyValueSorter) Less(i, j int) bool {
  1232. kvi, kvj := x.kvs[i], x.kvs[j]
  1233. return bytes.Compare(x.data[kvi.offset:kvi.valueOffset], x.data[kvj.offset:kvj.valueOffset]) <= 0
  1234. }
  1235. type lengthFirstKeyValueSorter struct {
  1236. kvs []keyValue
  1237. data []byte
  1238. }
  1239. func (x *lengthFirstKeyValueSorter) Len() int {
  1240. return len(x.kvs)
  1241. }
  1242. func (x *lengthFirstKeyValueSorter) Swap(i, j int) {
  1243. x.kvs[i], x.kvs[j] = x.kvs[j], x.kvs[i]
  1244. }
  1245. func (x *lengthFirstKeyValueSorter) Less(i, j int) bool {
  1246. kvi, kvj := x.kvs[i], x.kvs[j]
  1247. if keyLengthDifference := (kvi.valueOffset - kvi.offset) - (kvj.valueOffset - kvj.offset); keyLengthDifference != 0 {
  1248. return keyLengthDifference < 0
  1249. }
  1250. return bytes.Compare(x.data[kvi.offset:kvi.valueOffset], x.data[kvj.offset:kvj.valueOffset]) <= 0
  1251. }
  1252. var keyValuePool = sync.Pool{}
  1253. func getKeyValues(length int) *[]keyValue {
  1254. v := keyValuePool.Get()
  1255. if v == nil {
  1256. y := make([]keyValue, length)
  1257. return &y
  1258. }
  1259. x := v.(*[]keyValue)
  1260. if cap(*x) >= length {
  1261. *x = (*x)[:length]
  1262. return x
  1263. }
  1264. // []keyValue from the pool does not have enough capacity.
  1265. // Return it back to the pool and create a new one.
  1266. keyValuePool.Put(x)
  1267. y := make([]keyValue, length)
  1268. return &y
  1269. }
  1270. func putKeyValues(x *[]keyValue) {
  1271. *x = (*x)[:0]
  1272. keyValuePool.Put(x)
  1273. }
  1274. func encodeStructToArray(e *bytes.Buffer, em *encMode, v reflect.Value) (err error) {
  1275. structType, err := getEncodingStructType(v.Type())
  1276. if err != nil {
  1277. return err
  1278. }
  1279. if b := em.encTagBytes(v.Type()); b != nil {
  1280. e.Write(b)
  1281. }
  1282. flds := structType.fields
  1283. encodeHead(e, byte(cborTypeArray), uint64(len(flds)))
  1284. for i := 0; i < len(flds); i++ {
  1285. f := flds[i]
  1286. var fv reflect.Value
  1287. if len(f.idx) == 1 {
  1288. fv = v.Field(f.idx[0])
  1289. } else {
  1290. // Get embedded field value. No error is expected.
  1291. fv, _ = getFieldValue(v, f.idx, func(reflect.Value) (reflect.Value, error) {
  1292. // Write CBOR nil for null pointer to embedded struct
  1293. e.Write(cborNil)
  1294. return reflect.Value{}, nil
  1295. })
  1296. if !fv.IsValid() {
  1297. continue
  1298. }
  1299. }
  1300. if err := f.ef(e, em, fv); err != nil {
  1301. return err
  1302. }
  1303. }
  1304. return nil
  1305. }
  1306. func encodeStruct(e *bytes.Buffer, em *encMode, v reflect.Value) (err error) {
  1307. structType, err := getEncodingStructType(v.Type())
  1308. if err != nil {
  1309. return err
  1310. }
  1311. flds := structType.getFields(em)
  1312. start := 0
  1313. if em.sort == SortFastShuffle && len(flds) > 0 {
  1314. start = rand.Intn(len(flds)) //nolint:gosec // Don't need a CSPRNG for deck cutting.
  1315. }
  1316. if b := em.encTagBytes(v.Type()); b != nil {
  1317. e.Write(b)
  1318. }
  1319. // Encode head with struct field count.
  1320. // Head is rewritten later if actual encoded field count is different from struct field count.
  1321. encodedHeadLen := encodeHead(e, byte(cborTypeMap), uint64(len(flds)))
  1322. kvbegin := e.Len()
  1323. kvcount := 0
  1324. for offset := 0; offset < len(flds); offset++ {
  1325. f := flds[(start+offset)%len(flds)]
  1326. var fv reflect.Value
  1327. if len(f.idx) == 1 {
  1328. fv = v.Field(f.idx[0])
  1329. } else {
  1330. // Get embedded field value. No error is expected.
  1331. fv, _ = getFieldValue(v, f.idx, func(reflect.Value) (reflect.Value, error) {
  1332. // Skip null pointer to embedded struct
  1333. return reflect.Value{}, nil
  1334. })
  1335. if !fv.IsValid() {
  1336. continue
  1337. }
  1338. }
  1339. if f.omitEmpty {
  1340. empty, err := f.ief(em, fv)
  1341. if err != nil {
  1342. return err
  1343. }
  1344. if empty {
  1345. continue
  1346. }
  1347. }
  1348. if f.omitZero {
  1349. zero, err := f.izf(fv)
  1350. if err != nil {
  1351. return err
  1352. }
  1353. if zero {
  1354. continue
  1355. }
  1356. }
  1357. if !f.keyAsInt && em.fieldName == FieldNameToByteString {
  1358. e.Write(f.cborNameByteString)
  1359. } else { // int or text string
  1360. e.Write(f.cborName)
  1361. }
  1362. if err := f.ef(e, em, fv); err != nil {
  1363. return err
  1364. }
  1365. kvcount++
  1366. }
  1367. if len(flds) == kvcount {
  1368. // Encoded element count in head is the same as actual element count.
  1369. return nil
  1370. }
  1371. // Overwrite the bytes that were reserved for the head before encoding the map entries.
  1372. var actualHeadLen int
  1373. {
  1374. headbuf := *bytes.NewBuffer(e.Bytes()[kvbegin-encodedHeadLen : kvbegin-encodedHeadLen : kvbegin])
  1375. actualHeadLen = encodeHead(&headbuf, byte(cborTypeMap), uint64(kvcount))
  1376. }
  1377. if actualHeadLen == encodedHeadLen {
  1378. // The bytes reserved for the encoded head were exactly the right size, so the
  1379. // encoded entries are already in their final positions.
  1380. return nil
  1381. }
  1382. // We reserved more bytes than needed for the encoded head, based on the number of fields
  1383. // encoded. The encoded entries are offset to the right by the number of excess reserved
  1384. // bytes. Shift the entries left to remove the gap.
  1385. excessReservedBytes := encodedHeadLen - actualHeadLen
  1386. dst := e.Bytes()[kvbegin-excessReservedBytes : e.Len()-excessReservedBytes]
  1387. src := e.Bytes()[kvbegin:e.Len()]
  1388. copy(dst, src)
  1389. // After shifting, the excess bytes are at the end of the output buffer and they are
  1390. // garbage.
  1391. e.Truncate(e.Len() - excessReservedBytes)
  1392. return nil
  1393. }
  1394. func encodeIntf(e *bytes.Buffer, em *encMode, v reflect.Value) error {
  1395. if v.IsNil() {
  1396. e.Write(cborNil)
  1397. return nil
  1398. }
  1399. return encode(e, em, v.Elem())
  1400. }
  1401. func encodeTime(e *bytes.Buffer, em *encMode, v reflect.Value) error {
  1402. t := v.Interface().(time.Time)
  1403. if t.IsZero() {
  1404. e.Write(cborNil) // Even if tag is required, encode as CBOR null.
  1405. return nil
  1406. }
  1407. if em.timeTag == EncTagRequired {
  1408. tagNumber := 1
  1409. if em.time == TimeRFC3339 || em.time == TimeRFC3339Nano {
  1410. tagNumber = 0
  1411. }
  1412. encodeHead(e, byte(cborTypeTag), uint64(tagNumber))
  1413. }
  1414. switch em.time {
  1415. case TimeUnix:
  1416. secs := t.Unix()
  1417. return encodeInt(e, em, reflect.ValueOf(secs))
  1418. case TimeUnixMicro:
  1419. t = t.UTC().Round(time.Microsecond)
  1420. f := float64(t.UnixNano()) / 1e9
  1421. return encodeFloat(e, em, reflect.ValueOf(f))
  1422. case TimeUnixDynamic:
  1423. t = t.UTC().Round(time.Microsecond)
  1424. secs, nsecs := t.Unix(), uint64(t.Nanosecond())
  1425. if nsecs == 0 {
  1426. return encodeInt(e, em, reflect.ValueOf(secs))
  1427. }
  1428. f := float64(secs) + float64(nsecs)/1e9
  1429. return encodeFloat(e, em, reflect.ValueOf(f))
  1430. case TimeRFC3339:
  1431. s := t.Format(time.RFC3339)
  1432. return encodeString(e, em, reflect.ValueOf(s))
  1433. default: // TimeRFC3339Nano
  1434. s := t.Format(time.RFC3339Nano)
  1435. return encodeString(e, em, reflect.ValueOf(s))
  1436. }
  1437. }
  1438. func encodeBigInt(e *bytes.Buffer, em *encMode, v reflect.Value) error {
  1439. if em.bigIntConvert == BigIntConvertReject {
  1440. return &UnsupportedTypeError{Type: typeBigInt}
  1441. }
  1442. vbi := v.Interface().(big.Int)
  1443. sign := vbi.Sign()
  1444. bi := new(big.Int).SetBytes(vbi.Bytes()) // bi is absolute value of v
  1445. if sign < 0 {
  1446. // For negative number, convert to CBOR encoded number (-v-1).
  1447. bi.Sub(bi, big.NewInt(1))
  1448. }
  1449. if em.bigIntConvert == BigIntConvertShortest {
  1450. if bi.IsUint64() {
  1451. if sign >= 0 {
  1452. // Encode as CBOR pos int (major type 0)
  1453. encodeHead(e, byte(cborTypePositiveInt), bi.Uint64())
  1454. return nil
  1455. }
  1456. // Encode as CBOR neg int (major type 1)
  1457. encodeHead(e, byte(cborTypeNegativeInt), bi.Uint64())
  1458. return nil
  1459. }
  1460. }
  1461. tagNum := 2
  1462. if sign < 0 {
  1463. tagNum = 3
  1464. }
  1465. // Write tag number
  1466. encodeHead(e, byte(cborTypeTag), uint64(tagNum))
  1467. // Write bignum byte string
  1468. b := bi.Bytes()
  1469. encodeHead(e, byte(cborTypeByteString), uint64(len(b)))
  1470. e.Write(b)
  1471. return nil
  1472. }
  1473. type binaryMarshalerEncoder struct {
  1474. alternateEncode encodeFunc
  1475. alternateIsEmpty isEmptyFunc
  1476. }
  1477. func (bme binaryMarshalerEncoder) encode(e *bytes.Buffer, em *encMode, v reflect.Value) error {
  1478. if em.binaryMarshaler != BinaryMarshalerByteString {
  1479. return bme.alternateEncode(e, em, v)
  1480. }
  1481. vt := v.Type()
  1482. m, ok := v.Interface().(encoding.BinaryMarshaler)
  1483. if !ok {
  1484. pv := reflect.New(vt)
  1485. pv.Elem().Set(v)
  1486. m = pv.Interface().(encoding.BinaryMarshaler)
  1487. }
  1488. data, err := m.MarshalBinary()
  1489. if err != nil {
  1490. return err
  1491. }
  1492. if b := em.encTagBytes(vt); b != nil {
  1493. e.Write(b)
  1494. }
  1495. encodeHead(e, byte(cborTypeByteString), uint64(len(data)))
  1496. e.Write(data)
  1497. return nil
  1498. }
  1499. func (bme binaryMarshalerEncoder) isEmpty(em *encMode, v reflect.Value) (bool, error) {
  1500. if em.binaryMarshaler != BinaryMarshalerByteString {
  1501. return bme.alternateIsEmpty(em, v)
  1502. }
  1503. m, ok := v.Interface().(encoding.BinaryMarshaler)
  1504. if !ok {
  1505. pv := reflect.New(v.Type())
  1506. pv.Elem().Set(v)
  1507. m = pv.Interface().(encoding.BinaryMarshaler)
  1508. }
  1509. data, err := m.MarshalBinary()
  1510. if err != nil {
  1511. return false, err
  1512. }
  1513. return len(data) == 0, nil
  1514. }
  1515. type textMarshalerEncoder struct {
  1516. alternateEncode encodeFunc
  1517. alternateIsEmpty isEmptyFunc
  1518. }
  1519. func (tme textMarshalerEncoder) encode(e *bytes.Buffer, em *encMode, v reflect.Value) error {
  1520. if em.textMarshaler == TextMarshalerNone {
  1521. return tme.alternateEncode(e, em, v)
  1522. }
  1523. vt := v.Type()
  1524. m, ok := v.Interface().(encoding.TextMarshaler)
  1525. if !ok {
  1526. pv := reflect.New(vt)
  1527. pv.Elem().Set(v)
  1528. m = pv.Interface().(encoding.TextMarshaler)
  1529. }
  1530. data, err := m.MarshalText()
  1531. if err != nil {
  1532. return fmt.Errorf("cbor: cannot marshal text for %s: %w", vt, err)
  1533. }
  1534. if b := em.encTagBytes(vt); b != nil {
  1535. e.Write(b)
  1536. }
  1537. encodeHead(e, byte(cborTypeTextString), uint64(len(data)))
  1538. e.Write(data)
  1539. return nil
  1540. }
  1541. func (tme textMarshalerEncoder) isEmpty(em *encMode, v reflect.Value) (bool, error) {
  1542. if em.textMarshaler == TextMarshalerNone {
  1543. return tme.alternateIsEmpty(em, v)
  1544. }
  1545. m, ok := v.Interface().(encoding.TextMarshaler)
  1546. if !ok {
  1547. pv := reflect.New(v.Type())
  1548. pv.Elem().Set(v)
  1549. m = pv.Interface().(encoding.TextMarshaler)
  1550. }
  1551. data, err := m.MarshalText()
  1552. if err != nil {
  1553. return false, fmt.Errorf("cbor: cannot marshal text for %s: %w", v.Type(), err)
  1554. }
  1555. return len(data) == 0, nil
  1556. }
  1557. type jsonMarshalerEncoder struct {
  1558. alternateEncode encodeFunc
  1559. alternateIsEmpty isEmptyFunc
  1560. }
  1561. func (jme jsonMarshalerEncoder) encode(e *bytes.Buffer, em *encMode, v reflect.Value) error {
  1562. if em.jsonMarshalerTranscoder == nil {
  1563. return jme.alternateEncode(e, em, v)
  1564. }
  1565. vt := v.Type()
  1566. m, ok := v.Interface().(jsonMarshaler)
  1567. if !ok {
  1568. pv := reflect.New(vt)
  1569. pv.Elem().Set(v)
  1570. m = pv.Interface().(jsonMarshaler)
  1571. }
  1572. json, err := m.MarshalJSON()
  1573. if err != nil {
  1574. return err
  1575. }
  1576. offset := e.Len()
  1577. if b := em.encTagBytes(vt); b != nil {
  1578. e.Write(b)
  1579. }
  1580. if err := em.jsonMarshalerTranscoder.Transcode(e, bytes.NewReader(json)); err != nil {
  1581. return &TranscodeError{err: err, rtype: vt, sourceFormat: "json", targetFormat: "cbor"}
  1582. }
  1583. // Validate that the transcode function has written exactly one well-formed data item.
  1584. d := decoder{data: e.Bytes()[offset:], dm: getMarshalerDecMode(em.indefLength, em.tagsMd)}
  1585. if err := d.wellformed(false, true); err != nil {
  1586. e.Truncate(offset)
  1587. return &TranscodeError{err: err, rtype: vt, sourceFormat: "json", targetFormat: "cbor"}
  1588. }
  1589. return nil
  1590. }
  1591. func (jme jsonMarshalerEncoder) isEmpty(em *encMode, v reflect.Value) (bool, error) {
  1592. if em.jsonMarshalerTranscoder == nil {
  1593. return jme.alternateIsEmpty(em, v)
  1594. }
  1595. // As with types implementing cbor.Marshaler, transcoded json.Marshaler values always encode
  1596. // as exactly one complete CBOR data item.
  1597. return false, nil
  1598. }
  1599. func encodeMarshalerType(e *bytes.Buffer, em *encMode, v reflect.Value) error {
  1600. if em.tagsMd == TagsForbidden && v.Type() == typeRawTag {
  1601. return errors.New("cbor: cannot encode cbor.RawTag when TagsMd is TagsForbidden")
  1602. }
  1603. m, ok := v.Interface().(Marshaler)
  1604. if !ok {
  1605. pv := reflect.New(v.Type())
  1606. pv.Elem().Set(v)
  1607. m = pv.Interface().(Marshaler)
  1608. }
  1609. data, err := m.MarshalCBOR()
  1610. if err != nil {
  1611. return err
  1612. }
  1613. // Verify returned CBOR data item from MarshalCBOR() is well-formed and passes tag validity for builtin tags 0-3.
  1614. d := decoder{data: data, dm: getMarshalerDecMode(em.indefLength, em.tagsMd)}
  1615. err = d.wellformed(false, true)
  1616. if err != nil {
  1617. return &MarshalerError{typ: v.Type(), err: err}
  1618. }
  1619. e.Write(data)
  1620. return nil
  1621. }
  1622. func encodeTag(e *bytes.Buffer, em *encMode, v reflect.Value) error {
  1623. if em.tagsMd == TagsForbidden {
  1624. return errors.New("cbor: cannot encode cbor.Tag when TagsMd is TagsForbidden")
  1625. }
  1626. t := v.Interface().(Tag)
  1627. if t.Number == 0 && t.Content == nil {
  1628. // Marshal uninitialized cbor.Tag
  1629. e.Write(cborNil)
  1630. return nil
  1631. }
  1632. // Marshal tag number
  1633. encodeHead(e, byte(cborTypeTag), t.Number)
  1634. vem := *em // shallow copy
  1635. // For built-in tags, disable settings that may introduce tag validity errors when
  1636. // marshaling certain Content values.
  1637. switch t.Number {
  1638. case tagNumRFC3339Time:
  1639. vem.stringType = StringToTextString
  1640. vem.stringMajorType = cborTypeTextString
  1641. case tagNumUnsignedBignum, tagNumNegativeBignum:
  1642. vem.byteSliceLaterFormat = ByteSliceLaterFormatNone
  1643. vem.byteSliceLaterEncodingTag = 0
  1644. }
  1645. // Marshal tag content
  1646. return encode(e, &vem, reflect.ValueOf(t.Content))
  1647. }
  1648. // encodeHead writes CBOR head of specified type t and returns number of bytes written.
  1649. func encodeHead(e *bytes.Buffer, t byte, n uint64) int {
  1650. if n <= maxAdditionalInformationWithoutArgument {
  1651. const headSize = 1
  1652. e.WriteByte(t | byte(n))
  1653. return headSize
  1654. }
  1655. if n <= math.MaxUint8 {
  1656. const headSize = 2
  1657. scratch := [headSize]byte{
  1658. t | byte(additionalInformationWith1ByteArgument),
  1659. byte(n),
  1660. }
  1661. e.Write(scratch[:])
  1662. return headSize
  1663. }
  1664. if n <= math.MaxUint16 {
  1665. const headSize = 3
  1666. var scratch [headSize]byte
  1667. scratch[0] = t | byte(additionalInformationWith2ByteArgument)
  1668. binary.BigEndian.PutUint16(scratch[1:], uint16(n))
  1669. e.Write(scratch[:])
  1670. return headSize
  1671. }
  1672. if n <= math.MaxUint32 {
  1673. const headSize = 5
  1674. var scratch [headSize]byte
  1675. scratch[0] = t | byte(additionalInformationWith4ByteArgument)
  1676. binary.BigEndian.PutUint32(scratch[1:], uint32(n))
  1677. e.Write(scratch[:])
  1678. return headSize
  1679. }
  1680. const headSize = 9
  1681. var scratch [headSize]byte
  1682. scratch[0] = t | byte(additionalInformationWith8ByteArgument)
  1683. binary.BigEndian.PutUint64(scratch[1:], n)
  1684. e.Write(scratch[:])
  1685. return headSize
  1686. }
  1687. type jsonMarshaler interface{ MarshalJSON() ([]byte, error) }
  1688. var (
  1689. typeMarshaler = reflect.TypeOf((*Marshaler)(nil)).Elem()
  1690. typeBinaryMarshaler = reflect.TypeOf((*encoding.BinaryMarshaler)(nil)).Elem()
  1691. typeTextMarshaler = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()
  1692. typeJSONMarshaler = reflect.TypeOf((*jsonMarshaler)(nil)).Elem()
  1693. typeRawMessage = reflect.TypeOf(RawMessage(nil))
  1694. typeByteString = reflect.TypeOf(ByteString(""))
  1695. )
  1696. func getEncodeFuncInternal(t reflect.Type) (ef encodeFunc, ief isEmptyFunc, izf isZeroFunc) {
  1697. k := t.Kind()
  1698. if k == reflect.Pointer {
  1699. return getEncodeIndirectValueFunc(t), isEmptyPtr, getIsZeroFunc(t)
  1700. }
  1701. switch t {
  1702. case typeSimpleValue:
  1703. return encodeMarshalerType, isEmptyUint, getIsZeroFunc(t)
  1704. case typeTag:
  1705. return encodeTag, alwaysNotEmpty, getIsZeroFunc(t)
  1706. case typeTime:
  1707. return encodeTime, alwaysNotEmpty, getIsZeroFunc(t)
  1708. case typeBigInt:
  1709. return encodeBigInt, alwaysNotEmpty, getIsZeroFunc(t)
  1710. case typeRawMessage:
  1711. return encodeMarshalerType, isEmptySlice, getIsZeroFunc(t)
  1712. case typeByteString:
  1713. return encodeMarshalerType, isEmptyString, getIsZeroFunc(t)
  1714. }
  1715. if reflect.PointerTo(t).Implements(typeMarshaler) {
  1716. return encodeMarshalerType, alwaysNotEmpty, getIsZeroFunc(t)
  1717. }
  1718. if reflect.PointerTo(t).Implements(typeBinaryMarshaler) {
  1719. defer func() {
  1720. // capture encoding method used for modes that disable BinaryMarshaler
  1721. bme := binaryMarshalerEncoder{
  1722. alternateEncode: ef,
  1723. alternateIsEmpty: ief,
  1724. }
  1725. ef = bme.encode
  1726. ief = bme.isEmpty
  1727. }()
  1728. }
  1729. if reflect.PointerTo(t).Implements(typeTextMarshaler) {
  1730. defer func() {
  1731. // capture encoding method used for modes that disable TextMarshaler
  1732. tme := textMarshalerEncoder{
  1733. alternateEncode: ef,
  1734. alternateIsEmpty: ief,
  1735. }
  1736. ef = tme.encode
  1737. ief = tme.isEmpty
  1738. }()
  1739. }
  1740. if reflect.PointerTo(t).Implements(typeJSONMarshaler) {
  1741. defer func() {
  1742. // capture encoding method used for modes that don't support transcoding
  1743. // from types that implement json.Marshaler.
  1744. jme := jsonMarshalerEncoder{
  1745. alternateEncode: ef,
  1746. alternateIsEmpty: ief,
  1747. }
  1748. ef = jme.encode
  1749. ief = jme.isEmpty
  1750. }()
  1751. }
  1752. switch k {
  1753. case reflect.Bool:
  1754. return encodeBool, isEmptyBool, getIsZeroFunc(t)
  1755. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  1756. return encodeInt, isEmptyInt, getIsZeroFunc(t)
  1757. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  1758. return encodeUint, isEmptyUint, getIsZeroFunc(t)
  1759. case reflect.Float32, reflect.Float64:
  1760. return encodeFloat, isEmptyFloat, getIsZeroFunc(t)
  1761. case reflect.String:
  1762. return encodeString, isEmptyString, getIsZeroFunc(t)
  1763. case reflect.Slice:
  1764. if t.Elem().Kind() == reflect.Uint8 {
  1765. return encodeByteString, isEmptySlice, getIsZeroFunc(t)
  1766. }
  1767. fallthrough
  1768. case reflect.Array:
  1769. f, _, _ := getEncodeFunc(t.Elem())
  1770. if f == nil {
  1771. return nil, nil, nil
  1772. }
  1773. return arrayEncodeFunc{f: f}.encode, isEmptySlice, getIsZeroFunc(t)
  1774. case reflect.Map:
  1775. f := getEncodeMapFunc(t)
  1776. if f == nil {
  1777. return nil, nil, nil
  1778. }
  1779. return f, isEmptyMap, getIsZeroFunc(t)
  1780. case reflect.Struct:
  1781. // Get struct's special field "_" tag options
  1782. if f, ok := t.FieldByName("_"); ok {
  1783. tag := f.Tag.Get("cbor")
  1784. if tag != "-" {
  1785. if hasToArrayOption(tag) {
  1786. return encodeStructToArray, isEmptyStruct, isZeroFieldStruct
  1787. }
  1788. }
  1789. }
  1790. return encodeStruct, isEmptyStruct, getIsZeroFunc(t)
  1791. case reflect.Interface:
  1792. return encodeIntf, isEmptyIntf, getIsZeroFunc(t)
  1793. }
  1794. return nil, nil, nil
  1795. }
  1796. func getEncodeIndirectValueFunc(t reflect.Type) encodeFunc {
  1797. for t.Kind() == reflect.Pointer {
  1798. t = t.Elem()
  1799. }
  1800. f, _, _ := getEncodeFunc(t)
  1801. if f == nil {
  1802. return nil
  1803. }
  1804. return func(e *bytes.Buffer, em *encMode, v reflect.Value) error {
  1805. for v.Kind() == reflect.Pointer && !v.IsNil() {
  1806. v = v.Elem()
  1807. }
  1808. if v.Kind() == reflect.Pointer && v.IsNil() {
  1809. e.Write(cborNil)
  1810. return nil
  1811. }
  1812. return f(e, em, v)
  1813. }
  1814. }
  1815. func alwaysNotEmpty(_ *encMode, _ reflect.Value) (empty bool, err error) {
  1816. return false, nil
  1817. }
  1818. func isEmptyBool(_ *encMode, v reflect.Value) (bool, error) {
  1819. return !v.Bool(), nil
  1820. }
  1821. func isEmptyInt(_ *encMode, v reflect.Value) (bool, error) {
  1822. return v.Int() == 0, nil
  1823. }
  1824. func isEmptyUint(_ *encMode, v reflect.Value) (bool, error) {
  1825. return v.Uint() == 0, nil
  1826. }
  1827. func isEmptyFloat(_ *encMode, v reflect.Value) (bool, error) {
  1828. return v.Float() == 0.0, nil
  1829. }
  1830. func isEmptyString(_ *encMode, v reflect.Value) (bool, error) {
  1831. return v.Len() == 0, nil
  1832. }
  1833. func isEmptySlice(_ *encMode, v reflect.Value) (bool, error) {
  1834. return v.Len() == 0, nil
  1835. }
  1836. func isEmptyMap(_ *encMode, v reflect.Value) (bool, error) {
  1837. return v.Len() == 0, nil
  1838. }
  1839. func isEmptyPtr(_ *encMode, v reflect.Value) (bool, error) {
  1840. return v.IsNil(), nil
  1841. }
  1842. func isEmptyIntf(_ *encMode, v reflect.Value) (bool, error) {
  1843. return v.IsNil(), nil
  1844. }
  1845. func isEmptyStruct(em *encMode, v reflect.Value) (bool, error) {
  1846. structType, err := getEncodingStructType(v.Type())
  1847. if err != nil {
  1848. return false, err
  1849. }
  1850. if em.omitEmpty == OmitEmptyGoValue {
  1851. return false, nil
  1852. }
  1853. if structType.toArray {
  1854. return len(structType.fields) == 0, nil
  1855. }
  1856. if len(structType.fields) > len(structType.omitEmptyFieldsIdx) {
  1857. return false, nil
  1858. }
  1859. for _, i := range structType.omitEmptyFieldsIdx {
  1860. f := structType.fields[i]
  1861. // Get field value
  1862. var fv reflect.Value
  1863. if len(f.idx) == 1 {
  1864. fv = v.Field(f.idx[0])
  1865. } else {
  1866. // Get embedded field value. No error is expected.
  1867. fv, _ = getFieldValue(v, f.idx, func(reflect.Value) (reflect.Value, error) {
  1868. // Skip null pointer to embedded struct
  1869. return reflect.Value{}, nil
  1870. })
  1871. if !fv.IsValid() {
  1872. continue
  1873. }
  1874. }
  1875. empty, err := f.ief(em, fv)
  1876. if err != nil {
  1877. return false, err
  1878. }
  1879. if !empty {
  1880. return false, nil
  1881. }
  1882. }
  1883. return true, nil
  1884. }
  1885. func cannotFitFloat32(f64 float64) bool {
  1886. f32 := float32(f64)
  1887. return float64(f32) != f64
  1888. }
  1889. // float32NaNFromReflectValue extracts float32 NaN from reflect.Value while preserving NaN's quiet bit.
  1890. func float32NaNFromReflectValue(v reflect.Value) float32 {
  1891. // Keith Randall's workaround for issue https://github.com/golang/go/issues/36400
  1892. p := reflect.New(v.Type())
  1893. p.Elem().Set(v)
  1894. f32 := p.Convert(reflect.TypeOf((*float32)(nil))).Elem().Interface().(float32)
  1895. return f32
  1896. }
  1897. type isZeroer interface {
  1898. IsZero() bool
  1899. }
  1900. var isZeroerType = reflect.TypeOf((*isZeroer)(nil)).Elem()
  1901. // getIsZeroFunc returns a function for the given type that can be called to determine if a given value is zero.
  1902. // Types that implement `IsZero() bool` are delegated to for non-nil values.
  1903. // Types that do not implement `IsZero() bool` use the reflect.Value#IsZero() implementation.
  1904. // The returned function matches behavior of stdlib encoding/json behavior in Go 1.24+.
  1905. func getIsZeroFunc(t reflect.Type) isZeroFunc {
  1906. // Provide a function that uses a type's IsZero method if defined.
  1907. switch {
  1908. case t == nil:
  1909. return isZeroDefault
  1910. case t.Kind() == reflect.Interface && t.Implements(isZeroerType):
  1911. return isZeroInterfaceCustom
  1912. case t.Kind() == reflect.Pointer && t.Implements(isZeroerType):
  1913. return isZeroPointerCustom
  1914. case t.Implements(isZeroerType):
  1915. return isZeroCustom
  1916. case reflect.PointerTo(t).Implements(isZeroerType):
  1917. return isZeroAddrCustom
  1918. default:
  1919. return isZeroDefault
  1920. }
  1921. }
  1922. // isZeroInterfaceCustom returns true for nil or pointer-to-nil values,
  1923. // and delegates to the custom IsZero() implementation otherwise.
  1924. func isZeroInterfaceCustom(v reflect.Value) (bool, error) {
  1925. kind := v.Kind()
  1926. switch kind {
  1927. case reflect.Chan, reflect.Func, reflect.Map, reflect.Pointer, reflect.Interface, reflect.Slice:
  1928. if v.IsNil() {
  1929. return true, nil
  1930. }
  1931. }
  1932. switch kind {
  1933. case reflect.Interface, reflect.Pointer:
  1934. if elem := v.Elem(); elem.Kind() == reflect.Pointer && elem.IsNil() {
  1935. return true, nil
  1936. }
  1937. }
  1938. return v.Interface().(isZeroer).IsZero(), nil
  1939. }
  1940. // isZeroPointerCustom returns true for nil values,
  1941. // and delegates to the custom IsZero() implementation otherwise.
  1942. func isZeroPointerCustom(v reflect.Value) (bool, error) {
  1943. if v.IsNil() {
  1944. return true, nil
  1945. }
  1946. return v.Interface().(isZeroer).IsZero(), nil
  1947. }
  1948. // isZeroCustom delegates to the custom IsZero() implementation.
  1949. func isZeroCustom(v reflect.Value) (bool, error) {
  1950. return v.Interface().(isZeroer).IsZero(), nil
  1951. }
  1952. // isZeroAddrCustom delegates to the custom IsZero() implementation of the addr of the value.
  1953. func isZeroAddrCustom(v reflect.Value) (bool, error) {
  1954. if !v.CanAddr() {
  1955. // Temporarily box v so we can take the address.
  1956. v2 := reflect.New(v.Type()).Elem()
  1957. v2.Set(v)
  1958. v = v2
  1959. }
  1960. return v.Addr().Interface().(isZeroer).IsZero(), nil
  1961. }
  1962. // isZeroDefault calls reflect.Value#IsZero()
  1963. func isZeroDefault(v reflect.Value) (bool, error) {
  1964. if !v.IsValid() {
  1965. // v is zero value
  1966. return true, nil
  1967. }
  1968. return v.IsZero(), nil
  1969. }
  1970. // isZeroFieldStruct is used to determine whether to omit toarray structs
  1971. func isZeroFieldStruct(v reflect.Value) (bool, error) {
  1972. structType, err := getEncodingStructType(v.Type())
  1973. if err != nil {
  1974. return false, err
  1975. }
  1976. return len(structType.fields) == 0, nil
  1977. }