├── LICENSE ├── README.md ├── blind_decoder.go ├── common.go ├── common_test.go ├── composer.go ├── composer_test.go ├── decoder.go ├── decoder_test.go ├── encoder.go ├── encoder_test.go ├── error.go ├── kind_decoder.go ├── major_string.go ├── maps.go ├── parser.go └── parser_test.go /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Concise Binary Object Representation Golang implementation (RFC7049) 2 | 3 | This is a extensive high performance implementation of the CBOR (RFC7049) 4 | proposed standard data format. 5 | -------------------------------------------------------------------------------- /blind_decoder.go: -------------------------------------------------------------------------------- 1 | // A Golang RFC7049 implementation 2 | // Copyright (C) 2015 Oscar Campos 3 | 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | 16 | package cbor 17 | 18 | import ( 19 | "fmt" 20 | "math/big" 21 | "reflect" 22 | ) 23 | 24 | // function used to decode extended tag info 25 | type handleTagDecFn func(*Decoder, interface{}) error 26 | 27 | // tag maps, used by user code to register custom extensions 28 | // using the major type 6 Optional Semantic Tagging for more 29 | // information refer to http://tools.ietf.org/html/rfc7049#section-2.4 30 | type extensionTagMap map[uint64]handleTagDecFn 31 | 32 | // global extension tags map 33 | var extensionTagDec extensionTagMap = make(extensionTagMap) 34 | 35 | // register a new extension information tag in the tags register 36 | func (e *extensionTagMap) register(tagInfo uint64, fn handleTagDecFn) error { 37 | if _, ok := extensionTagDec[tagInfo]; ok { 38 | return fmt.Errorf("0x%x tag information is already registered", tagInfo) 39 | } 40 | extensionTagDec[tagInfo] = fn 41 | return nil 42 | } 43 | 44 | // Look for a function registered to handle a given tag info 45 | func (e *extensionTagMap) lookup(tagInfo uint64) (handleTagDecFn, error) { 46 | fn, ok := extensionTagDec[tagInfo] 47 | if !ok { 48 | return nil, fmt.Errorf( 49 | "0x%x not matched as registered tag extension handler", tagInfo) 50 | } 51 | return fn, nil 52 | } 53 | 54 | // Registers a new funtion to handle decode of tag extensions 55 | func RegisterTagExtensionFn(tagInfo uint64, fn handleTagDecFn) error { 56 | return extensionTagDec.register(tagInfo, fn) 57 | } 58 | 59 | // decodes into v scanning the CBOR data that comes in the encoded data 60 | func (dec *Decoder) blind() (v interface{}, vk reflect.Kind, err error) { 61 | header := dec.parser.header 62 | info := header & 0x1f 63 | switch header { 64 | case absoluteNil, absoluteUndef: 65 | vk = reflect.Invalid 66 | case absoluteFalse: 67 | vk = reflect.Bool 68 | v = false 69 | case absoluteTrue: 70 | vk = reflect.Bool 71 | v = true 72 | case absoluteFloat16, absoluteFloat32: 73 | vk = reflect.Float32 74 | if info == cborFloat16 { 75 | v = dec.decodeFloat16() 76 | } else { 77 | v = dec.decodeInt32() 78 | } 79 | case absoluteFloat64: 80 | vk = reflect.Float64 81 | v = dec.decodeFloat64() 82 | case absoluteIndefiniteBytes: 83 | vk = byteString 84 | v = dec.decodeBytes() 85 | case absoluteIndefiniteString: 86 | vk = reflect.String 87 | v = dec.decodeString() 88 | case absoluteIndefiniteArray: 89 | vk = reflect.Slice 90 | case absoluteIndefiniteMap: 91 | vk = reflect.Map 92 | case absolutePositiveBigNum: 93 | vk = bigNum 94 | v = dec.decodePositiveBigNum() 95 | case absoluteNegativeBigNum: 96 | vk = bigNum 97 | v = new(big.Int).Neg(dec.decodeNegativeBigNum()) 98 | case absoluteStringDateTime: 99 | vk = stringDateTime 100 | v = dec.decodeStringDateTime() 101 | case absoluteEpochDateTime: 102 | vk = epochDateTime 103 | v = dec.decodeEpochDateTime() 104 | case absoluteDecimalFraction: 105 | vk = decimalFraction 106 | v = dec.decodeDecimalFraction() 107 | case absoluteBigFloat: 108 | vk = bigFloat 109 | v = dec.decodeBigFloat() 110 | case absoluteBase64Url: 111 | vk = base64Url 112 | v = dec.decodeBase64Url() 113 | case absoluteBase64String: 114 | vk = base64String 115 | v = dec.decodeBase64() 116 | case absoluteBase16String: 117 | vk = base16String 118 | v = dec.decodeBase16() 119 | default: 120 | // unsigned integers 121 | if header >= absoluteUint && header < absoluteInt { 122 | switch info { 123 | case cborSmallInt, cborUint8: 124 | vk = reflect.Uint8 125 | v = dec.decodeUint8() 126 | case cborUint16: 127 | vk = reflect.Uint16 128 | v = dec.decodeUint16() 129 | case cborUint32: 130 | vk = reflect.Uint32 131 | v = dec.decodeUint32() 132 | case cborUint64: 133 | vk = reflect.Uint64 134 | v = dec.decodeUint64() 135 | default: 136 | if info < cborSmallInt { 137 | vk = reflect.Uint8 138 | v = dec.decodeUint8() 139 | } 140 | } 141 | } 142 | // signed integers 143 | if header >= absoluteInt && header < absoluteBytes { 144 | switch info { 145 | case cborSmallInt, cborUint8: 146 | vk = reflect.Int8 147 | v = dec.decodeInt8() 148 | case cborUint16: 149 | vk = reflect.Int16 150 | v = dec.decodeInt16() 151 | case cborUint32: 152 | vk = reflect.Int32 153 | v = dec.decodeInt32() 154 | case cborUint64: 155 | vk = reflect.Int64 156 | v = dec.decodeInt64() 157 | default: 158 | if info < cborSmallInt { 159 | vk = reflect.Int8 160 | v = dec.decodeInt8() 161 | } 162 | } 163 | } 164 | // byte strings 165 | if header >= absoluteBytes && header < absoluteString { 166 | vk = byteString 167 | v = dec.decodeBytes() 168 | } 169 | // unicode string 170 | if header >= absoluteString && header < absoluteArray { 171 | vk = reflect.String 172 | v = dec.decodeString() 173 | } 174 | // slice 175 | if header >= absoluteArray && header < absoluteMap { 176 | vk = reflect.Slice 177 | } 178 | // map 179 | if header >= absoluteMap && header < absoluteTag { 180 | vk = reflect.Map 181 | } 182 | // tags 183 | if header >= absoluteTag && header < absoluteNoContent { 184 | tagInfo := dec.parser.buflen() 185 | switch tagInfo { 186 | case cborURI: 187 | vk = URI 188 | v = dec.decodeURI() 189 | case cborTextBase64Url: 190 | vk = URI 191 | v = dec.decodeBase64URI() 192 | case cborTextBase64: 193 | vk = reflect.String 194 | v = dec.decodeBase64String() 195 | case cborRegexp: 196 | vk = tagRegexp 197 | v = dec.decodeRegexp() 198 | case cborMime: 199 | vk = MIME 200 | v = dec.decodeMime() 201 | default: 202 | // lookup in the extended user defined tags 203 | fn, err := extensionTagDec.lookup(tagInfo) 204 | if err == nil { 205 | vk = reflect.Invalid 206 | if err := fn(dec, v); err != nil { 207 | return nil, 0, err 208 | } 209 | } else { 210 | vk = reflect.Ptr 211 | } 212 | } 213 | } 214 | } 215 | 216 | if vk == 0 { 217 | return nil, 0, fmt.Errorf("blind: Unrecognized header 0x%x", header) 218 | } 219 | return v, vk, nil 220 | } 221 | -------------------------------------------------------------------------------- /common.go: -------------------------------------------------------------------------------- 1 | //go:generate stringer -type=Major 2 | 3 | // A Golang RFC7049 implementation 4 | // Copyright (C) 2015 Oscar Campos 5 | 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | package cbor 19 | 20 | import ( 21 | "math" 22 | "math/big" 23 | "reflect" 24 | "strconv" 25 | "strings" 26 | "unsafe" 27 | ) 28 | 29 | var someInt int 30 | 31 | // int size in the running platform 32 | const intSize = unsafe.Sizeof(someInt) 33 | 34 | type Major byte 35 | 36 | // RFC7049 defines eight "Major Types" that are contained in the 37 | // higher-order 3 bits in the initial byte of data of a 'data item' 38 | const ( 39 | cborUnsignedInt Major = iota // Unsigned integers 40 | cborNegativeInt // Negative integers 41 | cborByteString // String of bytes 42 | cborTextString // String of text UTF-8 encoded 43 | cborDataArray // Array of arbitrary data 44 | cborDataMap // Map of arbitrary data 45 | cborTag // Semantic tag 46 | cborNC // Other types that needs no content like "break" 47 | ) 48 | 49 | // Additional information contained in the 5 low-order bits of 50 | // the header byte have an specific meaning in general and a 51 | // special meaning in case of the Major 7 52 | const ( 53 | cborSmallInt byte = 0x17 54 | cborUint8 = 0x18 55 | cborUint16 = 0x19 56 | cborUint32 = 0x1a 57 | cborUint64 = 0x1b 58 | cborIndefinite = 0x1f 59 | ) 60 | 61 | // Additional information values for Major 7 62 | const ( 63 | cborFalse byte = 0x14 + iota 64 | cborTrue 65 | cborNil 66 | cborUndef 67 | cborSimple 68 | cborFloat16 69 | cborFloat32 70 | cborFloat64 71 | ) 72 | 73 | // Big nums 74 | const ( 75 | cborPositiveBigNum byte = 0xc2 76 | ) 77 | 78 | // Additional tags on RFC7049 79 | const ( 80 | cborTextDateTime byte = 0x00 81 | cborUnixTimestamp = 0x01 82 | cborBigNum = 0x02 83 | cborBigNegNum = 0x03 84 | cborFraction = 0x04 85 | cborBigFloat = 0x05 86 | cborBase64Url = 0x15 87 | cborBase64 = 0x16 88 | cborBase16 = 0x17 89 | cborEnc = 0x18 90 | cborURI = 0x20 91 | cborTextBase64Url = 0x21 92 | cborTextBase64 = 0x22 93 | cborRegexp = 0x23 94 | cborMime = 0x24 95 | cborSelfDescribe = 0xd9d9f7 96 | ) 97 | 98 | // this is being used to break indefinite streams 99 | const cborBreak byte = 0xff 100 | 101 | // convenience contants to help to the blind decoder 102 | const ( 103 | absoluteFalse byte = 0xf4 + iota 104 | absoluteTrue 105 | absoluteNil 106 | absoluteUndef 107 | absoluteSimple 108 | absoluteFloat16 109 | absoluteFloat32 110 | absoluteFloat64 111 | ) 112 | 113 | // absolute headers 114 | const ( 115 | absoluteIndefiniteBytes byte = 0x5f 116 | absoluteIndefiniteString = 0x7f 117 | absoluteIndefiniteArray = 0x9f 118 | absoluteIndefiniteMap = 0xbf 119 | absoluteUint = 0x00 120 | absoluteInt = 0x20 121 | absoluteBytes = 0x40 122 | absoluteString = 0x60 123 | absoluteArray = 0x80 124 | absoluteMap = 0xa0 125 | absoluteTag = 0xc0 126 | absoluteStringDateTime = absoluteTag 127 | absoluteEpochDateTime = 0xc1 128 | absolutePositiveBigNum = 0xc2 129 | absoluteNegativeBigNum = 0xc3 130 | absoluteDecimalFraction = 0xc4 131 | absoluteBigFloat = 0xc5 132 | absoluteBase64Url = 0xd5 133 | absoluteBase64String = 0xd6 134 | absoluteBase16String = 0xd7 135 | absoluteNoContent = 0xe0 136 | ) 137 | 138 | // type constants used on blind decode 139 | const ( 140 | byteString reflect.Kind = reflect.UnsafePointer + 1 + iota 141 | stringDateTime 142 | epochDateTime 143 | bigNum 144 | decimalFraction 145 | bigFloat 146 | base64Url 147 | base64String 148 | base16String 149 | encodedDataItem 150 | URI 151 | tagRegexp 152 | MIME 153 | ) 154 | 155 | // CBORMIME 156 | type CBORMIME struct { 157 | ContentType string 158 | Params map[string]string 159 | } 160 | 161 | type float16 float32 162 | 163 | // taken from OGRE 3D rendering engine 164 | func float16toUint32(yy uint16) (d uint32) { 165 | y := uint32(yy) 166 | s := (y >> 15) & 0x00000001 167 | e := (y >> 10) & 0x0000001f 168 | m := y & 0x000003ff 169 | 170 | if e == 0 { 171 | if m == 0 { // Plus or minus zero 172 | return s << 31 173 | } else { // Denormalized number -- renormalize it 174 | for (m & 0x00000400) == 0 { 175 | m <<= 1 176 | e -= 1 177 | } 178 | e += 1 179 | m &= ^uint32(0x00000400) 180 | } 181 | } else if e == 31 { 182 | if m == 0 { // Inf 183 | return (s << 31) | 0x7f800000 184 | } else { // NaN 185 | return (s << 31) | 0x7f800000 | (m << 13) 186 | } 187 | } 188 | e = e + (127 - 15) 189 | m = m << 13 190 | return (s << 31) | (e << 23) | m 191 | } 192 | 193 | func uint32toFloat16(i uint32) uint16 { 194 | s := (i >> 16) & 0x00008000 195 | e := ((i >> 23) & 0x000000ff) - (127 - 15) 196 | m := i & 0x007fffff 197 | 198 | if e <= 0 { 199 | if int(e) < -10 { 200 | return 0 201 | } 202 | m = (m | 0x00800000) >> uint32(1-e) 203 | return uint16(s | (m >> 13)) 204 | } else if e == 0xff-(127-15) { 205 | if m == 0 { // Inf 206 | return uint16(s | 0x7c00) 207 | } else { // NaN 208 | m >>= 13 209 | t := uint32(0) 210 | if m == 0 { 211 | t = 1 212 | } 213 | return uint16(s | 0x7c00 | m | t) 214 | } 215 | } else { 216 | if e > 30 { // Overflow 217 | return uint16(s | 0x7c00) 218 | } 219 | return uint16(s | (e << 10) | (m >> 13)) 220 | } 221 | } 222 | 223 | // convert a mantissa and an exponent into a float32 224 | func decimalFractionToFloat(m, e int64) float32 { 225 | be := math.Pow10(int(e)) 226 | return float32(float64(m) * be) 227 | } 228 | 229 | // convert a float32 to an exponent and a mantissa 230 | func floatToDecimalFraction(f float32) (int64, int64) { 231 | fs := strconv.FormatFloat(float64(f), 'f', -1, 32) 232 | l := len(fs) - (strings.Index(fs, ".") + 1) 233 | return int64(l), int64(f * float32(math.Pow10(l))) 234 | } 235 | 236 | // convert a mantissa and an exponent into a *big.Rat 237 | func bigFloatToRatFromInt64(m, e int64) *big.Rat { 238 | be := math.Pow(2, float64(e)) 239 | f := float32(float64(m) * be) 240 | r := &big.Rat{} 241 | r.SetFloat64(float64(f)) 242 | return r 243 | } 244 | 245 | // convert a mantissa and an exponent into a *big.Rat from a *big.Int 246 | func bigFloatToRatFromBigInt(m *big.Int, e int64) *big.Rat { 247 | multiplier := big.NewInt(2 * int64(math.Abs(float64(e)))) 248 | r := &big.Rat{} 249 | return r.SetFrac(m, multiplier) 250 | } 251 | -------------------------------------------------------------------------------- /common_test.go: -------------------------------------------------------------------------------- 1 | // A Golang RFC7049 implementation 2 | // Copyright (C) 2015 Oscar Campos 3 | 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | 16 | package cbor 17 | 18 | import "testing" 19 | 20 | // Common message for failed tests 21 | const failed = "%s: expected %v, got %v" 22 | 23 | // Interfaces to map results of any type 24 | type CurrentResult interface{} 25 | type ExpectedResult interface{} 26 | 27 | // convenience function for simple assertions 28 | func expect(got CurrentResult, expected ExpectedResult, t *testing.T, from ...string) { 29 | f := "TestTake" 30 | if len(from) > 0 { 31 | f = from[0] 32 | } 33 | if expected != got { 34 | t.Errorf(failed, f, expected, got) 35 | } 36 | } 37 | 38 | func check(e error) { 39 | if e != nil { 40 | panic(e) 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /composer.go: -------------------------------------------------------------------------------- 1 | // A Golang RFC7049 implementation 2 | // Copyright (C) 2015 Oscar Campos 3 | 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | 16 | package cbor 17 | 18 | import ( 19 | "encoding/binary" 20 | "fmt" 21 | "io" 22 | "math" 23 | "math/big" 24 | "time" 25 | "unsafe" 26 | ) 27 | 28 | // Composes a 'data item' 29 | type Composer struct { 30 | header byte 31 | w io.Writer 32 | indefinite bool 33 | } 34 | 35 | // Create a new Composer with the given 36 | // io.Writer and returns back it's address 37 | func NewComposer(w io.Writer) *Composer { 38 | return &Composer{w: w} 39 | } 40 | 41 | func (c *Composer) composeInformation(major Major, info byte) error { 42 | c.header = (byte(major) << 5) | info 43 | if _, err := c.w.Write([]byte{c.header}); err != nil { 44 | return fmt.Errorf("while composing inforamtion byte: %s", err) 45 | } 46 | return nil 47 | } 48 | 49 | // Write bytes into the io.Writer, returns the 50 | // number of bytes written and an error in case of any 51 | func (c *Composer) write(buf []byte) (n int, err error) { 52 | if len(buf) == 0 || buf == nil { 53 | return 0, nil 54 | } 55 | 56 | n, err = c.w.Write(buf) 57 | if err != nil { 58 | return n, err 59 | } 60 | if n != len(buf) { 61 | err = fmt.Errorf("buf was %d bytes length but only %d bytes were written", len(buf), n) 62 | } 63 | return n, err 64 | } 65 | 66 | // Writes a single byte into the io.Writer 67 | func (c *Composer) write1(b byte) error { 68 | if _, err := c.write([]byte{b}); err != nil { 69 | return err 70 | } 71 | return nil 72 | } 73 | 74 | // Write a single byte into the io.Writer 75 | // as an encoded CBOR Null value 76 | func (c *Composer) composeNil() error { 77 | if err := c.write1(absoluteNil); err != nil { 78 | return fmt.Errorf("while writting nil value: %s", err.Error()) 79 | } 80 | return nil 81 | } 82 | 83 | // Handle unsigned integers writing 84 | func (c *Composer) composeUint(i uint64, infoType ...Major) (n int, err error) { 85 | var t Major = cborUnsignedInt 86 | if len(infoType) > 0 { 87 | t = infoType[0] 88 | } 89 | if i < 24 { 90 | if err := c.composeInformation(t, byte(i)); err != nil { 91 | return 0, err 92 | } 93 | return 1, nil 94 | } 95 | if i <= math.MaxUint8 { 96 | if err := c.composeInformation(t, cborUint8); err != nil { 97 | return 0, err 98 | } 99 | return c.composeUint8(byte(i)) 100 | } 101 | if i <= math.MaxUint16 { 102 | if err := c.composeInformation(t, cborUint16); err != nil { 103 | return 0, err 104 | } 105 | return c.composeUint16(uint16(i)) 106 | } 107 | if i <= math.MaxUint32 { 108 | if err := c.composeInformation(t, cborUint32); err != nil { 109 | return 0, err 110 | } 111 | return c.composeUint32(uint32(i)) 112 | } 113 | if i <= math.MaxUint64 { 114 | if err := c.composeInformation(t, cborUint64); err != nil { 115 | return 0, err 116 | } 117 | return c.composeUin64(i) 118 | } 119 | return 0, fmt.Errorf("totally unexpected error, Uint size is unknown %v!", i) 120 | } 121 | 122 | // Handle signed integers writing 123 | func (c *Composer) composeInt(i int64) (n int, err error) { 124 | if i < 0 { 125 | return c.composeUint(uint64(^i), cborNegativeInt) 126 | } 127 | return c.composeUint(uint64(i)) 128 | } 129 | 130 | // Write a single byte into the io.Writer 131 | // as an encoded CBOR unsigned int of 8 bits 132 | func (c *Composer) composeUint8(i uint8) (int, error) { 133 | if i < 24 { 134 | return 0, NewCanonicalModeError(fmt.Sprintf("%d must be send in a single byte 0x%x\n", i, i)) 135 | } 136 | if err := binary.Write(c.w, binary.BigEndian, i); err != nil { 137 | return 0, err 138 | } 139 | return 1, nil 140 | } 141 | 142 | // Write two bytes into the io.Writer 143 | // as an encoded CBOR unsigned int of 16 bits 144 | func (c *Composer) composeUint16(i uint16) (int, error) { 145 | buf := []byte{byte(i >> 8), byte(i)} 146 | if _, err := c.write(buf); err != nil { 147 | return 0, err 148 | } 149 | return 2, nil 150 | } 151 | 152 | // Write two bytes into the io.Writer 153 | // as an encoded CBOR unsigned int of 32 bits 154 | func (c *Composer) composeUint32(i uint32) (int, error) { 155 | buf := []byte{byte(i >> 24), byte(i >> 16), byte(i >> 8), byte(i)} 156 | if _, err := c.write(buf); err != nil { 157 | return 0, err 158 | } 159 | return 4, nil 160 | } 161 | 162 | // Write two bytes into the io.Writer 163 | // as an encoded CBOR unsigned int of 64 bits 164 | func (c *Composer) composeUin64(i uint64) (int, error) { 165 | buf := []byte{ 166 | byte(i >> 56), byte(i >> 48), byte(i >> 40), byte(i >> 32), 167 | byte(i >> 24), byte(i >> 16), byte(i >> 8), byte(i), 168 | } 169 | if _, err := c.write(buf); err != nil { 170 | return 0, err 171 | } 172 | return 8, nil 173 | } 174 | 175 | // Write one byte into the io.Writer 176 | // as an encoded CBOR boolean value 177 | func (c *Composer) composeBoolean(v bool) error { 178 | b := absoluteFalse 179 | if v { 180 | b = absoluteTrue 181 | } 182 | if err := c.write1(b); err != nil { 183 | return fmt.Errorf("while writting boolean %v value: %s", v, err.Error()) 184 | } 185 | return nil 186 | } 187 | 188 | // Write two bytes into the io.Writer 189 | // as an encoded CBOR float16 190 | func (c *Composer) composeFloat16(f float16) error { 191 | if err := c.write1(absoluteFloat16); err != nil { 192 | return err 193 | } 194 | f16 := uint32toFloat16(*(*uint32)(unsafe.Pointer(&f))) 195 | buf := []byte{byte(f16 >> 8), byte(f16)} 196 | if _, err := c.write(buf); err != nil { 197 | return err 198 | } 199 | return nil 200 | } 201 | 202 | // Write four bytes into the io.Writer 203 | // as an encoded CBOR float32 204 | func (c *Composer) composeFloat32(f float32) error { 205 | if err := c.write1(absoluteFloat32); err != nil { 206 | return err 207 | } 208 | i := math.Float32bits(f) 209 | buf := []byte{byte(i >> 24), byte(i >> 16), byte(i >> 8), byte(i)} 210 | if _, err := c.write(buf); err != nil { 211 | return err 212 | } 213 | return nil 214 | } 215 | 216 | // Write eight bytes into the io.Writer 217 | // as an encoded CBOR float64 218 | func (c *Composer) composeFloat64(f float64) error { 219 | if err := c.write1(absoluteFloat64); err != nil { 220 | return err 221 | } 222 | i := math.Float64bits(f) 223 | buf := []byte{ 224 | byte(i >> 56), byte(i >> 48), byte(i >> 40), byte(i >> 32), 225 | byte(i >> 24), byte(i >> 16), byte(i >> 8), byte(i), 226 | } 227 | if _, err := c.write(buf); err != nil { 228 | return err 229 | } 230 | return nil 231 | } 232 | 233 | // Write len(b) + 1 bytes into the 234 | // io.Writer as a sequence of bytes 235 | func (c *Composer) composeBytes(b []byte, major ...Major) (err error) { 236 | m := cborByteString 237 | if len(major) != 0 { 238 | m = major[0] 239 | } 240 | l := uint(len(b)) 241 | if l <= 24 { 242 | err = c.composeInformation(m, byte(l)) 243 | } else { 244 | info, err := infoHelper(l) 245 | if err != nil { 246 | return err 247 | } 248 | err = c.composeInformation(m, info) 249 | } 250 | if err != nil { 251 | return err 252 | } 253 | if _, err := c.write(b); err != nil { 254 | return err 255 | } 256 | return nil 257 | } 258 | 259 | // Write N bytes into the io.Writer 260 | // as an encoded CBOR positive big.Int 261 | func (c *Composer) composeBigUint(n big.Int) error { 262 | if err := c.write1(absolutePositiveBigNum); err != nil { 263 | return err 264 | } 265 | return c.composeBytes(n.Bytes()) 266 | } 267 | 268 | // Write N bytes into the io.Writer 269 | // as an encoded CBOR negative big.Int 270 | func (c *Composer) composeBigInt(n big.Int) error { 271 | if err := c.write1(absoluteNegativeBigNum); err != nil { 272 | return err 273 | } 274 | buf := n.Bytes() 275 | buf[len(buf)-1]-- 276 | return c.composeBytes(buf) 277 | } 278 | 279 | // Write N bytes into the io.Writer 280 | // as an encoded CBOR epoch-based datetime 281 | func (c *Composer) composeEpochDateTime(t time.Time) error { 282 | if err := c.write1(absoluteEpochDateTime); err != nil { 283 | return err 284 | } 285 | _, err := c.composeInt(t.Unix()) 286 | return err 287 | } 288 | 289 | // Write N bytes into the io.Writer 290 | // as an encoded CBOR Big Float 291 | func (c *Composer) composeBigFloat(r big.Rat) error { 292 | if _, err := c.write([]byte{absoluteBigFloat, byte(0x82)}); err != nil { 293 | return err 294 | } 295 | f, _ := r.Float64() 296 | m, e := math.Frexp(f) 297 | if _, err := c.composeInt(int64(e)); err != nil { 298 | return err 299 | } 300 | if err := c.composeFloat64(m); err != nil { 301 | return err 302 | } 303 | return nil 304 | } 305 | 306 | // Write len(s) + 1 bytes into the 307 | // io.Writer as an UTF-8 string 308 | func (c *Composer) composeString(s string) error { 309 | return c.composeBytes([]byte(s), cborTextString) 310 | } 311 | 312 | // Write 5 bytes into the 313 | // io.Writer as a CBOR NaN value 314 | func (c *Composer) composeNaN() error { 315 | if _, err := c.write([]byte{0xfa, 0x7f, 0xc0, 0x00, 0x00}); err != nil { 316 | return err 317 | } 318 | return nil 319 | } 320 | 321 | // Write 5 bytes into the 322 | // io.Writer as a CBOR Infinity value 323 | func (c *Composer) composeInfinity(neg ...bool) error { 324 | data := []byte{0xfa, 0x7f, 0x80, 0x00, 0x00} 325 | if len(neg) > 0 && neg[0] { 326 | data = []byte{0xfa, 0xff, 0x80, 0x00, 0x00} 327 | } 328 | if _, err := c.write(data); err != nil { 329 | return err 330 | } 331 | return nil 332 | } 333 | 334 | // Write 9 bytes into the io.Writer as a 335 | // CBOR NaN value for double precission 336 | func (c *Composer) composeDoublePrecissionNaN() error { 337 | if _, err := c.write([]byte{0xfb, 0x7f, 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}); err != nil { 338 | return err 339 | } 340 | return nil 341 | } 342 | 343 | // Write 9 bytes into the io.Writer as a 344 | // CBOR Infinity value for double precission 345 | func (c *Composer) composeDoublePrecissionInfinity(neg ...bool) error { 346 | data := []byte{0xfb, 0x7f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} 347 | if len(neg) > 0 && neg[0] { 348 | data = []byte{0xfb, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} 349 | } 350 | if _, err := c.write(data); err != nil { 351 | return err 352 | } 353 | return nil 354 | } 355 | 356 | // Write 3 bytes into the io.Writer 357 | // as a CBOR NaN canonicalized float16 vlaue 358 | func (c *Composer) composeCanonicalNaN() error { 359 | if _, err := c.write([]byte{0xf9, 0x7e, 0x00}); err != nil { 360 | return err 361 | } 362 | return nil 363 | } 364 | 365 | // Write 3 bytes into the io.Writer 366 | // as a CBOR Infinity canonicalized float16 value 367 | func (c *Composer) composeCanonicalInfinity(neg ...bool) error { 368 | data := []byte{0xf9, 0x7c, 0x00} 369 | if len(neg) > 0 && neg[0] { 370 | data = []byte{0xf9, 0xfc, 0x00} 371 | } 372 | if _, err := c.write(data); err != nil { 373 | return err 374 | } 375 | return nil 376 | } 377 | 378 | // get the info code depending of the size of l 379 | func infoHelper(l uint) (byte, error) { 380 | var info byte 381 | if l <= math.MaxUint8 { 382 | info = cborUint8 383 | } else if l <= math.MaxUint16 { 384 | info = cborUint16 385 | } else if l <= math.MaxUint32 { 386 | info = cborUint32 387 | } else if l <= math.MaxUint64 { 388 | info = cborUint64 389 | } else { 390 | return 0, fmt.Errorf("totally unexpected error, []byte buf length size is unkwnown %v!", l) 391 | } 392 | return info, nil 393 | } 394 | -------------------------------------------------------------------------------- /composer_test.go: -------------------------------------------------------------------------------- 1 | // A Golang RFC7049 implementation 2 | // Copyright (C) 2015 Oscar Campos 3 | 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | 16 | package cbor 17 | 18 | import ( 19 | "bytes" 20 | "testing" 21 | ) 22 | 23 | func TestWrite(t *testing.T) { 24 | buf := bytes.NewBuffer(nil) 25 | c := NewComposer(buf) 26 | n, err := c.write([]byte{absoluteArray}) 27 | check(err) 28 | expect(n, 1, t, "TestWrite") 29 | b := []byte{0x10, 0x20, 0x30, 0x40, 0x50} 30 | expect(buf.Bytes()[0], byte(absoluteArray), t, "TestWrite") 31 | n, err = c.write(b) 32 | check(err) 33 | expect(n, 5, t, "TestWrite") 34 | for i, elem := range buf.Bytes()[1:] { 35 | expect(elem, b[i], t, "TestWrite") 36 | } 37 | } 38 | 39 | func TestComposeInt(t *testing.T) { 40 | buf := bytes.NewBuffer(nil) 41 | c := NewComposer(buf) 42 | var i int64 = 1936 43 | n, err := c.composeInt(i) 44 | check(err) 45 | expect(n, 2, t, "TestComposeInt") 46 | expect(buf.Bytes()[0], byte(0x19), t, "TestComposeInt") 47 | expect(buf.Bytes()[1], byte(0x07), t, "TestComposeInt") 48 | expect(buf.Bytes()[2], byte(0x90), t, "TestComposeInt") 49 | buf.Reset() 50 | i = 56 51 | n, err = c.composeInt(i) 52 | check(err) 53 | expect(n, 1, t, "TestComposeInt") 54 | expect(buf.Bytes()[0], byte(0x18), t, "TestComposeInt") 55 | expect(int8(buf.Bytes()[1]), int8(56), t, "TestComposeInt") 56 | buf.Reset() 57 | i = -1936 58 | n, err = c.composeInt(i) 59 | check(err) 60 | expect(n, 2, t, "TestComposeInt") 61 | expect(buf.Bytes()[0], byte(0x39), t, "TestComposeInt") 62 | expect(buf.Bytes()[1], byte(0x07), t, "TestComposeInt") 63 | expect(buf.Bytes()[2], byte(0x8f), t, "TestComposeInt") 64 | buf.Reset() 65 | i = -56 66 | n, err = c.composeInt(i) 67 | check(err) 68 | expect(n, 1, t, "TestComposeInt") 69 | expect(buf.Bytes()[0], byte(0x38), t, "TestComposeInt") 70 | expect(int8(buf.Bytes()[1]), int8(55), t, "TestComposeInt") 71 | } 72 | 73 | func TestComposeUint(t *testing.T) { 74 | buf := bytes.NewBuffer(nil) 75 | c := NewComposer(buf) 76 | var i uint64 = 67524 77 | n, err := c.composeUint(i) 78 | check(err) 79 | expect(n, 4, t, "TestComposeUint") 80 | expect(buf.Bytes()[0], byte(0x1a), t, "TestComposeUint") 81 | expect(buf.Bytes()[1], byte(0x00), t, "TestComposeUint") 82 | expect(buf.Bytes()[2], byte(0x01), t, "TestComposeUint") 83 | expect(buf.Bytes()[3], byte(0x07), t, "TestComposeUint") 84 | expect(buf.Bytes()[4], byte(0xc4), t, "TestComposeUint") 85 | buf.Reset() 86 | i = 1 87 | n, err = c.composeUint(i) 88 | check(err) 89 | expect(n, 1, t, "TestComposeUint") 90 | expect(buf.Bytes()[0], byte(0x01), t, "TestComposeUint") 91 | expect(uint8(buf.Bytes()[0]), uint8(1), t, "TestComposeUint") 92 | } 93 | 94 | func TestComposeBoolean(t *testing.T) { 95 | buf := bytes.NewBuffer(nil) 96 | c := NewComposer(buf) 97 | var v bool = false 98 | check(c.composeBoolean(v)) 99 | expect(buf.Bytes()[0], byte(0xf4), t, "TestComposeBoolean") 100 | v = true 101 | check(c.composeBoolean(v)) 102 | expect(buf.Bytes()[1], byte(0xf5), t, "TestComposeBoolean") 103 | } 104 | -------------------------------------------------------------------------------- /decoder.go: -------------------------------------------------------------------------------- 1 | // A Golang RFC7049 implementation 2 | // Copyright (C) 2015 Oscar Campos 3 | 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | 16 | package cbor 17 | 18 | import ( 19 | "encoding/base64" 20 | "errors" 21 | "fmt" 22 | "io" 23 | "math/big" 24 | "mime" 25 | "net/url" 26 | "reflect" 27 | "regexp" 28 | "time" 29 | ) 30 | 31 | // Type of function that handles decoding of extensions 32 | type handleDecFn func(*Decoder, reflect.Value) error 33 | 34 | // additional types map defined by the user 35 | type extensionDecMap map[uintptr]handleDecFn 36 | 37 | // global extensions register 38 | var extensionsDec extensionDecMap = make(extensionDecMap) 39 | 40 | // Registers a new extension in the extensions custom types register 41 | func (e *extensionDecMap) register(t reflect.Type, fn handleDecFn) error { 42 | tid := reflect.ValueOf(t).Pointer() 43 | if _, ok := extensionsDec[tid]; ok { 44 | return fmt.Errorf("%s type is already registered\n", t) 45 | } 46 | extensionsDec[tid] = fn 47 | return nil 48 | } 49 | 50 | // Look for a function registered to handle a given type 51 | func (e *extensionDecMap) lookup(t reflect.Type) (handleDecFn, error) { 52 | tid := reflect.ValueOf(t).Pointer() 53 | fn, ok := extensionsDec[tid] 54 | if !ok { 55 | return nil, errors.New(fmt.Sprintf( 56 | "%s not matched as registered extension handler", t)) 57 | } 58 | return fn, nil 59 | } 60 | 61 | // Registers a new function to hanle decode of extensions 62 | func RegisterExtensionFn(t reflect.Type, fn handleDecFn) error { 63 | return extensionsDec.register(t, fn) 64 | } 65 | 66 | // Lookup for a registered function that handles the given type decode 67 | func LookupExtensionFn(t reflect.Type) (handleDecFn, error) { 68 | return extensionsDec.lookup(t) 69 | } 70 | 71 | // A Decoder reads and decode CBOR objects from an input stream. 72 | type Decoder struct { 73 | parser *Parser 74 | strict bool 75 | } 76 | 77 | // NewDecoder returns a new decoder that reads from r. 78 | func NewDecoder(r io.Reader, options ...func(*Decoder)) *Decoder { 79 | d := &Decoder{parser: &Parser{r: r}, strict: false} 80 | if len(options) > 0 { 81 | for _, option := range options { 82 | option(d) 83 | } 84 | } 85 | return d 86 | } 87 | 88 | // Decode reads the next CBOR-encoded value from its 89 | // input and stores it in the value pointed to by v. 90 | // It also checks for the well-formedness of the 'data item' 91 | func (dec *Decoder) Decode(v interface{}) (err error) { 92 | defer func() { 93 | if r := recover(); r != nil { 94 | err = r.(error) 95 | } 96 | }() 97 | 98 | var info byte 99 | var major Major 100 | major, info, err = dec.parser.parseInformation() 101 | if err != nil { 102 | return err 103 | } 104 | if err = dec.checkTypes(reflect.TypeOf(v), major, info); err != nil { 105 | return err 106 | } 107 | switch t := v.(type) { 108 | case nil: 109 | return errors.New("can't decode a value into nil") 110 | case *uint8: 111 | *t = dec.decodeUint8() 112 | case *int8: 113 | *t = dec.decodeInt8() 114 | case *uint16: 115 | *t = dec.decodeUint16() 116 | case *int16: 117 | *t = dec.decodeInt16() 118 | case *uint32: 119 | *t = dec.decodeUint32() 120 | case *int32: 121 | *t = dec.decodeInt32() 122 | case *uint64: 123 | *t = dec.decodeUint64() 124 | case *int64: 125 | *t = dec.decodeInt64() 126 | case *float16: 127 | *t = dec.decodeFloat16() 128 | case *float32: 129 | if major == cborNC { 130 | *t = dec.decodeFloat32() 131 | } else { 132 | *t = dec.decodeDecimalFraction() 133 | } 134 | case *float64: 135 | *t = dec.decodeFloat64() 136 | case *big.Int: 137 | if v.(*big.Int).Sign() < 0 { 138 | n := dec.decodeNegativeBigNum() 139 | *t = *n.Neg(n) 140 | } else { 141 | n := dec.decodePositiveBigNum() 142 | *t = *n 143 | } 144 | case *time.Time: 145 | func() { 146 | defer func() { 147 | if r := recover(); r != nil { 148 | *t = dec.decodeEpochDateTime(struct{}{}) 149 | } 150 | }() 151 | *t = dec.decodeStringDateTime() 152 | }() 153 | case *big.Rat: 154 | n := dec.decodeBigFloat() 155 | *t = *n 156 | case *[]byte: 157 | *t = dec.decodeBytes() 158 | case *string: 159 | *t = dec.decodeString() 160 | case *bool: 161 | *t = dec.decodeBool() 162 | case *interface{}: 163 | return dec.decode(reflect.ValueOf(v).Elem()) 164 | case reflect.Value: 165 | return dec.decode(t.Elem()) 166 | default: 167 | rv := reflect.ValueOf(v) 168 | if rv.Kind() == reflect.Ptr && !rv.IsNil() || !rv.IsValid() { 169 | return dec.decode(rv.Elem()) 170 | } 171 | return &InvalidDecodeError{rv.Type()} 172 | } 173 | 174 | return err 175 | } 176 | 177 | // decode is being used when the type of the receiver of the decode 178 | // operation is a slice, a map an interface or any type of custom type 179 | func (dec *Decoder) decode(rv reflect.Value) (err error) { 180 | // Decode nil and undef into zero values 181 | if dec.parser.isNil() || dec.parser.isUndef() { 182 | if rv.Kind() == reflect.Ptr { 183 | if !rv.IsNil() { 184 | rv.Set(reflect.Zero(rv.Type())) 185 | } 186 | return nil 187 | } 188 | if rv.IsValid() && rv.CanSet() { 189 | rv.Set(reflect.Zero(rv.Type())) 190 | } 191 | return nil 192 | } 193 | var handler handleDecFn 194 | handler, err = dec.lookupFn(rv) 195 | if err != nil { 196 | return err 197 | } 198 | defer func() { 199 | if r := recover(); r != nil { 200 | err = errors.New(fmt.Sprint(r)) 201 | } 202 | }() 203 | return handler(dec, rv) 204 | } 205 | 206 | // lookup for decode function based on type Kind 207 | func (dec *Decoder) lookupFn(rv reflect.Value) (handler handleDecFn, e error) { 208 | rk := rv.Kind() 209 | switch rk { 210 | case reflect.Map: 211 | handler = (*Decoder).decodekMap 212 | case reflect.Struct: 213 | handler = (*Decoder).decodekStruct 214 | case reflect.Interface: 215 | handler = (*Decoder).decodekInterface 216 | case reflect.String: 217 | handler = (*Decoder).decodekString 218 | case reflect.Int: 219 | handler = (*Decoder).decodekInt 220 | case reflect.Int8: 221 | handler = (*Decoder).decodekInt8 222 | case reflect.Int16: 223 | handler = (*Decoder).decodekInt16 224 | case reflect.Int32: 225 | handler = (*Decoder).decodekInt32 226 | case reflect.Int64: 227 | handler = (*Decoder).decodekInt64 228 | case reflect.Uint: 229 | handler = (*Decoder).decodekUint 230 | case reflect.Uint8: 231 | handler = (*Decoder).decodekUint8 232 | case reflect.Uint16: 233 | handler = (*Decoder).decodekUint16 234 | case reflect.Uint32: 235 | handler = (*Decoder).decodekUint32 236 | case reflect.Uint64: 237 | handler = (*Decoder).decodekUint64 238 | case reflect.Bool: 239 | handler = (*Decoder).decodekBool 240 | case reflect.Float32: 241 | handler = (*Decoder).decodekFloat32 242 | case reflect.Float64: 243 | handler = (*Decoder).decodekFloat64 244 | case reflect.Slice: 245 | handler = (*Decoder).decodekSlice 246 | case reflect.Array: 247 | handler = (*Decoder).decodekArray 248 | default: 249 | handler, e = LookupExtensionFn(rv.Type()) 250 | } 251 | return handler, e 252 | } 253 | 254 | // check if the major and info types are the expected for decode and return 255 | // an error in case of the encoded data doesn't match or well-formedness errors 256 | func (dec *Decoder) checkTypes(t reflect.Type, major Major, info byte) error { 257 | if major == cborTag || major == cborDataArray || major == cborDataMap || t == reflect.TypeOf(reflect.Value{}) { 258 | return nil 259 | } 260 | msg := "expected %s, got %s (major %d, info %d [%#v])\n" 261 | e, ok := expectedTypesMap[major][info] 262 | if !ok { 263 | switch major { 264 | case cborUnsignedInt: 265 | if info <= cborSmallInt { 266 | e = reflect.PtrTo(reflect.TypeOf(uint8(0))) 267 | break 268 | } 269 | return errors.New(fmt.Sprintf("Unknown info %d for major 1", info)) 270 | case cborByteString: 271 | if info <= cborSmallInt || info == cborIndefinite { 272 | e = reflect.TypeOf([]byte{}) 273 | break 274 | } 275 | return errors.New(fmt.Sprintf("Unknown info %d for major 2", info)) 276 | case cborTextString: 277 | if info <= cborSmallInt || info == cborIndefinite { 278 | e = reflect.TypeOf("") 279 | break 280 | } 281 | return errors.New(fmt.Sprintf("Unknown info %d for major 3", info)) 282 | case cborNC: 283 | if info == cborFalse || info == cborTrue { 284 | e = reflect.TypeOf(false) 285 | break 286 | } 287 | if info == cborNil || info == cborUndef { 288 | e = reflect.TypeOf(reflect.Interface) 289 | break 290 | } 291 | return errors.New(fmt.Sprintf("Unknown info %d for major 7", info)) 292 | } 293 | } 294 | e = reflect.PtrTo(e) 295 | header := byte((major << 5)) | info 296 | if e != t { 297 | return errors.New(fmt.Sprintf(msg, t, e, major, info, header)) 298 | } 299 | return nil 300 | } 301 | 302 | // Decode into an unsigned int 303 | // of any size between 8 and 64 bits 304 | func (dec *Decoder) decodeUint() uint64 { 305 | return dec.parser.buflen() 306 | } 307 | 308 | // Decode into an signed int 309 | // of any size between 8 and 64 bits 310 | func (dec *Decoder) decodeInt() int64 { 311 | return ^int64(dec.parser.buflen()) 312 | } 313 | 314 | // Decodes into an unsigned integer of 8 bits 315 | func (dec *Decoder) decodeUint8() uint8 { 316 | return dec.parser.parseUint8() 317 | } 318 | 319 | // Decodes into an unsigned integer of 16 bits 320 | func (dec *Decoder) decodeUint16() uint16 { 321 | return dec.parser.parseUint16() 322 | } 323 | 324 | // Decodes into an unsigend integer of 32 bits 325 | func (dec *Decoder) decodeUint32() uint32 { 326 | return dec.parser.parseUint32() 327 | } 328 | 329 | // Decodes into an unsigned integer of 64 bits 330 | func (dec *Decoder) decodeUint64() uint64 { 331 | return dec.parser.parseUint64() 332 | } 333 | 334 | // Decodes into a signed integer of 8 bits 335 | func (dec *Decoder) decodeInt8() int8 { 336 | return int8(^dec.decodeUint8()) 337 | } 338 | 339 | // Decodes into a signed integer of 16 bits 340 | func (dec *Decoder) decodeInt16() int16 { 341 | return int16(^dec.decodeUint16()) 342 | } 343 | 344 | // Decodes into a signed integer of 32 bits 345 | func (dec *Decoder) decodeInt32() int32 { 346 | return int32(^dec.decodeUint32()) 347 | } 348 | 349 | // Decodes into a signed integer of 64 bits 350 | func (dec *Decoder) decodeInt64() int64 { 351 | return int64(^dec.decodeUint64()) 352 | } 353 | 354 | // Decode into a float16 355 | func (dec *Decoder) decodeFloat16() float16 { 356 | return dec.parser.parseFloat16() 357 | } 358 | 359 | // Decode into a float32 360 | func (dec *Decoder) decodeFloat32() float32 { 361 | return dec.parser.parseFloat32() 362 | } 363 | 364 | // Decode into a float64 365 | func (dec *Decoder) decodeFloat64() float64 { 366 | return dec.parser.parseFloat64() 367 | } 368 | 369 | // Decode a string date representation 370 | // that follows the standard format defined in 371 | // RFC3339 with RFC4287 Section 3.3 additions 372 | func (dec *Decoder) decodeStringDateTime() time.Time { 373 | major, _, err := dec.parser.parseInformation() 374 | checkErr(err) 375 | 376 | if major != cborTextString { 377 | panic(fmt.Errorf("expected UTF-8 string, found %v", major)) 378 | } 379 | t, err := time.Parse(time.RFC3339, dec.decodeString()) 380 | checkErr(err) 381 | return t 382 | } 383 | 384 | // Decode a positive or negative 385 | // integer or floating point with 386 | // additional information a time.Time 387 | func (dec *Decoder) decodeEpochDateTime(parseInforamtion ...struct{}) time.Time { 388 | var err error 389 | var major Major 390 | if len(parseInforamtion) == 0 { 391 | major, _, err = dec.parser.parseInformation() 392 | checkErr(err) 393 | } else { 394 | major, _ = dec.parser.parseHeader() 395 | } 396 | var n int64 397 | switch major { 398 | case cborUnsignedInt: 399 | n = int64(dec.decodeUint()) 400 | case cborNegativeInt: 401 | n = dec.decodeInt() 402 | default: 403 | switch dec.parser.header { 404 | case absoluteFloat16: 405 | n = int64(int(dec.decodeFloat16())) 406 | case absoluteFloat32: 407 | n = int64(int(dec.decodeFloat32())) 408 | case absoluteFloat64: 409 | n = int64(int(dec.decodeFloat64())) 410 | default: 411 | panic(fmt.Errorf("can't decode Epoch timestamp %v", major)) 412 | } 413 | } 414 | return time.Unix(n, int64(0)) 415 | } 416 | 417 | // Decode a decimal fraction as defined in Section 2.4.3 of RFC7049 418 | // http://tools.ietf.org/html/rfc7049#section-2.4.3 419 | func (dec *Decoder) decodeDecimalFraction() float32 { 420 | major, _, err := dec.parser.parseInformation() 421 | checkErr(err) 422 | if major != cborDataArray { 423 | panic(fmt.Errorf("Decimal Fraction must be represented as an array of two elements")) 424 | } 425 | 426 | major, _, err = dec.parser.parseInformation() 427 | checkErr(err) 428 | if major > cborNegativeInt { 429 | panic(fmt.Errorf("Can't decode %s as decimal fraction exponent", major)) 430 | } 431 | e := dec.decodeInt() 432 | major, _, err = dec.parser.parseInformation() 433 | checkErr(err) 434 | if major > cborNegativeInt { 435 | panic(fmt.Errorf("Can't decode %s as decimal fraction mantissa", major)) 436 | } 437 | var m int64 438 | if major == cborUnsignedInt { 439 | m = int64(dec.decodeUint()) 440 | } else { 441 | m = dec.decodeInt() 442 | } 443 | return decimalFractionToFloat(m, e) 444 | } 445 | 446 | // Decode a big float a defined in Section 2.3.4 of RFC7049 447 | // http://tools.ietf.org/html/rfc7049#section-2.4.3 448 | func (dec *Decoder) decodeBigFloat() *big.Rat { 449 | major, _, err := dec.parser.parseInformation() 450 | checkErr(err) 451 | if major != cborDataArray { 452 | panic("Big float must be represented as an array of two elements") 453 | } 454 | 455 | major, _, err = dec.parser.parseInformation() 456 | checkErr(err) 457 | if major > cborNegativeInt { 458 | panic(fmt.Errorf("Can't decode %s as decimal fraction exponent", major)) 459 | } 460 | e := dec.decodeInt() 461 | major, info, err := dec.parser.parseInformation() 462 | checkErr(err) 463 | if major > cborNegativeInt && (major != cborTag && info != cborBigNum) { 464 | panic(fmt.Errorf("Can't decode %s as decimal fraction mantissa", major)) 465 | } 466 | switch major { 467 | case cborUnsignedInt: 468 | m := int64(dec.decodeUint()) 469 | return bigFloatToRatFromInt64(m, e) 470 | case cborNegativeInt: 471 | m := int64(dec.decodeInt()) 472 | return bigFloatToRatFromInt64(m, e) 473 | case cborTag: 474 | m := dec.decodePositiveBigNum() 475 | return bigFloatToRatFromBigInt(m, e) 476 | } 477 | return big.NewRat(0, 0) 478 | } 479 | 480 | // Decode positive big num 481 | func (dec *Decoder) decodePositiveBigNum() *big.Int { 482 | major, _, err := dec.parser.parseInformation() 483 | checkErr(err) 484 | 485 | if major != cborByteString { 486 | panic(fmt.Errorf("expected bytes found %v", major)) 487 | } 488 | i := new(big.Int) 489 | i.SetBytes(dec.decodeBytes()) 490 | return i 491 | } 492 | 493 | // Decode negative big num 494 | func (dec *Decoder) decodeNegativeBigNum() *big.Int { 495 | major, _, err := dec.parser.parseInformation() 496 | checkErr(err) 497 | 498 | if major != cborByteString { 499 | panic(fmt.Errorf("expected bytes found %v", major)) 500 | } 501 | i := new(big.Int) 502 | i.SetBytes(dec.decodeBytes()) 503 | return i.Add(i, big.NewInt(1)) 504 | } 505 | 506 | // Decode a base64 url 507 | func (dec *Decoder) decodeBase64Url() []byte { 508 | major, _, err := dec.parser.parseInformation() 509 | checkErr(err) 510 | 511 | if major != cborByteString && major != cborTextString { 512 | panic(fmt.Errorf("expected string or bytes found %v", major)) 513 | } 514 | data := dec.decodeBytes() 515 | var buf []byte = make([]byte, base64.URLEncoding.EncodedLen(len(data))) 516 | base64.URLEncoding.Encode(buf, data) 517 | return buf 518 | } 519 | 520 | // Decode a base64 string 521 | func (dec *Decoder) decodeBase64() []byte { 522 | major, _, err := dec.parser.parseInformation() 523 | checkErr(err) 524 | 525 | if major != cborByteString && major != cborTextString { 526 | panic(fmt.Errorf("expected string or bytes found %v", major)) 527 | } 528 | data := dec.decodeBytes() 529 | var buf []byte = make([]byte, base64.StdEncoding.EncodedLen(len(data))) 530 | base64.StdEncoding.Encode(buf, data) 531 | return buf 532 | } 533 | 534 | // Decode a base16 string 535 | func (dec *Decoder) decodeBase16() []byte { 536 | major, _, err := dec.parser.parseInformation() 537 | checkErr(err) 538 | 539 | if major != cborByteString && major != cborTextString { 540 | panic(fmt.Errorf("expected string or bytes found %v", major)) 541 | } 542 | data := dec.decodeBytes() 543 | return []byte(fmt.Sprintf("%x", data)) 544 | } 545 | 546 | // Read the following byte string as raw bytes data 547 | func (dec *Decoder) decodeDataItem() []byte { 548 | major, _, err := dec.parser.parseInformation() 549 | checkErr(err) 550 | 551 | if major != cborByteString { 552 | panic(fmt.Errorf("expected bytes found %v", major)) 553 | } 554 | return dec.decodeBytes() 555 | } 556 | 557 | // Decode a UTF8 URI 558 | func (dec *Decoder) decodeURI() *url.URL { 559 | major, _, err := dec.parser.parseInformation() 560 | checkErr(err) 561 | 562 | if major != cborTextString { 563 | panic(fmt.Errorf("expected string found %v", major)) 564 | } 565 | uri, err := url.Parse(dec.decodeString()) 566 | checkErr(err) 567 | return uri 568 | } 569 | 570 | // Decode a UTF8 base64 encoded URI 571 | func (dec *Decoder) decodeBase64URI() *url.URL { 572 | major, _, err := dec.parser.parseInformation() 573 | checkErr(err) 574 | 575 | if major != cborTextString { 576 | panic(fmt.Errorf("expected string found %v", major)) 577 | } 578 | decodedUrl, err := base64.URLEncoding.DecodeString(dec.decodeString()) 579 | checkErr(err) 580 | uri, err := url.Parse(string(decodedUrl)) 581 | checkErr(err) 582 | return uri 583 | } 584 | 585 | // Decode a UTF8 base64 encoded string 586 | func (dec *Decoder) decodeBase64String() string { 587 | major, _, err := dec.parser.parseInformation() 588 | checkErr(err) 589 | 590 | if major != cborTextString { 591 | panic(fmt.Errorf("expected string found %v", major)) 592 | } 593 | decodedBytes, err := base64.StdEncoding.DecodeString(dec.decodeString()) 594 | checkErr(err) 595 | return string(decodedBytes) 596 | } 597 | 598 | // Decode an UTF8 Regular Expression 599 | func (dec *Decoder) decodeRegexp() *regexp.Regexp { 600 | major, _, err := dec.parser.parseInformation() 601 | checkErr(err) 602 | 603 | if major != cborTextString { 604 | panic(fmt.Errorf("expected string found %v", major)) 605 | } 606 | re, err := regexp.Compile(dec.decodeString()) 607 | checkErr(err) 608 | return re 609 | } 610 | 611 | // Decode a UTF8 MIME Message 612 | func (dec *Decoder) decodeMime() *CBORMIME { 613 | var mediatype string 614 | var params map[string]string 615 | 616 | major, _, err := dec.parser.parseInformation() 617 | checkErr(err) 618 | 619 | if major != cborTextString { 620 | panic(fmt.Errorf("expected string found %v", major)) 621 | } 622 | mediatype, params, err = mime.ParseMediaType(dec.decodeString()) 623 | checkErr(err) 624 | return &CBORMIME{mediatype, params} 625 | } 626 | 627 | // Decode into a byte string 628 | func (dec *Decoder) decodeBytes() []byte { 629 | _, info := dec.parser.parseHeader() 630 | if dec.parser.isNil() || dec.parser.isUndef() { 631 | return nil 632 | } 633 | 634 | if info != cborIndefinite { 635 | _, d, err := dec.parser.scan(int(dec.parser.buflen())) 636 | checkErr(err) 637 | return d 638 | } 639 | 640 | return dec.decodeIndefiniteBytes(nil) 641 | } 642 | 643 | // Decode an UTF8 text string 644 | func (dec *Decoder) decodeString() string { 645 | return string(dec.decodeBytes()) 646 | } 647 | 648 | // decode an indefinite stream of bytes 649 | // it doesn't really decode it, just read it and returns it back 650 | func (dec *Decoder) decodeIndefiniteBytes(buf []byte) []byte { 651 | for { 652 | if dec.parser.isBreak() { 653 | break 654 | } 655 | buflen := int(dec.parser.buflen()) 656 | n, d, err := dec.parser.scan(buflen) 657 | checkErr(err) 658 | if n < buflen { 659 | panic(fmt.Errorf("expected %d bytes in buffer, got %d", buflen, n)) 660 | } 661 | buf = append(buf, d...) 662 | if _, _, err := dec.parser.parseInformation(); err != nil { 663 | panic(err) 664 | } 665 | } 666 | return buf 667 | } 668 | 669 | // Decode into a boolean value 670 | func (dec *Decoder) decodeBool() bool { 671 | return dec.parser.parseBool() 672 | } 673 | 674 | // helper function that panics if err is not nil 675 | func checkErr(err error) { 676 | if err != nil { 677 | panic(err.Error()) 678 | } 679 | } 680 | -------------------------------------------------------------------------------- /decoder_test.go: -------------------------------------------------------------------------------- 1 | // A Golang RFC7049 implementation 2 | // Copyright (C) 2015 Oscar Campos 3 | 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | 16 | package cbor 17 | 18 | import ( 19 | "bytes" 20 | "fmt" 21 | "io/ioutil" 22 | "log" 23 | "net/url" 24 | 25 | "math/big" 26 | 27 | "os" 28 | "reflect" 29 | "regexp" 30 | "testing" 31 | "time" 32 | ) 33 | 34 | func TestMain(m *testing.M) { 35 | log.SetOutput(ioutil.Discard) 36 | os.Exit(m.Run()) 37 | } 38 | 39 | func TestDecodeUint8(t *testing.T) { 40 | buf := []byte{0x18, 0x6f} 41 | r := bytes.NewReader(buf) 42 | d := NewDecoder(r) 43 | var a uint8 44 | check(d.Decode(&a)) 45 | expect(uint8(111), a, t, "TestDecodeUint8") 46 | 47 | buf = []byte{0x38, 0x6f} 48 | r = bytes.NewReader(buf) 49 | d = NewDecoder(r) 50 | expect(d.Decode(&a) != nil, true, t, "TestDecodeUint8") 51 | 52 | buf = []byte{0x19, 0x6f, 0x00} 53 | r = bytes.NewReader(buf) 54 | d = NewDecoder(r) 55 | expect(d.Decode(&a) != nil, true, t, "TestDecodeUint8") 56 | } 57 | 58 | func TestDecodeInt8(t *testing.T) { 59 | buf := []byte{0x38, 0x6f} 60 | r := bytes.NewReader(buf) 61 | d := NewDecoder(r) 62 | var a int8 63 | check(d.Decode(&a)) 64 | expect(int8(-112), a, t) 65 | 66 | buf = []byte{0x18, 0x6f} 67 | r = bytes.NewReader(buf) 68 | d = NewDecoder(r) 69 | expect(d.Decode(&a) != nil, true, t) 70 | 71 | buf = []byte{0x39, 0x6f, 0x00} 72 | r = bytes.NewReader(buf) 73 | d = NewDecoder(r) 74 | expect(d.Decode(&a) != nil, true, t) 75 | } 76 | 77 | func TestDecodeUint16(t *testing.T) { 78 | buf := []byte{0x19, 0x45, 0xab} 79 | r := bytes.NewReader(buf) 80 | d := NewDecoder(r) 81 | var a uint16 82 | check(d.Decode(&a)) 83 | expect(uint16(17835), a, t) 84 | 85 | buf = []byte{0x39, 0x45, 0xab} 86 | r = bytes.NewReader(buf) 87 | d = NewDecoder(r) 88 | expect(d.Decode(&a) != nil, true, t) 89 | 90 | buf = []byte{0x1a, 0x45, 0xab, 0x00, 0x00} 91 | r = bytes.NewReader(buf) 92 | d = NewDecoder(r) 93 | expect(d.Decode(&a) != nil, true, t) 94 | } 95 | 96 | func TestDecodeInt16(t *testing.T) { 97 | buf := []byte{0x39, 0x45, 0xab} 98 | r := bytes.NewReader(buf) 99 | d := NewDecoder(r) 100 | var a int16 101 | check(d.Decode(&a)) 102 | expect(int16(-17836), a, t) 103 | 104 | buf = []byte{0x19, 0x45, 0xab} 105 | r = bytes.NewReader(buf) 106 | d = NewDecoder(r) 107 | expect(d.Decode(&a) != nil, true, t) 108 | 109 | buf = []byte{0x38, 0x45, 0xab} 110 | r = bytes.NewReader(buf) 111 | d = NewDecoder(r) 112 | expect(d.Decode(&a) != nil, true, t) 113 | } 114 | 115 | func TestDecodeUint32(t *testing.T) { 116 | buf := []byte{0x1a, 0x45, 0xab, 0x23, 0x00} 117 | r := bytes.NewReader(buf) 118 | d := NewDecoder(r) 119 | var a uint32 120 | check(d.Decode(&a)) 121 | expect(uint32(1168843520), a, t) 122 | 123 | buf = []byte{0x3a, 0x45, 0xab, 0x23, 0x00} 124 | r = bytes.NewReader(buf) 125 | d = NewDecoder(r) 126 | expect(d.Decode(&a) != nil, true, t) 127 | 128 | buf = []byte{0x19, 0x45, 0xab, 0x23, 0x00} 129 | r = bytes.NewReader(buf) 130 | d = NewDecoder(r) 131 | expect(d.Decode(&a) != nil, true, t) 132 | } 133 | 134 | func TestDecodeInt32(t *testing.T) { 135 | buf := []byte{0x3a, 0x45, 0xab, 0x23, 0x00} 136 | r := bytes.NewReader(buf) 137 | d := NewDecoder(r) 138 | var a int32 139 | check(d.Decode(&a)) 140 | expect(int32(-1168843521), a, t) 141 | 142 | buf = []byte{0x1a, 0x45, 0xab, 0x23, 0x00} 143 | r = bytes.NewReader(buf) 144 | d = NewDecoder(r) 145 | expect(d.Decode(&a) != nil, true, t) 146 | 147 | buf = []byte{0x39, 0x45, 0xab, 0x23, 0x00} 148 | r = bytes.NewReader(buf) 149 | d = NewDecoder(r) 150 | expect(d.Decode(&a) != nil, true, t) 151 | } 152 | 153 | func TestDecodeUint64(t *testing.T) { 154 | buf := []byte{0x1b, 0x45, 0xab, 0x23, 0x00, 0x10, 0x11, 0x12, 0x13} 155 | r := bytes.NewReader(buf) 156 | d := NewDecoder(r) 157 | var a uint64 158 | check(d.Decode(&a)) 159 | expect(uint64(5020144692811076115), a, t) 160 | 161 | buf = []byte{0x3b, 0x45, 0xab, 0x23, 0x00, 0x10, 0x11, 0x12, 0x13} 162 | r = bytes.NewReader(buf) 163 | d = NewDecoder(r) 164 | expect(d.Decode(&a) != nil, true, t) 165 | 166 | buf = []byte{0x19, 0x45, 0xab, 0x23, 0x00, 0x10, 0x11, 0x12, 0x13} 167 | r = bytes.NewReader(buf) 168 | d = NewDecoder(r) 169 | expect(d.Decode(&a) != nil, true, t) 170 | } 171 | 172 | func TestDecodeInt64(t *testing.T) { 173 | buf := []byte{0x3b, 0x45, 0xab, 0x23, 0x00, 0x10, 0x11, 0x12, 0x13} 174 | r := bytes.NewReader(buf) 175 | d := NewDecoder(r) 176 | var a int64 177 | check(d.Decode(&a)) 178 | expect(int64(-5020144692811076116), a, t) 179 | 180 | buf = []byte{0x1b, 0x45, 0xab, 0x23, 0x00, 0x10, 0x11, 0x12, 0x13} 181 | r = bytes.NewReader(buf) 182 | d = NewDecoder(r) 183 | expect(d.Decode(&a) != nil, true, t) 184 | 185 | buf = []byte{0x39, 0x45, 0xab, 0x23, 0x00, 0x10, 0x11, 0x12, 0x13} 186 | r = bytes.NewReader(buf) 187 | d = NewDecoder(r) 188 | expect(d.Decode(&a) != nil, true, t) 189 | } 190 | 191 | func TestDecodeFloat16(t *testing.T) { 192 | buf := []byte{0xf9, 0x3f, 0xe0} 193 | r := bytes.NewReader(buf) 194 | d := NewDecoder(r) 195 | var a float16 196 | check(d.Decode(&a)) 197 | expect(float16(1.96875), a, t) 198 | 199 | buf = []byte{0xf9, 0x3c, 0x00} 200 | r = bytes.NewReader(buf) 201 | d = NewDecoder(r) 202 | check(d.Decode(&a)) 203 | expect(float16(1.0), a, t) 204 | 205 | } 206 | 207 | func TestDecodeFloat32(t *testing.T) { 208 | buf := []byte{0xfa, 0x3f, 0x66, 0x66, 0x66} 209 | r := bytes.NewReader(buf) 210 | d := NewDecoder(r) 211 | var a float32 212 | check(d.Decode(&a)) 213 | expect(float32(0.9), a, t) 214 | 215 | buf = []byte{0xfb, 0x40, 0x63, 0x8e, 0xa6, 0xb7, 0x23, 0xee, 0x1c} 216 | r = bytes.NewReader(buf) 217 | d = NewDecoder(r) 218 | expect(d.Decode(&a) != nil, true, t) 219 | } 220 | 221 | func TestDecodeFloat64(t *testing.T) { 222 | buf := []byte{0xfb, 0x40, 0x63, 0x8e, 0xa6, 0xb7, 0x23, 0xee, 0x1c} 223 | r := bytes.NewReader(buf) 224 | d := NewDecoder(r) 225 | var a float64 226 | check(d.Decode(&a)) 227 | expect(float64(156.457851), a, t) 228 | 229 | buf = []byte{0xfa, 0x40, 0x63, 0x8e, 0xa6, 0xb7, 0x23, 0xee, 0x1c} 230 | r = bytes.NewReader(buf) 231 | d = NewDecoder(r) 232 | expect(d.Decode(&a) != nil, true, t) 233 | } 234 | 235 | func TestDecodeBytes(t *testing.T) { 236 | buf := []byte{0x4c, 0x62, 0x79, 0x74, 0x65, 0x73, 0x20, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67} 237 | r := bytes.NewReader(buf) 238 | d := NewDecoder(r) 239 | var a []byte 240 | check(d.Decode(&a)) 241 | expect("bytes string", string(a), t) 242 | } 243 | 244 | func TestDecodeString(t *testing.T) { 245 | buf := []byte{0x67, 0x65, 0x73, 0x70, 0x61, 0xc3, 0xb1, 0x61} 246 | r := bytes.NewReader(buf) 247 | d := NewDecoder(r) 248 | var a string 249 | check(d.Decode(&a)) 250 | expect("españa", a, t) 251 | } 252 | 253 | func TestDecodeBool(t *testing.T) { 254 | buf := []byte{0xf4} 255 | r := bytes.NewReader(buf) 256 | d := NewDecoder(r) 257 | var a bool 258 | check(d.Decode(&a)) 259 | expect(false, a, t) 260 | 261 | buf = []byte{0xf5} 262 | r = bytes.NewReader(buf) 263 | d = NewDecoder(r) 264 | check(d.Decode(&a)) 265 | expect(true, a, t) 266 | } 267 | 268 | func TestDecodeIndefiniteBytes(t *testing.T) { 269 | buf := []byte{0x5f, 0x4c, 0x62, 0x79, 0x74, 0x65, 0x73, 0x20, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67, 0x43, 0x20, 0x78, 0x44, 0xff} 270 | r := bytes.NewReader(buf) 271 | d := NewDecoder(r) 272 | var a []byte 273 | check(d.Decode(&a)) 274 | expect("bytes string xD", string(a), t) 275 | } 276 | 277 | func TestDecodeIndefiniteString(t *testing.T) { 278 | buf := []byte{0x7f, 0x63, 0xe4, 0xb8, 0x96, 0x63, 0xe7, 0x95, 0x8c, 0xff} 279 | r := bytes.NewReader(buf) 280 | d := NewDecoder(r) 281 | var a string 282 | check(d.Decode(&a)) 283 | expect("世界", a, t) 284 | } 285 | 286 | func TestDecodeKInt(t *testing.T) { 287 | buf := []byte{0x3a, 0x45, 0xab, 0x23, 0x00} 288 | r := bytes.NewReader(buf) 289 | d := NewDecoder(r) 290 | var a int32 291 | check(d.Decode(reflect.ValueOf(&a))) 292 | expect(int32(-1168843521), a, t) 293 | 294 | buf = []byte{0x39, 0x45, 0xab, 0x23, 0x00} 295 | r = bytes.NewReader(buf) 296 | d = NewDecoder(r) 297 | expect(d.Decode(reflect.ValueOf(&a)) != nil, true, t) 298 | } 299 | 300 | func TestDecodeKUint(t *testing.T) { 301 | buf := []byte{0x1a, 0x45, 0xab, 0x23, 0x00} 302 | r := bytes.NewReader(buf) 303 | d := NewDecoder(r) 304 | var a uint32 305 | check(d.Decode(reflect.ValueOf(&a))) 306 | expect(uint32(1168843520), a, t) 307 | 308 | buf = []byte{0x19, 0x45, 0xab, 0x23, 0x00} 309 | r = bytes.NewReader(buf) 310 | d = NewDecoder(r) 311 | expect(d.Decode(reflect.ValueOf(&a)) != nil, true, t) 312 | } 313 | 314 | func TestDecodeUnsignedIntsArray(t *testing.T) { 315 | buf := []byte{0x84, 0x04, 0x09, 0x19, 0x04, 0x00, 0x10} 316 | r := bytes.NewReader(buf) 317 | d := NewDecoder(r) 318 | var a []uint 319 | check(d.Decode(&a)) 320 | expected := []uint{4, 9, 1024, 16} 321 | for i, e := range a { 322 | expect(expected[i], e, t) 323 | } 324 | } 325 | 326 | func TestDecodeUnsignedIntsIndefiniteArray(t *testing.T) { 327 | buf := []byte{0x9f, 0x04, 0x09, 0x19, 0x04, 0x00, 0x10, 0xff} 328 | r := bytes.NewReader(buf) 329 | d := NewDecoder(r) 330 | var a []uint 331 | check(d.Decode(&a)) 332 | expected := []uint{4, 9, 1024, 16} 333 | for i, e := range a { 334 | expect(expected[i], e, t) 335 | } 336 | } 337 | 338 | func TestDecodeArrayOfUin32(t *testing.T) { 339 | buf := []byte{0x81, 0x1a, 0x45, 0xab, 0x23, 0x00} 340 | r := bytes.NewReader(buf) 341 | d := NewDecoder(r) 342 | var a [1]uint32 343 | check(d.Decode(&a)) 344 | expected := [1]uint32{1168843520} 345 | expect(expected[0], a[0], t) 346 | expect(expected, a, t) 347 | } 348 | 349 | func TestDecodeEmptyArray(t *testing.T) { 350 | buf := []byte{0x80} 351 | r := bytes.NewReader(buf) 352 | d := NewDecoder(r) 353 | var a []bool 354 | check(d.Decode(&a)) 355 | expect(len(a) == 0, true, t) 356 | } 357 | 358 | func TestDecodeInterface(t *testing.T) { 359 | buf := []byte{0x85, 0x04, 0x09, 0x19, 0x04, 0x00, 0x10, 0x83, 0x01, 0x02, 0x67, 0x65, 0x73, 0x70, 0x61, 0xc3, 0xb1, 0x61} 360 | r := bytes.NewReader(buf) 361 | d := NewDecoder(r) 362 | var a interface{} 363 | check(d.Decode(&a)) 364 | av := *a.(*[]interface{}) 365 | expected := []interface{}{uint8(4), uint8(9), uint16(1024), uint8(16)} 366 | for i := 0; i < 4; i++ { 367 | expect(expected[i], av[i], t) 368 | } 369 | aiv := *av[4].(*[]interface{}) 370 | expect(aiv[0], uint8(1), t) 371 | expect(aiv[1], uint8(2), t) 372 | expect(aiv[2], "españa", t) 373 | } 374 | 375 | func TestDecodeMap(t *testing.T) { 376 | buf := []byte{0xa2, 0x63, 0x46, 0x75, 0x6e, 0xf5, 0x63, 0x41, 0x6d, 0x74, 0x21} 377 | r := bytes.NewReader(buf) 378 | d := NewDecoder(r) 379 | var a map[string]interface{} 380 | check(d.Decode(&a)) 381 | v1, ok := a["Fun"] 382 | expect(ok, true, t) 383 | expect(v1, true, t) 384 | v2, ok := a["Amt"] 385 | expect(ok, true, t) 386 | expect(v2, int8(-2), t) 387 | } 388 | 389 | func TestDecodeStrictMap(t *testing.T) { 390 | buf := []byte{0xa2, 0x63, 0x46, 0x75, 0x6e, 0xf5, 0x63, 0x46, 0x75, 0x6e, 0x21} 391 | r := bytes.NewReader(buf) 392 | d := NewDecoder(r, func(dec *Decoder) { dec.strict = true }) 393 | var a map[string]interface{} 394 | err := d.Decode(&a) 395 | expect(err != nil, true, t) 396 | 397 | buf = []byte{0xa2, 0x63, 0x46, 0x75, 0x6e, 0xf5, 0x63, 0x46, 0x75, 0x6e, 0x21} 398 | r = bytes.NewReader(buf) 399 | d = NewDecoder(r, func(dec *Decoder) { dec.strict = false }) 400 | var a2 map[string]interface{} 401 | err = d.Decode(&a2) 402 | expect(len(a2), 1, t) 403 | _, ok := a["Fun"] 404 | expect(ok, true, t) 405 | } 406 | 407 | func TestDecodeIndefiniteMap(t *testing.T) { 408 | buf := []byte{0xbf, 0x63, 0x46, 0x75, 0x6e, 0xf5, 0x63, 0x41, 0x6d, 0x74, 0x21, 0xff} 409 | r := bytes.NewReader(buf) 410 | d := NewDecoder(r) 411 | var a map[string]interface{} 412 | check(d.Decode(&a)) 413 | v1, ok := a["Fun"] 414 | expect(ok, true, t) 415 | expect(v1, true, t) 416 | v2, ok := a["Amt"] 417 | expect(ok, true, t) 418 | expect(v2, int8(-2), t) 419 | } 420 | 421 | func TestDecodeInterfaceKeyInterfaceValueMap(t *testing.T) { 422 | buf := []byte{0xa2, 0x63, 0x46, 0x75, 0x6e, 0xf5, 0x63, 0x41, 0x6d, 0x74, 0x21} 423 | r := bytes.NewReader(buf) 424 | d := NewDecoder(r) 425 | var a map[interface{}]interface{} 426 | check(d.Decode(&a)) 427 | v1, ok := a["Fun"] 428 | expect(ok, true, t) 429 | expect(v1, true, t) 430 | v2, ok := a["Amt"] 431 | expect(ok, true, t) 432 | expect(v2, int8(-2), t) 433 | } 434 | 435 | func TestDecodeMapIntoInterface(t *testing.T) { 436 | buf := []byte{0xa2, 0x63, 0x46, 0x75, 0x6e, 0xf5, 0x63, 0x41, 0x6d, 0x74, 0x21} 437 | r := bytes.NewReader(buf) 438 | d := NewDecoder(r) 439 | var a interface{} 440 | check(d.Decode(&a)) 441 | av := *a.(*map[interface{}]interface{}) 442 | v1, ok := av["Fun"] 443 | expect(ok, true, t) 444 | expect(v1, true, t) 445 | v2, ok := av["Amt"] 446 | expect(ok, true, t) 447 | expect(v2, int8(-2), t) 448 | } 449 | 450 | func TestDecodeMapIntoStruct(t *testing.T) { 451 | buf := []byte{0xa2, 0x63, 0x46, 0x75, 0x6e, 0xf5, 0x63, 0x41, 0x6d, 0x74, 0x21} 452 | r := bytes.NewReader(buf) 453 | d := NewDecoder(r) 454 | type MyType struct { 455 | Fun bool 456 | Amt int8 457 | } 458 | var a MyType 459 | check(d.Decode(&a)) 460 | expect(a.Fun, true, t) 461 | expect(a.Amt, int8(-2), t) 462 | } 463 | 464 | func TestDecodeIndefiniteMapIntoStruct(t *testing.T) { 465 | buf := []byte{0xbf, 0x63, 0x46, 0x75, 0x6e, 0xf5, 0x63, 0x41, 0x6d, 0x74, 0x21, 0xff} 466 | r := bytes.NewReader(buf) 467 | d := NewDecoder(r) 468 | type MyType struct { 469 | Fun bool 470 | Amt int8 471 | } 472 | var a MyType 473 | check(d.Decode(&a)) 474 | expect(a.Fun, true, t) 475 | expect(a.Amt, int8(-2), t) 476 | } 477 | 478 | func TestDecodeDuplicateKeysMapIntoStruct(t *testing.T) { 479 | buf := []byte{0xa2, 0x63, 0x46, 0x75, 0x6e, 0xf5, 0x63, 0x46, 0x75, 0x6e, 0x21} 480 | r := bytes.NewReader(buf) 481 | d := NewDecoder(r) 482 | type MyType struct { 483 | Fun bool 484 | Amt int8 485 | } 486 | var a MyType 487 | check(d.Decode(&a)) 488 | expect(a.Fun, true, t) 489 | expect(a.Amt, int8(0), t) // is not set 490 | } 491 | 492 | func TestDecodeDuplicateKeysMapIntoStructStrictMode(t *testing.T) { 493 | buf := []byte{0xa2, 0x63, 0x46, 0x75, 0x6e, 0xf5, 0x63, 0x46, 0x75, 0x6e, 0x21} 494 | r := bytes.NewReader(buf) 495 | d := NewDecoder(r, func(dec *Decoder) { dec.strict = true }) 496 | type MyType struct { 497 | Fun bool 498 | Amt int8 499 | } 500 | var a MyType 501 | err := d.Decode(&a) 502 | expect(err != nil, true, t) 503 | expect(fmt.Sprint(err), "strict-mode: duplicated key Fun in map", t) 504 | } 505 | 506 | func TestDecodeMapIntoStructNonStringKeys(t *testing.T) { 507 | buf := []byte{0xa2, 0x10, 0xf5, 0x11, 0x21} 508 | r := bytes.NewReader(buf) 509 | d := NewDecoder(r) 510 | type MyType struct { 511 | Fun bool 512 | Amt int8 513 | } 514 | var a MyType 515 | err := d.Decode(&a) 516 | expect(err != nil, true, t) 517 | expect(fmt.Sprint(err), "map keys must be string, cborUnsignedInt received", t) 518 | } 519 | 520 | func TestDecodeMapNonFieldIntoStruct(t *testing.T) { 521 | buf := []byte{0xa2, 0x63, 0x46, 0x75, 0x6e, 0xf5, 0x63, 0x41, 0x6d, 0x74, 0x21} 522 | r := bytes.NewReader(buf) 523 | d := NewDecoder(r) 524 | type MyType struct { 525 | Fun bool 526 | } 527 | var a MyType 528 | check(d.Decode(&a)) 529 | expect(a.Fun, true, t) 530 | } 531 | 532 | func TestDecodeMapNonFieldIntoStructWithValidTag(t *testing.T) { 533 | buf := []byte{0xa2, 0x63, 0x46, 0x75, 0x6e, 0xf5, 0x63, 0x41, 0x6d, 0x74, 0x21} 534 | r := bytes.NewReader(buf) 535 | d := NewDecoder(r) 536 | type MyType struct { 537 | Fun bool 538 | Other int8 `cbor:"Amt"` 539 | } 540 | var a MyType 541 | check(d.Decode(&a)) 542 | expect(a.Fun, true, t) 543 | expect(a.Other, int8(-2), t) 544 | } 545 | 546 | func TestDecodeIndefiniteMapNonFieldIntoStruct(t *testing.T) { 547 | buf := []byte{0xbf, 0x63, 0x46, 0x75, 0x6e, 0xf5, 0x63, 0x41, 0x6d, 0x74, 0x21, 0xff} 548 | r := bytes.NewReader(buf) 549 | d := NewDecoder(r) 550 | type MyType struct { 551 | Fun bool 552 | } 553 | var a MyType 554 | check(d.Decode(&a)) 555 | expect(a.Fun, true, t) 556 | } 557 | 558 | func TestDecodeMapNonFieldIntoStructStrictMode(t *testing.T) { 559 | buf := []byte{0xa2, 0x63, 0x46, 0x75, 0x6e, 0xf5, 0x63, 0x41, 0x6d, 0x74, 0x21} 560 | r := bytes.NewReader(buf) 561 | d := NewDecoder(r, func(dec *Decoder) { dec.strict = true }) 562 | type MyType struct { 563 | Fun bool 564 | None int8 565 | } 566 | var a MyType 567 | err := d.Decode(&a) 568 | expect(err != nil, true, t) 569 | expect(fmt.Sprint(err), "strict-mode: key Amt doesn't match with any field", t) 570 | } 571 | 572 | func TestDecodeMapOutboundsIntoStruct(t *testing.T) { 573 | buf := []byte{0xa3, 0x63, 0x46, 0x75, 0x6e, 0xf5, 0x63, 0x41, 0x6d, 0x74, 0x21, 0x64, 0x46, 0x61, 0x69, 0x6c, 0x04} 574 | r := bytes.NewReader(buf) 575 | d := NewDecoder(r) 576 | type MyType struct { 577 | Fun bool 578 | Amt int8 579 | } 580 | var a MyType 581 | check(d.Decode(&a)) 582 | expect(a.Fun, true, t) 583 | expect(a.Amt, int8(-2), t) 584 | expect(r.Len(), 0, t) 585 | } 586 | 587 | func TestDecodeMapOutboundsIntoStructStrictMode(t *testing.T) { 588 | buf := []byte{0xa3, 0x63, 0x46, 0x75, 0x6e, 0xf5, 0x63, 0x41, 0x6d, 0x74, 0x21, 0x64, 0x46, 0x61, 0x69, 0x6c, 0x04} 589 | r := bytes.NewReader(buf) 590 | d := NewDecoder(r, func(dec *Decoder) { dec.strict = true }) 591 | type MyType struct { 592 | Fun bool 593 | Amt int8 594 | } 595 | var a MyType 596 | err := d.Decode(&a) 597 | expect(err != nil, true, t) 598 | expect(fmt.Sprint(err), "strict-mode: destination struct fields num 2 doesn't match map length 3", t) 599 | } 600 | 601 | func TestDecodeArrayIntoStruct(t *testing.T) { 602 | buf := []byte{0x84, 0x63, 0x46, 0x75, 0x6e, 0xf5, 0x63, 0x41, 0x6d, 0x74, 0x21} 603 | r := bytes.NewReader(buf) 604 | d := NewDecoder(r) 605 | type MyType struct { 606 | Fun bool 607 | Amt int8 608 | } 609 | var a MyType 610 | check(d.Decode(&a)) 611 | expect(a.Fun, true, t) 612 | expect(a.Amt, int8(-2), t) 613 | expect(r.Len(), 0, t) 614 | } 615 | 616 | func TestDecodeIndefiniteArrayIntoStruct(t *testing.T) { 617 | buf := []byte{0x8f, 0x63, 0x46, 0x75, 0x6e, 0xf5, 0x63, 0x41, 0x6d, 0x74, 0x21, 0xff} 618 | r := bytes.NewReader(buf) 619 | d := NewDecoder(r) 620 | type MyType struct { 621 | Fun bool 622 | Amt int8 623 | } 624 | var a MyType 625 | check(d.Decode(&a)) 626 | expect(a.Fun, true, t) 627 | expect(a.Amt, int8(-2), t) 628 | } 629 | 630 | func TestDecodeDuplicateKeysArrayIntoStruct(t *testing.T) { 631 | buf := []byte{0x84, 0x63, 0x46, 0x75, 0x6e, 0xf5, 0x63, 0x46, 0x75, 0x6e, 0x21} 632 | r := bytes.NewReader(buf) 633 | d := NewDecoder(r) 634 | type MyType struct { 635 | Fun bool 636 | Amt int8 637 | } 638 | var a MyType 639 | check(d.Decode(&a)) 640 | expect(a.Fun, true, t) 641 | expect(a.Amt, int8(0), t) // is not set 642 | } 643 | 644 | func TestDecodeDuplicateKeysArrayIntoStructStrictMode(t *testing.T) { 645 | buf := []byte{0x84, 0x63, 0x46, 0x75, 0x6e, 0xf5, 0x63, 0x46, 0x75, 0x6e, 0x21} 646 | r := bytes.NewReader(buf) 647 | d := NewDecoder(r, func(dec *Decoder) { dec.strict = true }) 648 | type MyType struct { 649 | Fun bool 650 | Amt int8 651 | } 652 | var a MyType 653 | err := d.Decode(&a) 654 | expect(err != nil, true, t) 655 | expect(fmt.Sprint(err), "strict-mode: duplicated key Fun in map", t) 656 | } 657 | 658 | func TestDecodeArrayIntoStructNonStringKeys(t *testing.T) { 659 | buf := []byte{0x84, 0x10, 0xf5, 0x11, 0x21} 660 | r := bytes.NewReader(buf) 661 | d := NewDecoder(r) 662 | type MyType struct { 663 | Fun bool 664 | Amt int8 665 | } 666 | var a MyType 667 | err := d.Decode(&a) 668 | expect(err != nil, true, t) 669 | expect(fmt.Sprint(err), "array keys must be string, cborUnsignedInt received", t) 670 | } 671 | 672 | func TestDecodeArrayNonFieldIntoStruct(t *testing.T) { 673 | buf := []byte{0x84, 0x63, 0x46, 0x75, 0x6e, 0xf5, 0x63, 0x41, 0x6d, 0x74, 0x21} 674 | r := bytes.NewReader(buf) 675 | d := NewDecoder(r) 676 | type MyType struct { 677 | Fun bool 678 | } 679 | var a MyType 680 | check(d.Decode(&a)) 681 | expect(a.Fun, true, t) 682 | } 683 | 684 | func TestDecodeArrayNonFieldIntoStructWithValidTag(t *testing.T) { 685 | buf := []byte{0x84, 0x63, 0x46, 0x75, 0x6e, 0xf5, 0x63, 0x41, 0x6d, 0x74, 0x21} 686 | r := bytes.NewReader(buf) 687 | d := NewDecoder(r) 688 | type MyType struct { 689 | Fun bool 690 | Other int8 `cbor:"Amt"` 691 | } 692 | var a MyType 693 | check(d.Decode(&a)) 694 | expect(a.Fun, true, t) 695 | expect(a.Other, int8(-2), t) 696 | } 697 | 698 | func TestDecodeIndefiniteArrayNonFieldIntoStruct(t *testing.T) { 699 | buf := []byte{0x8f, 0x63, 0x46, 0x75, 0x6e, 0xf5, 0x63, 0x41, 0x6d, 0x74, 0x21, 0xff} 700 | r := bytes.NewReader(buf) 701 | d := NewDecoder(r) 702 | type MyType struct { 703 | Fun bool 704 | } 705 | var a MyType 706 | check(d.Decode(&a)) 707 | expect(a.Fun, true, t) 708 | } 709 | 710 | func TestDecodeArrayNonFieldIntoStructStrictMode(t *testing.T) { 711 | buf := []byte{0x84, 0x63, 0x46, 0x75, 0x6e, 0xf5, 0x63, 0x41, 0x6d, 0x74, 0x21} 712 | r := bytes.NewReader(buf) 713 | d := NewDecoder(r, func(dec *Decoder) { dec.strict = true }) 714 | type MyType struct { 715 | Fun bool 716 | None int8 717 | } 718 | var a MyType 719 | err := d.Decode(&a) 720 | expect(err != nil, true, t) 721 | expect(fmt.Sprint(err), "strict-mode: key Amt doesn't match with any field", t) 722 | } 723 | 724 | func TestDecodeArrayOutboundsIntoStruct(t *testing.T) { 725 | buf := []byte{0x86, 0x63, 0x46, 0x75, 0x6e, 0xf5, 0x63, 0x41, 0x6d, 0x74, 0x21, 0x64, 0x46, 0x61, 0x69, 0x6c, 0x04} 726 | r := bytes.NewReader(buf) 727 | d := NewDecoder(r) 728 | type MyType struct { 729 | Fun bool 730 | Amt int8 731 | } 732 | var a MyType 733 | check(d.Decode(&a)) 734 | expect(a.Fun, true, t) 735 | expect(a.Amt, int8(-2), t) 736 | expect(r.Len(), 0, t) 737 | } 738 | 739 | func TestDecodeArrayOutboundsIntoStructStrictMode(t *testing.T) { 740 | buf := []byte{0x86, 0x63, 0x46, 0x75, 0x6e, 0xf5, 0x63, 0x41, 0x6d, 0x74, 0x21, 0x64, 0x46, 0x61, 0x69, 0x6c, 0x04} 741 | r := bytes.NewReader(buf) 742 | d := NewDecoder(r, func(dec *Decoder) { dec.strict = true }) 743 | type MyType struct { 744 | Fun bool 745 | Amt int8 746 | } 747 | var a MyType 748 | err := d.Decode(&a) 749 | expect(err != nil, true, t) 750 | expect(fmt.Sprint(err), "strict-mode: destination struct fields num 2 doesn't match map length 3", t) 751 | } 752 | 753 | func TestDecodeArrayIntoStructWithNilValue(t *testing.T) { 754 | buf := []byte{0x84, 0x63, 0x46, 0x75, 0x6e, 0xf5, 0x63, 0x41, 0x6d, 0x74, 0xf6} 755 | r := bytes.NewReader(buf) 756 | d := NewDecoder(r) 757 | type MyType struct { 758 | Fun bool 759 | Amt int8 760 | } 761 | var a MyType 762 | check(d.Decode(&a)) 763 | expect(a.Fun, true, t) 764 | expect(a.Amt, int8(0), t) 765 | expect(r.Len(), 0, t) 766 | } 767 | 768 | func TestDecodePositiveBigNum(t *testing.T) { 769 | buf := []byte{0xc2, 0x49, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} 770 | r := bytes.NewReader(buf) 771 | d := NewDecoder(r) 772 | a := new(big.Int) 773 | check(d.Decode(a)) 774 | expect(fmt.Sprint(a), "18446744073709551616", t) 775 | } 776 | 777 | func TestDecodePositiveBigNumFromInterface(t *testing.T) { 778 | buf := []byte{0xc2, 0x49, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} 779 | r := bytes.NewReader(buf) 780 | d := NewDecoder(r) 781 | var a interface{} 782 | check(d.Decode(&a)) 783 | expect(fmt.Sprint(a), "18446744073709551616", t) 784 | } 785 | 786 | func TestDecodeNegativeBigNum(t *testing.T) { 787 | buf := []byte{0xc3, 0x49, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} 788 | r := bytes.NewReader(buf) 789 | d := NewDecoder(r) 790 | a := big.NewInt(-1) 791 | check(d.Decode(a)) 792 | expect(fmt.Sprint(a), "-18446744073709551617", t) 793 | } 794 | 795 | func TestDecodeNegativeBigNumFromInterface(t *testing.T) { 796 | buf := []byte{0xc3, 0x49, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} 797 | r := bytes.NewReader(buf) 798 | d := NewDecoder(r) 799 | var a interface{} 800 | check(d.Decode(&a)) 801 | expect(fmt.Sprint(a), "-18446744073709551617", t) 802 | } 803 | 804 | func TestDecodeBigNumWrongData(t *testing.T) { 805 | buf := []byte{0xc2, 0x29, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} 806 | r := bytes.NewReader(buf) 807 | d := NewDecoder(r) 808 | a := new(big.Int) 809 | msg := "expected bytes found cborNegativeInt" 810 | err := d.Decode(a) 811 | expect(err.Error(), msg, t, "TestDecodeBigNumWrongData") 812 | } 813 | 814 | func TestDecodeUtf8DateTime(t *testing.T) { 815 | buf := []byte{0xc0, 0x74, 0x32, 0x30, 0x30, 0x33, 0x2d, 0x31, 0x32, 0x2d, 0x31, 0x33, 0x54, 0x31, 0x38, 0x3a, 0x33, 0x30, 0x3a, 0x30, 0x32, 0x5a} 816 | r := bytes.NewReader(buf) 817 | d := NewDecoder(r) 818 | var a time.Time 819 | check(d.Decode(&a)) 820 | expect(a.Year(), 2003, t, "TestDecodeUtf8DateTime") 821 | expect(a.Month(), time.December, t, "TestDecodeUtf8DateTime") 822 | expect(a.Day(), 13, t, "TestDecodeUtf8DateTime") 823 | expect(a.Hour(), 18, t, "TestDecodeUtf8DateTime") 824 | expect(a.Minute(), 30, t, "TestDecodeUtf8DateTime") 825 | expect(a.Nanosecond(), 0, t, "TestDecodeUtf8DateTime") 826 | expect(a.Location(), time.UTC, t, "TestDecodeUtf8DateTime") 827 | } 828 | 829 | func TestDecodeUtf8DAteTimeFromInterface(t *testing.T) { 830 | buf := []byte{0xc0, 0x74, 0x32, 0x30, 0x30, 0x33, 0x2d, 0x31, 0x32, 0x2d, 0x31, 0x33, 0x54, 0x31, 0x38, 0x3a, 0x33, 0x30, 0x3a, 0x30, 0x32, 0x5a} 831 | r := bytes.NewReader(buf) 832 | d := NewDecoder(r) 833 | var a interface{} 834 | check(d.Decode(&a)) 835 | expect(a.(time.Time).Year(), 2003, t) 836 | expect(a.(time.Time).Month(), time.December, t) 837 | expect(a.(time.Time).Day(), 13, t) 838 | expect(a.(time.Time).Hour(), 18, t) 839 | expect(a.(time.Time).Minute(), 30, t) 840 | expect(a.(time.Time).Nanosecond(), 0, t) 841 | expect(a.(time.Time).Location(), time.UTC, t) 842 | } 843 | 844 | func TestDecodeUtf8DateTimeWrongMajor(t *testing.T) { 845 | buf := []byte{0xc0, 0x54, 0x32, 0x30, 0x30, 0x33, 0x2d, 0x31, 0x32, 0x2d, 0x31, 0x33, 0x54, 0x31, 0x38, 0x3a, 0x33, 0x30, 0x3a, 0x30, 0x32, 0x5a} 846 | r := bytes.NewReader(buf) 847 | d := NewDecoder(r) 848 | var a interface{} 849 | err := d.Decode(&a) 850 | expect(a, nil, t) 851 | expect(err.Error(), "expected UTF-8 string, found cborByteString", t) 852 | } 853 | 854 | func TestDecodeEpochDateTime(t *testing.T) { 855 | buf := []byte{0xc1, 0x1a, 0x3f, 0xdb, 0x5a, 0xaa} 856 | r := bytes.NewReader(buf) 857 | d := NewDecoder(r) 858 | var a time.Time 859 | check(d.Decode(&a)) 860 | expect(a.Year(), 2003, t) 861 | expect(a.Month(), time.December, t) 862 | expect(a.Day(), 13, t) 863 | expect(a.Hour(), 18, t) 864 | expect(a.Minute(), 30, t) 865 | expect(a.Nanosecond(), 0, t) 866 | expect(a.Location(), time.Local, t) 867 | } 868 | 869 | func TestDecodeEpochDateTimeFromInterface(t *testing.T) { 870 | buf := []byte{0xc1, 0x1a, 0x3f, 0xdb, 0x5a, 0xaa} 871 | r := bytes.NewReader(buf) 872 | d := NewDecoder(r) 873 | var a interface{} 874 | check(d.Decode(&a)) 875 | expect(a.(time.Time).Year(), 2003, t) 876 | expect(a.(time.Time).Month(), time.December, t) 877 | expect(a.(time.Time).Day(), 13, t) 878 | expect(a.(time.Time).Hour(), 18, t) 879 | expect(a.(time.Time).Minute(), 30, t) 880 | expect(a.(time.Time).Nanosecond(), 0, t) 881 | expect(a.(time.Time).Location(), time.Local, t) 882 | } 883 | 884 | func TestDecodeEpochDateTimeWrongMajor(t *testing.T) { 885 | buf := []byte{0xc1, 0x4a, 0x3f, 0xdb, 0x5a, 0xaa} 886 | r := bytes.NewReader(buf) 887 | d := NewDecoder(r) 888 | var a interface{} 889 | err := d.Decode(&a) 890 | expect(a, nil, t) 891 | expect(err.Error(), "can't decode Epoch timestamp cborByteString", t) 892 | } 893 | 894 | func TestDecodeNegativeEpochDateTimeFromInterface(t *testing.T) { 895 | buf := []byte{0xc1, 0x3a, 0x01, 0x93, 0xa9, 0x4b} 896 | r := bytes.NewReader(buf) 897 | d := NewDecoder(r) 898 | var a interface{} 899 | check(d.Decode(&a)) 900 | expect(a.(time.Time).Year(), 1969, t) 901 | expect(a.(time.Time).Month(), time.February, t) 902 | expect(a.(time.Time).Day(), 28, t) 903 | expect(a.(time.Time).Hour(), 20, t) 904 | expect(a.(time.Time).Minute(), 34, t) 905 | expect(a.(time.Time).Second(), 12, t) 906 | expect(a.(time.Time).Nanosecond(), 0, t) 907 | expect(a.(time.Time).Location(), time.Local, t) 908 | } 909 | 910 | func TestDecodeDecimalFraction(t *testing.T) { 911 | buf := []byte{0xc4, 0x82, 0x21, 0x19, 0x6a, 0xb3} 912 | r := bytes.NewReader(buf) 913 | d := NewDecoder(r) 914 | var a interface{} 915 | check(d.Decode(&a)) 916 | expect(a, float32(273.15), t, "TestDecodeDecimalFraction") 917 | } 918 | 919 | func TestDecodeDecimalFractionNonArray(t *testing.T) { 920 | buf := []byte{0xc4, 0xa2, 0x21, 0x19, 0x6a, 0xb3} 921 | r := bytes.NewReader(buf) 922 | d := NewDecoder(r) 923 | var a interface{} 924 | err := d.Decode(&a) 925 | msg := "Decimal Fraction must be represented as an array of two elements" 926 | expect(a, nil, t, "TestDecodeCecimalFractionNonArray") 927 | expect(err.Error(), msg, t, "TestDecodeDecimalFractionNonArray") 928 | } 929 | 930 | func TestDecodeDecimalFractionInvalidExponent(t *testing.T) { 931 | buf := []byte{0xc4, 0x82, 0x51, 0x19, 0x6a, 0xb3} 932 | r := bytes.NewReader(buf) 933 | d := NewDecoder(r) 934 | var a interface{} 935 | err := d.Decode(&a) 936 | msg := "Can't decode cborByteString as decimal fraction exponent" 937 | expect(a, nil, t, "TestDecodeDecimalFractionInvalidExponent") 938 | expect(err.Error(), msg, t, "TestDecodeDecimalFractionInvalidExponent") 939 | } 940 | 941 | func TestDecodeDecimalFractionInvalidMantissa(t *testing.T) { 942 | buf := []byte{0xc4, 0x82, 0x21, 0x59, 0x6a, 0xb3} 943 | r := bytes.NewReader(buf) 944 | d := NewDecoder(r) 945 | var a interface{} 946 | err := d.Decode(&a) 947 | msg := "Can't decode cborByteString as decimal fraction mantissa" 948 | expect(a, nil, t, "TestDecodeDecimalFractionInvalidMantissa") 949 | expect(err.Error(), msg, t, "TestDecodeDecimalFractionInvalidMantissa") 950 | } 951 | 952 | func TestDecodeBigFloat(t *testing.T) { 953 | buf := []byte{0xc5, 0x82, 0x20, 0x03} 954 | r := bytes.NewReader(buf) 955 | d := NewDecoder(r) 956 | var a interface{} 957 | check(d.Decode(&a)) 958 | expect(a.(*big.Rat).String(), big.NewRat(3, 2).String(), t) 959 | } 960 | 961 | func TestDecodeBigFloatFromBigInt(t *testing.T) { 962 | buf := []byte{0xc5, 0x82, 0x20, 0xc2, 0x41, 0x03} 963 | r := bytes.NewReader(buf) 964 | d := NewDecoder(r) 965 | var a interface{} 966 | check(d.Decode(&a)) 967 | expect(a.(*big.Rat).String(), big.NewRat(3, 2).String(), t) 968 | } 969 | 970 | func TestDecodeBigFloatNonArray(t *testing.T) { 971 | buf := []byte{0xc5, 0x52, 0x20, 0x03} 972 | r := bytes.NewReader(buf) 973 | d := NewDecoder(r) 974 | var a interface{} 975 | err := d.Decode(&a) 976 | msg := "Big float must be represented as an array of two elements" 977 | expect(a, nil, t, "TestDecodeBigFloatNonArray") 978 | expect(err.Error(), msg, t, "TestDecodeBigFloatNonArray") 979 | } 980 | 981 | func TestDecodeBigFloatInvalidExponent(t *testing.T) { 982 | buf := []byte{0xc5, 0x82, 0x50, 0x03} 983 | r := bytes.NewReader(buf) 984 | d := NewDecoder(r) 985 | var a interface{} 986 | err := d.Decode(&a) 987 | msg := "Can't decode cborByteString as decimal fraction exponent" 988 | expect(a, nil, t, "TestDecodeBigFloatInvalidExponent") 989 | expect(err.Error(), msg, t, "TestDecodeBigFloatInvalidExponent") 990 | } 991 | 992 | func TestDecodeBigFloatInvalidMantissa(t *testing.T) { 993 | buf := []byte{0xc5, 0x82, 0x20, 0x53} 994 | r := bytes.NewReader(buf) 995 | d := NewDecoder(r) 996 | var a interface{} 997 | err := d.Decode(&a) 998 | msg := "Can't decode cborByteString as decimal fraction mantissa" 999 | expect(a, nil, t, "TestDecodeBigFloatInvalidMantissa") 1000 | expect(err.Error(), msg, t, "TestDecodeBigFloatInvalidMantissa") 1001 | } 1002 | 1003 | func TestDecodeBase64Url(t *testing.T) { 1004 | buf := []byte{0xd6, 0x58, 0x1c, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x63, 0x62, 0x6f, 0x72, 0x2f, 0x3f, 0x69, 0x73, 0x20, 0x61, 0x77, 0x65, 0x73, 0x6f, 0x6d, 0x65, 0x3d, 0x74, 0x72, 0x75, 0x65} 1005 | r := bytes.NewReader(buf) 1006 | d := NewDecoder(r) 1007 | var a interface{} 1008 | check(d.Decode(&a)) 1009 | e := []byte{0x61, 0x48, 0x52, 0x30, 0x63, 0x44, 0x6f, 0x76, 0x4c, 0x32, 0x4e, 0x69, 0x62, 0x33, 0x49, 0x76, 0x50, 0x32, 0x6c, 0x7a, 0x49, 0x47, 0x46, 0x33, 0x5a, 0x58, 0x4e, 0x76, 0x62, 0x57, 0x55, 0x39, 0x64, 0x48, 0x4a, 0x31, 0x5a, 0x51, 0x3d, 0x3d} 1010 | for i, _ := range e { 1011 | expect(a.([]byte)[i], e[i], t, "TestDecodeBase64Url") 1012 | } 1013 | } 1014 | 1015 | func TestDecodeBase64UrlInvalidData(t *testing.T) { 1016 | buf := []byte{0xd5, 0x9f, 0x43, 0x42, 0x4f, 0x52, 0x20, 0x69, 0x73, 0x20, 0x61, 0x77, 0x65, 0x73, 0x6f, 0x6d, 0x65} 1017 | r := bytes.NewReader(buf) 1018 | d := NewDecoder(r) 1019 | var a interface{} 1020 | err := d.Decode(&a) 1021 | msg := "expected string or bytes found cborDataArray" 1022 | expect(err.Error(), msg, t, "TestDecodeBase64UrlInvalidDAta") 1023 | } 1024 | 1025 | func TestDecodeBase64String(t *testing.T) { 1026 | buf := []byte{0xd5, 0x4f, 0x43, 0x42, 0x4f, 0x52, 0x20, 0x69, 0x73, 0x20, 0x61, 0x77, 0x65, 0x73, 0x6f, 0x6d, 0x65} 1027 | r := bytes.NewReader(buf) 1028 | d := NewDecoder(r) 1029 | var a interface{} 1030 | check(d.Decode(&a)) 1031 | e := []byte{0x51, 0x30, 0x4a, 0x50, 0x55, 0x69, 0x42, 0x70, 0x63, 0x79, 0x42, 0x68, 0x64, 0x32, 0x56, 0x7a, 0x62, 0x32, 0x31, 0x6c} 1032 | for i, _ := range e { 1033 | expect(a.([]byte)[i], e[i], t, "TestDecodeBase64String") 1034 | } 1035 | } 1036 | 1037 | func TestDecodeBase64StringInvalidData(t *testing.T) { 1038 | buf := []byte{0xd6, 0x98, 0x1c, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x63, 0x62, 0x6f, 0x72, 0x2f, 0x3f, 0x69, 0x73, 0x20, 0x61, 0x77, 0x65, 0x73, 0x6f, 0x6d, 0x65, 0x3d, 0x74, 0x72, 0x75, 0x65} 1039 | r := bytes.NewReader(buf) 1040 | d := NewDecoder(r) 1041 | var a interface{} 1042 | err := d.Decode(&a) 1043 | msg := "expected string or bytes found cborDataArray" 1044 | expect(err.Error(), msg, t, "TestDecodeBase64StringInvalidData") 1045 | } 1046 | 1047 | func TestDecodeBase16String(t *testing.T) { 1048 | buf := []byte{0xd7, 0x46, 0x62, 0x61, 0x73, 0x65, 0x31, 0x36} 1049 | r := bytes.NewReader(buf) 1050 | d := NewDecoder(r) 1051 | var a interface{} 1052 | check(d.Decode(&a)) 1053 | e := []byte{0x36, 0x32, 0x36, 0x31, 0x37, 0x33, 0x36, 0x35, 0x33, 0x31, 0x33, 0x36} 1054 | for i, _ := range e { 1055 | expect(a.([]byte)[i], e[i], t, "TestDecodeBase16String") 1056 | } 1057 | } 1058 | 1059 | func TestDecodeUri(t *testing.T) { 1060 | buf := []byte{0xd8, 0x20, 0x78, 0x19, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, 0x6f, 0x72, 0x67, 0x3f, 0x6f, 0x68, 0x3d, 0x79, 0x65, 0x61, 0x68} 1061 | r := bytes.NewReader(buf) 1062 | d := NewDecoder(r) 1063 | var a interface{} 1064 | check(d.Decode(&a)) 1065 | uri, _ := url.Parse("http://golang.org?oh=yeah") 1066 | expect(a.(*url.URL).String(), uri.String(), t, "TestDeecodeUri") 1067 | } 1068 | 1069 | func TestDecodeUriInvalidData(t *testing.T) { 1070 | buf := []byte{0xd8, 0x20, 0x58, 0x19, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, 0x6f, 0x72, 0x67, 0x3f, 0x6f, 0x68, 0x3d, 0x79, 0x65, 0x61, 0x68} 1071 | r := bytes.NewReader(buf) 1072 | d := NewDecoder(r) 1073 | var a interface{} 1074 | err := d.Decode(&a) 1075 | msg := "expected string found cborByteString" 1076 | expect(err.Error(), msg, t, "TestDeecodeUriInvalidData") 1077 | } 1078 | 1079 | func TestDecodeBase64URI(t *testing.T) { 1080 | buf := []byte{0xd8, 0x21, 0x78, 0x24, 0x61, 0x48, 0x52, 0x30, 0x63, 0x44, 0x6f, 0x76, 0x4c, 0x32, 0x64, 0x76, 0x62, 0x47, 0x46, 0x75, 0x5a, 0x79, 0x35, 0x76, 0x63, 0x6d, 0x63, 0x5f, 0x62, 0x32, 0x67, 0x39, 0x65, 0x57, 0x56, 0x68, 0x61, 0x41, 0x3d, 0x3d} 1081 | r := bytes.NewReader(buf) 1082 | d := NewDecoder(r) 1083 | var a interface{} 1084 | check(d.Decode(&a)) 1085 | uri, _ := url.Parse("http://golang.org?oh=yeah") 1086 | expect(a.(*url.URL).String(), uri.String(), t, "TestDecodeBase64URI") 1087 | } 1088 | 1089 | func TestDecodeBase64URIInvalidData(t *testing.T) { 1090 | buf := []byte{0xd8, 0x21, 0x58, 0x24, 0x61, 0x48, 0x52, 0x30, 0x63, 0x44, 0x6f, 0x76, 0x4c, 0x32, 0x64, 0x76, 0x62, 0x47, 0x46, 0x75, 0x5a, 0x79, 0x35, 0x76, 0x63, 0x6d, 0x63, 0x5f, 0x62, 0x32, 0x67, 0x39, 0x65, 0x57, 0x56, 0x68, 0x61, 0x41, 0x3d, 0x3d} 1091 | r := bytes.NewReader(buf) 1092 | d := NewDecoder(r) 1093 | var a interface{} 1094 | err := d.Decode(&a) 1095 | msg := "expected string found cborByteString" 1096 | expect(err.Error(), msg, t, "TestDeecodeBase64URIInvalidData") 1097 | } 1098 | 1099 | func TestDecodeBase64DecodedString(t *testing.T) { 1100 | buf := []byte{0xd8, 0x22, 0x78, 0xf0, 0x52, 0x57, 0x34, 0x67, 0x64, 0x57, 0x34, 0x67, 0x62, 0x48, 0x56, 0x6e, 0x59, 0x58, 0x49, 0x67, 0x5a, 0x47, 0x55, 0x67, 0x62, 0x47, 0x45, 0x67, 0x62, 0x57, 0x46, 0x75, 0x59, 0x32, 0x68, 0x68, 0x4c, 0x43, 0x42, 0x6b, 0x5a, 0x53, 0x42, 0x6a, 0x64, 0x58, 0x6c, 0x76, 0x49, 0x47, 0x35, 0x76, 0x62, 0x57, 0x4a, 0x79, 0x5a, 0x53, 0x42, 0x75, 0x62, 0x79, 0x42, 0x78, 0x64, 0x57, 0x6c, 0x6c, 0x63, 0x6d, 0x38, 0x67, 0x59, 0x57, 0x4e, 0x76, 0x63, 0x6d, 0x52, 0x68, 0x63, 0x6d, 0x31, 0x6c, 0x4c, 0x43, 0x42, 0x75, 0x62, 0x79, 0x42, 0x6f, 0x59, 0x53, 0x42, 0x74, 0x64, 0x57, 0x4e, 0x6f, 0x62, 0x79, 0x42, 0x30, 0x61, 0x57, 0x31, 0x6c, 0x63, 0x47, 0x38, 0x67, 0x63, 0x58, 0x56, 0x6c, 0x49, 0x48, 0x5a, 0x70, 0x64, 0x73, 0x4f, 0x74, 0x59, 0x53, 0x42, 0x70, 0x62, 0x69, 0x42, 0x6f, 0x61, 0x57, 0x52, 0x68, 0x62, 0x47, 0x64, 0x76, 0x49, 0x47, 0x52, 0x6c, 0x49, 0x47, 0x78, 0x76, 0x63, 0x79, 0x42, 0x6b, 0x5a, 0x53, 0x42, 0x73, 0x59, 0x57, 0x35, 0x36, 0x59, 0x53, 0x42, 0x6c, 0x62, 0x69, 0x42, 0x68, 0x63, 0x33, 0x52, 0x70, 0x62, 0x47, 0x78, 0x6c, 0x63, 0x6d, 0x38, 0x73, 0x49, 0x47, 0x46, 0x6b, 0x59, 0x58, 0x4a, 0x6e, 0x59, 0x53, 0x42, 0x68, 0x62, 0x6e, 0x52, 0x70, 0x5a, 0x33, 0x56, 0x68, 0x4c, 0x43, 0x42, 0x79, 0x62, 0x32, 0x50, 0x44, 0x72, 0x57, 0x34, 0x67, 0x5a, 0x6d, 0x78, 0x68, 0x59, 0x32, 0x38, 0x67, 0x65, 0x53, 0x42, 0x6e, 0x59, 0x57, 0x78, 0x6e, 0x62, 0x79, 0x42, 0x6a, 0x62, 0x33, 0x4a, 0x79, 0x5a, 0x57, 0x52, 0x76, 0x63, 0x69, 0x34, 0x3d} 1101 | r := bytes.NewReader(buf) 1102 | d := NewDecoder(r) 1103 | var a interface{} 1104 | check(d.Decode(&a)) 1105 | text := "En un lugar de la mancha, de cuyo nombre no quiero acordarme, no ha mucho timepo que vivía in hidalgo de los de lanza en astillero, adarga antigua, rocín flaco y galgo corredor." 1106 | expect(a, text, t, "TestDecodeBase64DecodedString") 1107 | } 1108 | 1109 | func TestDecodeBase64DecodedStringInvalidData(t *testing.T) { 1110 | buf := []byte{0xd8, 0x22, 0x58, 0xf0, 0x52, 0x57, 0x34, 0x67, 0x64, 0x57, 0x34, 0x67, 0x62, 0x48, 0x56, 0x6e, 0x59, 0x58, 0x49, 0x67, 0x5a, 0x47, 0x55, 0x67, 0x62, 0x47, 0x45, 0x67, 0x62, 0x57, 0x46, 0x75, 0x59, 0x32, 0x68, 0x68, 0x4c, 0x43, 0x42, 0x6b, 0x5a, 0x53, 0x42, 0x6a, 0x64, 0x58, 0x6c, 0x76, 0x49, 0x47, 0x35, 0x76, 0x62, 0x57, 0x4a, 0x79, 0x5a, 0x53, 0x42, 0x75, 0x62, 0x79, 0x42, 0x78, 0x64, 0x57, 0x6c, 0x6c, 0x63, 0x6d, 0x38, 0x67, 0x59, 0x57, 0x4e, 0x76, 0x63, 0x6d, 0x52, 0x68, 0x63, 0x6d, 0x31, 0x6c, 0x4c, 0x43, 0x42, 0x75, 0x62, 0x79, 0x42, 0x6f, 0x59, 0x53, 0x42, 0x74, 0x64, 0x57, 0x4e, 0x6f, 0x62, 0x79, 0x42, 0x30, 0x61, 0x57, 0x31, 0x6c, 0x63, 0x47, 0x38, 0x67, 0x63, 0x58, 0x56, 0x6c, 0x49, 0x48, 0x5a, 0x70, 0x64, 0x73, 0x4f, 0x74, 0x59, 0x53, 0x42, 0x70, 0x62, 0x69, 0x42, 0x6f, 0x61, 0x57, 0x52, 0x68, 0x62, 0x47, 0x64, 0x76, 0x49, 0x47, 0x52, 0x6c, 0x49, 0x47, 0x78, 0x76, 0x63, 0x79, 0x42, 0x6b, 0x5a, 0x53, 0x42, 0x73, 0x59, 0x57, 0x35, 0x36, 0x59, 0x53, 0x42, 0x6c, 0x62, 0x69, 0x42, 0x68, 0x63, 0x33, 0x52, 0x70, 0x62, 0x47, 0x78, 0x6c, 0x63, 0x6d, 0x38, 0x73, 0x49, 0x47, 0x46, 0x6b, 0x59, 0x58, 0x4a, 0x6e, 0x59, 0x53, 0x42, 0x68, 0x62, 0x6e, 0x52, 0x70, 0x5a, 0x33, 0x56, 0x68, 0x4c, 0x43, 0x42, 0x79, 0x62, 0x32, 0x50, 0x44, 0x72, 0x57, 0x34, 0x67, 0x5a, 0x6d, 0x78, 0x68, 0x59, 0x32, 0x38, 0x67, 0x65, 0x53, 0x42, 0x6e, 0x59, 0x57, 0x78, 0x6e, 0x62, 0x79, 0x42, 0x6a, 0x62, 0x33, 0x4a, 0x79, 0x5a, 0x57, 0x52, 0x76, 0x63, 0x69, 0x34, 0x3d} 1111 | r := bytes.NewReader(buf) 1112 | d := NewDecoder(r) 1113 | var a interface{} 1114 | err := d.Decode(&a) 1115 | msg := "expected string found cborByteString" 1116 | expect(err.Error(), msg, t, "TestDeecodeBase64DecodedStringInvalidData") 1117 | } 1118 | 1119 | func TestDecodeRegexp(t *testing.T) { 1120 | buf := []byte{0xd8, 0x23, 0x72, 0x5e, 0x5b, 0x61, 0x2d, 0x7a, 0x5d, 0x2b, 0x5c, 0x5b, 0x5b, 0x30, 0x2d, 0x39, 0x5d, 0x2b, 0x5c, 0x5d, 0x24} 1121 | r := bytes.NewReader(buf) 1122 | d := NewDecoder(r) 1123 | var a interface{} 1124 | check(d.Decode(&a)) 1125 | msg := `^[a-z]+\[[0-9]+\]$` 1126 | expect(a.(*regexp.Regexp).String(), msg, t, "TestDecodeRegexp") 1127 | } 1128 | 1129 | func TestDecodeRegexpInvalidData(t *testing.T) { 1130 | buf := []byte{0xd8, 0x23, 0x52, 0x5e, 0x5b, 0x61, 0x2d, 0x7a, 0x5d, 0x2b, 0x5c, 0x5b, 0x5b, 0x30, 0x2d, 0x39, 0x5d, 0x2b, 0x5c, 0x5d, 0x24} 1131 | r := bytes.NewReader(buf) 1132 | d := NewDecoder(r) 1133 | var a interface{} 1134 | err := d.Decode(&a) 1135 | msg := "expected string found cborByteString" 1136 | expect(err.Error(), msg, t, "TestDecodeRegexpInvalidData") 1137 | } 1138 | 1139 | func TestDecodeMime(t *testing.T) { 1140 | buf := []byte{0xd8, 0x24, 0x78, 0x4c, 0x61, 0x70, 0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x78, 0x2d, 0x73, 0x74, 0x75, 0x66, 0x66, 0x3b, 0x20, 0x74, 0x69, 0x74, 0x6c, 0x65, 0x2a, 0x3d, 0x75, 0x73, 0x2d, 0x61, 0x73, 0x63, 0x69, 0x69, 0x27, 0x65, 0x6e, 0x2d, 0x75, 0x73, 0x27, 0x54, 0x68, 0x69, 0x73, 0x25, 0x32, 0x30, 0x69, 0x73, 0x25, 0x32, 0x30, 0x25, 0x32, 0x41, 0x25, 0x32, 0x41, 0x25, 0x32, 0x41, 0x66, 0x75, 0x6e, 0x25, 0x32, 0x41, 0x25, 0x32, 0x41, 0x25, 0x32, 0x41} 1141 | r := bytes.NewReader(buf) 1142 | d := NewDecoder(r) 1143 | var a interface{} 1144 | check(d.Decode(&a)) 1145 | expect(a.(*CBORMIME).ContentType, "application/x-stuff", t, "TestDecodeMime") 1146 | expect(a.(*CBORMIME).Params["title"], "This is ***fun***", t, "TestDecodeMime") 1147 | } 1148 | 1149 | type MineType struct { 1150 | Id int 1151 | Name string 1152 | } 1153 | 1154 | var tFn = func(*Decoder, reflect.Value) error { return nil } 1155 | var etFn = func(*Decoder, interface{}) error { return nil } 1156 | var extTagInfo = uint64(0xBABE) 1157 | 1158 | func TestRegisterExtensionFn(t *testing.T) { 1159 | var mt MineType 1160 | RegisterExtensionFn(reflect.TypeOf(mt), tFn) 1161 | expect(len(extensionsDec), 1, t, "TestRegisterExtesnionFn") 1162 | } 1163 | 1164 | func TestLookupExtensionFn(t *testing.T) { 1165 | var mt MineType 1166 | fn, err := LookupExtensionFn(reflect.TypeOf(mt)) 1167 | expect(err, nil, t, "TestLookupExtensionFn") 1168 | expect(fmt.Sprintf("%x", fn), fmt.Sprintf("%x", tFn), t, "TestLookupExtensionFn") 1169 | } 1170 | 1171 | func TestRegisterTagExtensionFn(t *testing.T) { 1172 | RegisterTagExtensionFn(extTagInfo, etFn) 1173 | expect(len(extensionTagDec), 1, t, "TestRegisterTagExtensionFn") 1174 | } 1175 | 1176 | // Some benchmarks 1177 | func BenchmarkDecodeUint8(b *testing.B) { 1178 | buf := []byte{0x18, 0x6f} 1179 | r := bytes.NewReader(buf) 1180 | d := NewDecoder(r) 1181 | var a uint8 1182 | 1183 | for i := 0; i < b.N; i++ { 1184 | d.Decode(&a) 1185 | } 1186 | } 1187 | 1188 | func BenchmarkDecodeFLoat16(b *testing.B) { 1189 | buf := []byte{0xf9, 0x3f, 0xe0} 1190 | r := bytes.NewReader(buf) 1191 | d := NewDecoder(r) 1192 | var a float16 1193 | 1194 | for i := 0; i < b.N; i++ { 1195 | d.Decode(&a) 1196 | } 1197 | } 1198 | 1199 | func BenchmarkDecodeFLoat32(b *testing.B) { 1200 | buf := []byte{0xfa, 0x3f, 0x66, 0x66, 0x66} 1201 | r := bytes.NewReader(buf) 1202 | d := NewDecoder(r) 1203 | var a float32 1204 | 1205 | for i := 0; i < b.N; i++ { 1206 | d.Decode(&a) 1207 | } 1208 | } 1209 | 1210 | func BenchmarkDecodeUnsignedIntsIndefiniteArray(b *testing.B) { 1211 | buf := []byte{0x9f, 0x04, 0x09, 0x19, 0x04, 0x00, 0x10, 0xff} 1212 | r := bytes.NewReader(buf) 1213 | d := NewDecoder(r) 1214 | var a []uint 1215 | 1216 | for i := 0; i < b.N; i++ { 1217 | d.Decode(&a) 1218 | } 1219 | } 1220 | 1221 | func BenchmarkDecodeUnsignedIntsArray(b *testing.B) { 1222 | buf := []byte{0x84, 0x04, 0x09, 0x19, 0x04, 0x00, 0x10} 1223 | r := bytes.NewReader(buf) 1224 | d := NewDecoder(r) 1225 | var a []uint 1226 | 1227 | for i := 0; i < b.N; i++ { 1228 | d.Decode(&a) 1229 | } 1230 | } 1231 | 1232 | func BenchmarkDecodeInterface(b *testing.B) { 1233 | buf := []byte{0x85, 0x04, 0x09, 0x19, 0x04, 0x00, 0x10, 0x83, 0x01, 0x02, 0x67, 0x65, 0x73, 0x70, 0x61, 0xc3, 0xb1, 0x61} 1234 | r := bytes.NewReader(buf) 1235 | d := NewDecoder(r) 1236 | var a interface{} 1237 | 1238 | for i := 0; i < b.N; i++ { 1239 | d.Decode(&a) 1240 | } 1241 | } 1242 | 1243 | func BenchmarkDecodeMapInterfaceKeyInterfaceValues(b *testing.B) { 1244 | buf := []byte{0xa2, 0x63, 0x46, 0x75, 0x6e, 0xf5, 0x63, 0x41, 0x6d, 0x74, 0x21} 1245 | r := bytes.NewReader(buf) 1246 | d := NewDecoder(r) 1247 | var a map[interface{}]interface{} 1248 | 1249 | for i := 0; i < b.N; i++ { 1250 | d.Decode(&a) 1251 | } 1252 | } 1253 | 1254 | func BenchmarkDecodeMapInterfaceValues(b *testing.B) { 1255 | buf := []byte{0xa2, 0x63, 0x46, 0x75, 0x6e, 0xf5, 0x63, 0x41, 0x6d, 0x74, 0x21} 1256 | r := bytes.NewReader(buf) 1257 | d := NewDecoder(r) 1258 | var a map[string]interface{} 1259 | 1260 | for i := 0; i < b.N; i++ { 1261 | d.Decode(&a) 1262 | } 1263 | } 1264 | 1265 | func BenchmarkDecodeMapInt8Values(b *testing.B) { 1266 | buf := []byte{0xa2, 0x63, 0x46, 0x75, 0x6e, 0x23, 0x63, 0x41, 0x6d, 0x74, 0x21} 1267 | r := bytes.NewReader(buf) 1268 | d := NewDecoder(r) 1269 | var a map[string]int8 1270 | 1271 | for i := 0; i < b.N; i++ { 1272 | d.Decode(&a) 1273 | } 1274 | } 1275 | 1276 | func BenchmarkDecodeMapIntoInterface(b *testing.B) { 1277 | buf := []byte{0xa2, 0x63, 0x46, 0x75, 0x6e, 0xf5, 0x63, 0x41, 0x6d, 0x74, 0x21} 1278 | r := bytes.NewReader(buf) 1279 | d := NewDecoder(r) 1280 | var a interface{} 1281 | 1282 | for i := 0; i < b.N; i++ { 1283 | d.Decode(&a) 1284 | } 1285 | } 1286 | 1287 | func BenchmarkDecodeMapIntoStruct(b *testing.B) { 1288 | buf := []byte{0xa2, 0x63, 0x46, 0x75, 0x6e, 0xf5, 0x63, 0x41, 0x6d, 0x74, 0x21} 1289 | r := bytes.NewReader(buf) 1290 | d := NewDecoder(r) 1291 | type MyType struct { 1292 | Fun bool 1293 | Amt int8 1294 | } 1295 | var a MyType 1296 | 1297 | for i := 0; i < b.N; i++ { 1298 | d.Decode(&a) 1299 | } 1300 | } 1301 | -------------------------------------------------------------------------------- /encoder.go: -------------------------------------------------------------------------------- 1 | // A Golang RFC7049 implementation 2 | // Copyright (C) 2015 Oscar Campos 3 | 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | 16 | package cbor 17 | 18 | import ( 19 | "bytes" 20 | "errors" 21 | "fmt" 22 | "io" 23 | "math/big" 24 | "reflect" 25 | "time" 26 | "unicode" 27 | "unsafe" 28 | ) 29 | 30 | // Type of function that handler encoding of extensions 31 | type handleEncFn handleDecFn 32 | 33 | // An Encoder writes and encode CBOR objects to an output stream 34 | type Encoder struct { 35 | composer *Composer 36 | canonical bool 37 | strict bool 38 | } 39 | 40 | // NewEncoder returns a new encoder that write to w 41 | func NewEncoder(w io.Writer, options ...func(*Encoder)) *Encoder { 42 | e := &Encoder{composer: &Composer{w: w}, strict: false} 43 | if len(options) > 0 { 44 | for _, option := range options { 45 | option(e) 46 | } 47 | } 48 | return e 49 | } 50 | 51 | // Check if the pointer passed to Encode 52 | // is nil and then call enc.encodeNil() 53 | func (enc *Encoder) isValidPointer(t unsafe.Pointer) bool { 54 | if t == nil { 55 | enc.encodeNil() 56 | return false 57 | } 58 | return true 59 | } 60 | 61 | // Encoder takes any object passed as parameter and 62 | // writes it into a io.Writer using the C.B.O.R encoding format. 63 | func (enc *Encoder) Encode(v interface{}) (err error) { 64 | defer func() { 65 | if r := recover(); r != nil { 66 | err = r.(error) 67 | } 68 | }() 69 | 70 | // fast path encoding for simple values 71 | switch t := v.(type) { 72 | case nil: 73 | enc.encodeNil() 74 | case bool: 75 | enc.encodeBool(t) 76 | case uint8: 77 | enc.encodeUint(uint64(t)) 78 | case int8: 79 | enc.encodeInt(int64(t)) 80 | case uint16: 81 | enc.encodeUint(uint64(t)) 82 | case int16: 83 | enc.encodeInt(int64(t)) 84 | case uint32: 85 | enc.encodeUint(uint64(t)) 86 | case int32: 87 | enc.encodeInt(int64(t)) 88 | case uint64: 89 | enc.encodeUint(t) 90 | case int64: 91 | enc.encodeInt(t) 92 | case uint: 93 | enc.encodeUint(uint64(t)) 94 | case int: 95 | enc.encodeInt(int64(t)) 96 | case float16: 97 | enc.encodeFloat16(t) 98 | case float32: 99 | enc.encodeFloat32(t) 100 | case float64: 101 | enc.encodeFloat64(t) 102 | case big.Int: 103 | if t.Sign() < 0 { 104 | enc.encodeBigInt(t) 105 | } else { 106 | enc.encodeBigUint(t) 107 | } 108 | case time.Time: 109 | enc.encodeEpochDateTime(t) 110 | case big.Rat: 111 | enc.encodeBigFloat(t) 112 | case []uint8: 113 | enc.encodeByteString(t) 114 | case string: 115 | enc.encodeTextString(t) 116 | case *bool: 117 | if enc.isValidPointer(unsafe.Pointer(t)) { 118 | enc.encodeBool(*t) 119 | } 120 | case *uint8: 121 | if enc.isValidPointer(unsafe.Pointer(t)) { 122 | enc.encodeUint(uint64(*t)) 123 | } 124 | case *int8: 125 | if enc.isValidPointer(unsafe.Pointer(t)) { 126 | enc.encodeInt(int64(*t)) 127 | } 128 | case *uint16: 129 | if enc.isValidPointer(unsafe.Pointer(t)) { 130 | enc.encodeUint(uint64(*t)) 131 | } 132 | case *int16: 133 | if enc.isValidPointer(unsafe.Pointer(t)) { 134 | enc.encodeInt(int64(*t)) 135 | } 136 | case *uint32: 137 | if enc.isValidPointer(unsafe.Pointer(t)) { 138 | enc.encodeUint(uint64(*t)) 139 | } 140 | case *int32: 141 | if enc.isValidPointer(unsafe.Pointer(t)) { 142 | enc.encodeInt(int64(*t)) 143 | } 144 | case *uint64: 145 | if enc.isValidPointer(unsafe.Pointer(t)) { 146 | enc.encodeUint(*t) 147 | } 148 | case *int64: 149 | if enc.isValidPointer(unsafe.Pointer(t)) { 150 | enc.encodeInt(*t) 151 | } 152 | case *uint: 153 | if enc.isValidPointer(unsafe.Pointer(t)) { 154 | enc.encodeUint(uint64(*t)) 155 | } 156 | case *int: 157 | if enc.isValidPointer(unsafe.Pointer(t)) { 158 | enc.encodeInt(int64(*t)) 159 | } 160 | case *float16: 161 | if enc.isValidPointer(unsafe.Pointer(t)) { 162 | enc.encodeFloat16(*t) 163 | } 164 | case *float32: 165 | if enc.isValidPointer(unsafe.Pointer(t)) { 166 | enc.encodeFloat32(*t) 167 | } 168 | case *float64: 169 | if enc.isValidPointer(unsafe.Pointer(t)) { 170 | enc.encodeFloat64(*t) 171 | } 172 | case *big.Int: 173 | if enc.isValidPointer(unsafe.Pointer(t)) { 174 | if t.Sign() < 0 { 175 | enc.encodeBigInt(*t) 176 | } else { 177 | enc.encodeBigUint(*t) 178 | } 179 | } 180 | case *time.Time: 181 | if enc.isValidPointer(unsafe.Pointer(t)) { 182 | enc.encodeEpochDateTime(*t) 183 | } 184 | case *big.Rat: 185 | if enc.isValidPointer(unsafe.Pointer(t)) { 186 | enc.encodeBigFloat(*t) 187 | } 188 | case *[]uint8: 189 | if enc.isValidPointer(unsafe.Pointer(t)) { 190 | enc.encodeByteString(*t) 191 | } 192 | case *string: 193 | if enc.isValidPointer(unsafe.Pointer(t)) { 194 | enc.encodeTextString(*t) 195 | } 196 | case reflect.Value: 197 | enc.encode(t, v) 198 | default: 199 | enc.encode(reflect.ValueOf(v), v) 200 | } 201 | 202 | return nil 203 | } 204 | 205 | // encode is being used when the type of the supplier of the encode 206 | // operation is a slice, a map an interface or any other custom type 207 | func (enc *Encoder) encode(rv reflect.Value, vs ...interface{}) (err error) { 208 | defer func() { 209 | if r := recover(); r != nil { 210 | err = errors.New(fmt.Sprint(r)) 211 | } 212 | }() 213 | 214 | // If rv is a pointer, get the value it's references 215 | for rv.Kind() == reflect.Ptr { 216 | // Lets encode nil values if present 217 | if rv.IsNil() { 218 | enc.encodeNil() 219 | return 220 | } 221 | rv = rv.Elem() 222 | } 223 | if !rv.IsValid() { 224 | // Encode as nil if the value is not valid 225 | enc.encodeNil() 226 | return 227 | } 228 | var v interface{} = rv.Interface() 229 | if len(vs) > 0 { 230 | v = vs[0] 231 | } 232 | 233 | switch rv.Type().Kind() { 234 | case reflect.Bool: 235 | err = enc.composer.composeBoolean(v.(bool)) 236 | case reflect.Uint8: 237 | _, err = enc.composer.composeUint(uint64(v.(uint8))) 238 | case reflect.Uint16: 239 | _, err = enc.composer.composeUint(uint64(v.(uint16))) 240 | case reflect.Uint32: 241 | _, err = enc.composer.composeUint(uint64(v.(uint32))) 242 | case reflect.Uint64: 243 | _, err = enc.composer.composeUint(v.(uint64)) 244 | case reflect.Uint: 245 | _, err = enc.composer.composeUint(uint64(v.(uint))) 246 | case reflect.Int8: 247 | _, err = enc.composer.composeInt(int64(v.(int8))) 248 | case reflect.Int16: 249 | _, err = enc.composer.composeInt(int64(v.(int16))) 250 | case reflect.Int32: 251 | _, err = enc.composer.composeInt(int64(v.(int32))) 252 | case reflect.Int64: 253 | _, err = enc.composer.composeInt(v.(int64)) 254 | case reflect.Int: 255 | _, err = enc.composer.composeInt(int64(v.(int))) 256 | case reflect.Float32: 257 | err = enc.composer.composeFloat32(v.(float32)) 258 | case reflect.Float64: 259 | err = enc.composer.composeFloat64(v.(float64)) 260 | case reflect.String: 261 | enc.encodeTextString(v.(string)) 262 | case reflect.Invalid: 263 | err = enc.composer.composeNil() 264 | case reflect.Slice, reflect.Array: 265 | enc.encodeSlice(rv) 266 | case reflect.Map: 267 | enc.encodeMap(rv) 268 | case reflect.Struct: 269 | enc.encodeStruct(rv) 270 | // case reflect.Interface: 271 | // err = enc.encodeInterface() 272 | // default: 273 | // err = enc.lookupExtension(rv) 274 | } 275 | 276 | return err 277 | } 278 | 279 | // Encode a Nil value 280 | func (enc *Encoder) encodeNil() { 281 | if err := enc.composer.composeNil(); err != nil { 282 | panic(err) 283 | } 284 | } 285 | 286 | // Encode a boolean value 287 | func (enc *Encoder) encodeBool(v bool) { 288 | if err := enc.composer.composeBoolean(v); err != nil { 289 | panic(err) 290 | } 291 | } 292 | 293 | // Encode a signed in of any size 294 | func (enc *Encoder) encodeInt(v int64) { 295 | if _, err := enc.composer.composeInt(v); err != nil { 296 | panic(err) 297 | } 298 | } 299 | 300 | // Encode an unsigned int of any size 301 | func (enc *Encoder) encodeUint(v uint64) { 302 | if _, err := enc.composer.composeUint(v); err != nil { 303 | panic(err) 304 | } 305 | } 306 | 307 | // Encode a float16 308 | func (enc *Encoder) encodeFloat16(v float16) { 309 | if err := enc.composer.composeFloat16(v); err != nil { 310 | panic(err) 311 | } 312 | } 313 | 314 | // Encode a float32 315 | func (enc *Encoder) encodeFloat32(v float32) { 316 | if err := enc.composer.composeFloat32(v); err != nil { 317 | panic(err) 318 | } 319 | } 320 | 321 | // Encode a float64 322 | func (enc *Encoder) encodeFloat64(v float64) { 323 | if err := enc.composer.composeFloat64(v); err != nil { 324 | panic(err) 325 | } 326 | } 327 | 328 | // Encode a bytes string 329 | func (enc *Encoder) encodeByteString(v []byte) { 330 | if err := enc.composer.composeBytes(v); err != nil { 331 | panic(err) 332 | } 333 | } 334 | 335 | // Encode a positive big.Int 336 | func (enc *Encoder) encodeBigUint(v big.Int) { 337 | if err := enc.composer.composeBigUint(v); err != nil { 338 | panic(err) 339 | } 340 | } 341 | 342 | // Encode a negative big.Int 343 | func (enc *Encoder) encodeBigInt(v big.Int) { 344 | if err := enc.composer.composeBigInt(v); err != nil { 345 | panic(err) 346 | } 347 | } 348 | 349 | // Encode a datetime as epoch 350 | func (enc *Encoder) encodeEpochDateTime(v time.Time) { 351 | if err := enc.composer.composeEpochDateTime(v); err != nil { 352 | panic(err) 353 | } 354 | } 355 | 356 | // Encode a big float 357 | func (enc *Encoder) encodeBigFloat(v big.Rat) { 358 | if err := enc.composer.composeBigFloat(v); err != nil { 359 | panic(err) 360 | } 361 | } 362 | 363 | // Encode a Text String (UTF-8) 364 | func (enc *Encoder) encodeTextString(v string) { 365 | if err := enc.composer.composeString(v); err != nil { 366 | panic(err) 367 | } 368 | } 369 | 370 | // Encode an Slice 371 | func (enc *Encoder) encodeSlice(rv reflect.Value) { 372 | etp := rv.Type().Elem() 373 | if etp.Kind() == reflect.Uint8 { 374 | // Bytes String 375 | enc.encodeByteString(rv.Bytes()) 376 | return 377 | } 378 | l := rv.Len() 379 | info, err := calculateInfoFromIntLength(l) 380 | if err != nil { 381 | panic(err) 382 | } 383 | if err := enc.composer.composeInformation(cborDataArray, info); err != nil { 384 | panic(err) 385 | } 386 | if info > cborSmallInt { 387 | enc.encodeUint(uint64(l)) 388 | } 389 | for i := 0; i < l; i++ { 390 | if err := enc.encode(rv.Index(i)); err != nil { 391 | panic(err) 392 | } 393 | } 394 | } 395 | 396 | // Encode a Map 397 | func (enc *Encoder) encodeMap(rv reflect.Value) { 398 | l := rv.Len() 399 | info, err := calculateInfoFromIntLength(l) 400 | if err != nil { 401 | panic(err) 402 | } 403 | if err := enc.composer.composeInformation(cborDataMap, info); err != nil { 404 | panic(err) 405 | } 406 | if info > cborSmallInt { 407 | enc.encodeUint(uint64(l)) 408 | } 409 | for _, key := range rv.MapKeys() { 410 | if err := enc.encode(key); err != nil { 411 | panic(err) 412 | } 413 | if err := enc.encode(rv.MapIndex(key)); err != nil { 414 | panic(err) 415 | } 416 | } 417 | 418 | } 419 | 420 | // Encode a Struct 421 | func (enc *Encoder) encodeStruct(rv reflect.Value, array ...bool) { 422 | // buffer the fields encoding 423 | buf := bytes.NewBuffer(nil) 424 | w := enc.composer.w 425 | enc.composer.w = buf 426 | 427 | exportedFields := 0 428 | numfields := rv.NumField() 429 | for i := 0; i < numfields; i++ { 430 | field := rv.Type().Field(i) 431 | key := field.Name 432 | if unicode.IsUpper(rune(key[0])) { 433 | tag := field.Tag.Get("cbor") 434 | if tag != "" { 435 | if tag == "-" { 436 | continue 437 | } 438 | key = tag 439 | } 440 | exportedFields++ 441 | enc.encodeTextString(key) 442 | if err := enc.encode(rv.Field(i)); err != nil { 443 | panic(err) 444 | } 445 | } 446 | } 447 | 448 | enc.composer.w = w 449 | var info byte 450 | if len(array) > 0 && array[0] { 451 | info, _ = calculateInfoFromIntLength(exportedFields * 2) 452 | } else { 453 | info, _ = calculateInfoFromIntLength(exportedFields) 454 | } 455 | if err := enc.composer.composeInformation(cborDataMap, info); err != nil { 456 | panic(err) 457 | } 458 | if _, err := enc.composer.write(buf.Bytes()); err != nil { 459 | panic(err) 460 | } 461 | } 462 | 463 | // helper function that calculates the size 464 | // of the info byte depending on the given length 465 | func calculateInfoFromIntLength(l int) (info byte, err error) { 466 | if l < int(cborSmallInt) { 467 | info = byte(l) 468 | } else { 469 | if info, err = infoHelper(uint(l)); err != nil { 470 | return 0, err 471 | } 472 | } 473 | return info, nil 474 | } 475 | -------------------------------------------------------------------------------- /encoder_test.go: -------------------------------------------------------------------------------- 1 | // A Golang RFC7049 implementation 2 | // Copyright (C) 2015 Oscar Campos 3 | 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | 16 | package cbor 17 | 18 | import ( 19 | "bytes" 20 | "fmt" 21 | "math/big" 22 | "testing" 23 | "time" 24 | ) 25 | 26 | func TestEncodeNil(t *testing.T) { 27 | buf := bytes.NewBuffer(nil) 28 | e := NewEncoder(buf) 29 | check(e.Encode(nil)) 30 | expect(buf.Bytes()[0], absoluteNil, t, "TestEncodeNil") 31 | } 32 | 33 | func TestEncodeBool(t *testing.T) { 34 | buf := bytes.NewBuffer(nil) 35 | e := NewEncoder(buf) 36 | check(e.Encode(false)) 37 | expect(buf.Bytes()[0], absoluteFalse, t, "TestEncodeBool") 38 | check(e.Encode(true)) 39 | expect(buf.Bytes()[1], absoluteTrue, t, "TestEncodeBool") 40 | } 41 | 42 | func TestEncodePointerToBool(t *testing.T) { 43 | buf := bytes.NewBuffer(nil) 44 | e := NewEncoder(buf) 45 | var v bool = false 46 | check(e.Encode(&v)) 47 | expect(buf.Bytes()[0], absoluteFalse, t, "TestEncodePointerToBool") 48 | v = true 49 | check(e.Encode(&v)) 50 | expect(buf.Bytes()[1], absoluteTrue, t, "TestEncodePointerToBool") 51 | } 52 | 53 | func TestEncodeUint8(t *testing.T) { 54 | buf := bytes.NewBuffer(nil) 55 | e := NewEncoder(buf) 56 | check(e.Encode(uint8(200))) 57 | expect(buf.Bytes()[0], byte(cborUint8), t, "TestEncodeUint8") 58 | expect(buf.Bytes()[1], uint8(200), t, "TestEncodeUint8") 59 | check(e.Encode(uint8(10))) 60 | expect(buf.Bytes()[2], byte(cborUnsignedInt+Major(0x0a)), t, "TestEncodeUint8") 61 | } 62 | 63 | func TestEncodePointerToUint8(t *testing.T) { 64 | buf := bytes.NewBuffer(nil) 65 | e := NewEncoder(buf) 66 | var v uint8 = 200 67 | check(e.Encode(&v)) 68 | expect(buf.Bytes()[0], byte(cborUint8), t, "TestEncodePointerToUint8") 69 | expect(buf.Bytes()[1], uint8(200), t, "TestEncodePointerToUint8") 70 | } 71 | 72 | func TestEncodeUint16(t *testing.T) { 73 | buf := bytes.NewBuffer(nil) 74 | e := NewEncoder(buf) 75 | check(e.Encode(uint16(65000))) 76 | expect(buf.Bytes()[0], byte(cborUint16), t, "TestEncodeUint16") 77 | expect(buf.Bytes()[1], byte(0xfd), t, "TestEncodeUint16") 78 | expect(buf.Bytes()[2], byte(0xe8), t, "TestEncodeUint16") 79 | } 80 | 81 | func TestEncodePointerToUint16(t *testing.T) { 82 | buf := bytes.NewBuffer(nil) 83 | e := NewEncoder(buf) 84 | var v uint16 = 65000 85 | check(e.Encode(&v)) 86 | expect(buf.Bytes()[0], byte(cborUint16), t, "TestEncodePointerToUint16") 87 | expect(buf.Bytes()[1], byte(0xfd), t, "TestEncodePointerToUint16") 88 | expect(buf.Bytes()[2], byte(0xe8), t, "TestEncodePointerToUint16") 89 | } 90 | 91 | func TestEncodeUint32(t *testing.T) { 92 | buf := bytes.NewBuffer(nil) 93 | e := NewEncoder(buf) 94 | check(e.Encode(uint32(650000))) 95 | expect(buf.Bytes()[0], byte(cborUint32), t, "TestEncodeUint32") 96 | expect(buf.Bytes()[1], byte(0x00), t, "TestEncodeUint32") 97 | expect(buf.Bytes()[2], byte(0x09), t, "TestEncodeUint32") 98 | expect(buf.Bytes()[3], byte(0xeb), t, "TestEncodeUint32") 99 | expect(buf.Bytes()[4], byte(0x10), t, "TestEncodeUint32") 100 | } 101 | 102 | func TestEncodePointerToUint32(t *testing.T) { 103 | buf := bytes.NewBuffer(nil) 104 | e := NewEncoder(buf) 105 | var v uint32 = 650000 106 | check(e.Encode(&v)) 107 | expect(buf.Bytes()[0], byte(cborUint32), t, "TestEncodePointerToUint32") 108 | expect(buf.Bytes()[1], byte(0x00), t, "TestEncodePointerToUint32") 109 | expect(buf.Bytes()[2], byte(0x09), t, "TestEncodePointerToUint32") 110 | expect(buf.Bytes()[3], byte(0xeb), t, "TestEncodePointerToUint32") 111 | expect(buf.Bytes()[4], byte(0x10), t, "TestEncodePointerToUint32") 112 | } 113 | 114 | func TestEncodeUint64(t *testing.T) { 115 | buf := bytes.NewBuffer(nil) 116 | e := NewEncoder(buf) 117 | check(e.Encode(uint64(6500000000))) 118 | expect(buf.Bytes()[0], byte(cborUint64), t, "TestEncodeUint64") 119 | expect(buf.Bytes()[1], byte(0x00), t, "TestEncodeUint64") 120 | expect(buf.Bytes()[2], byte(0x00), t, "TestEncodeUint64") 121 | expect(buf.Bytes()[3], byte(0x00), t, "TestEncodeUint64") 122 | expect(buf.Bytes()[4], byte(0x01), t, "TestEncodeUint64") 123 | expect(buf.Bytes()[5], byte(0x83), t, "TestEncodeUint64") 124 | expect(buf.Bytes()[6], byte(0x6e), t, "TestEncodeUint64") 125 | expect(buf.Bytes()[7], byte(0x21), t, "TestEncodeUint64") 126 | expect(buf.Bytes()[8], byte(0x00), t, "TestEncodeUint64") 127 | } 128 | 129 | func TestEncodePointerToUint64(t *testing.T) { 130 | buf := bytes.NewBuffer(nil) 131 | e := NewEncoder(buf) 132 | var v uint64 = 6500000000 133 | check(e.Encode(&v)) 134 | expect(buf.Bytes()[0], byte(cborUint64), t, "TestEncodePointerToUint64") 135 | expect(buf.Bytes()[1], byte(0x00), t, "TestEncodePointerToUint64") 136 | expect(buf.Bytes()[2], byte(0x00), t, "TestEncodePointerToUint64") 137 | expect(buf.Bytes()[3], byte(0x00), t, "TestEncodePointerToUint64") 138 | expect(buf.Bytes()[4], byte(0x01), t, "TestEncodePointerToUint64") 139 | expect(buf.Bytes()[5], byte(0x83), t, "TestEncodePointerToUint64") 140 | expect(buf.Bytes()[6], byte(0x6e), t, "TestEncodePointerToUint64") 141 | expect(buf.Bytes()[7], byte(0x21), t, "TestEncodePointerToUint64") 142 | expect(buf.Bytes()[8], byte(0x00), t, "TestEncodePointerToUint64") 143 | } 144 | 145 | func TestEncodeInt8(t *testing.T) { 146 | buf := bytes.NewBuffer(nil) 147 | e := NewEncoder(buf) 148 | check(e.Encode(int8(-16))) 149 | expect(Major(buf.Bytes()[0]>>5), cborNegativeInt, t, "TestEncodeInt") 150 | expect(buf.Bytes()[0]&0x1f, byte(0x0f), t, "TestEncodeInt8") 151 | check(e.Encode(int8(-100))) 152 | expect(Major(buf.Bytes()[1]>>5), cborNegativeInt, t, "TestEncodeInt8") 153 | expect(buf.Bytes()[1]&0x1f, uint8(cborUint8), t, "TestEncodeInt8") 154 | expect(buf.Bytes()[2], byte(0x63), t, "TestEncodeInt8") 155 | check(e.Encode(int8(16))) 156 | expect(buf.Bytes()[3], byte(cborUnsignedInt+Major(0x10)), t, "TestEncodeInt8") 157 | check(e.Encode(int8(100))) 158 | expect(buf.Bytes()[4], byte(cborUint8), t, "TestEncodeInt8") 159 | expect(buf.Bytes()[5], byte(0x64), t, "TestEncodeInt8") 160 | } 161 | 162 | func TestEncodePointerToInt8(t *testing.T) { 163 | buf := bytes.NewBuffer(nil) 164 | e := NewEncoder(buf) 165 | var v int8 = -16 166 | check(e.Encode(&v)) 167 | expect(Major(buf.Bytes()[0]>>5), cborNegativeInt, t, "TestEncodeInt") 168 | expect(buf.Bytes()[0]&0x1f, byte(0x0f), t, "TestEncodePointerToInt8") 169 | v = -100 170 | check(e.Encode(&v)) 171 | expect(Major(buf.Bytes()[1]>>5), cborNegativeInt, t, "TestEncodePointerToInt8") 172 | expect(buf.Bytes()[1]&0x1f, uint8(cborUint8), t, "TestEncodePointerToInt8") 173 | expect(buf.Bytes()[2], byte(0x63), t, "TestEncodePointerToInt8") 174 | v = 16 175 | check(e.Encode(&v)) 176 | expect(buf.Bytes()[3], byte(cborUnsignedInt+Major(0x10)), t, "TestEncodePointerToInt8") 177 | v = 100 178 | check(e.Encode(&v)) 179 | expect(buf.Bytes()[4], byte(cborUint8), t, "TestEncodePointerToInt8") 180 | expect(buf.Bytes()[5], byte(0x64), t, "TestEncodePointerToInt8") 181 | } 182 | 183 | func TestEncodeInt16(t *testing.T) { 184 | buf := bytes.NewBuffer(nil) 185 | e := NewEncoder(buf) 186 | check(e.Encode(int16(-32000))) 187 | expect(Major(buf.Bytes()[0]>>5), cborNegativeInt, t, "TestEncodeInt16") 188 | expect(buf.Bytes()[0]&0x1f, uint8(cborUint16), t, "TestEncodeInt16") 189 | expect(buf.Bytes()[1], byte(0x7c), t, "TestEncodeInt16") 190 | expect(buf.Bytes()[2], byte(0xff), t, "TestEncodeInt16") 191 | check(e.Encode(int16(32000))) 192 | expect(buf.Bytes()[3], byte(cborUint16), t, "TestEncodeInt16") 193 | expect(buf.Bytes()[4], byte(0x7d), t, "TestEncodeInt16") 194 | expect(buf.Bytes()[5], byte(0x00), t, "TestEncodeInt16") 195 | } 196 | 197 | func TestEncodePointerToInt16(t *testing.T) { 198 | buf := bytes.NewBuffer(nil) 199 | e := NewEncoder(buf) 200 | var v int16 = -32000 201 | check(e.Encode(&v)) 202 | expect(Major(buf.Bytes()[0]>>5), cborNegativeInt, t, "TestEncodePointerToInt16") 203 | expect(buf.Bytes()[0]&0x1f, uint8(cborUint16), t, "TestEncodePointerToInt16") 204 | expect(buf.Bytes()[1], byte(0x7c), t, "TestEncodePointerToInt16") 205 | expect(buf.Bytes()[2], byte(0xff), t, "TestEncodePointerToInt16") 206 | v = 32000 207 | check(e.Encode(&v)) 208 | expect(buf.Bytes()[3], byte(cborUint16), t, "TestEncodePointerToInt16") 209 | expect(buf.Bytes()[4], byte(0x7d), t, "TestEncodePointerToInt16") 210 | expect(buf.Bytes()[5], byte(0x00), t, "TestEncodePointerToInt16") 211 | } 212 | 213 | func TestEncodeInt32(t *testing.T) { 214 | buf := bytes.NewBuffer(nil) 215 | e := NewEncoder(buf) 216 | check(e.Encode(int32(-2147483647))) 217 | expect(Major(buf.Bytes()[0]>>5), cborNegativeInt, t, "TestEncodeInt32") 218 | expect(buf.Bytes()[0]&0x1f, uint8(cborUint32), t, "TestEncodeInt32") 219 | expect(buf.Bytes()[1], byte(0x7f), t, "TestEncodeInt32") 220 | expect(buf.Bytes()[2], byte(0xff), t, "TestEncodeInt32") 221 | expect(buf.Bytes()[3], byte(0xff), t, "TestEncodeInt32") 222 | expect(buf.Bytes()[4], byte(0xfe), t, "TestEncodeInt32") 223 | check(e.Encode(int32(2147483647))) 224 | expect(buf.Bytes()[5], byte(cborUint32), t, "TestEncodeInt32") 225 | expect(buf.Bytes()[6], byte(0x7f), t, "TestEncodeInt32") 226 | expect(buf.Bytes()[7], byte(0xff), t, "TestEncodeInt32") 227 | expect(buf.Bytes()[8], byte(0xff), t, "TestEncodeInt32") 228 | expect(buf.Bytes()[9], byte(0xff), t, "TestEncodeInt32") 229 | } 230 | 231 | func TestEncodePointerToInt32(t *testing.T) { 232 | buf := bytes.NewBuffer(nil) 233 | e := NewEncoder(buf) 234 | var v int32 = -2147483647 235 | check(e.Encode(&v)) 236 | expect(Major(buf.Bytes()[0]>>5), cborNegativeInt, t, "TestEncodePointerToInt32") 237 | expect(buf.Bytes()[0]&0x1f, uint8(cborUint32), t, "TestEncodePointerToInt32") 238 | expect(buf.Bytes()[1], byte(0x7f), t, "TestEncodePointerToInt32") 239 | expect(buf.Bytes()[2], byte(0xff), t, "TestEncodePointerToInt32") 240 | expect(buf.Bytes()[3], byte(0xff), t, "TestEncodePointerToInt32") 241 | expect(buf.Bytes()[4], byte(0xfe), t, "TestEncodePointerToInt32") 242 | v = 2147483647 243 | check(e.Encode(&v)) 244 | expect(buf.Bytes()[5], byte(cborUint32), t, "TestEncodeInt32") 245 | expect(buf.Bytes()[6], byte(0x7f), t, "TestEncodeInt32") 246 | expect(buf.Bytes()[7], byte(0xff), t, "TestEncodeInt32") 247 | expect(buf.Bytes()[8], byte(0xff), t, "TestEncodeInt32") 248 | expect(buf.Bytes()[9], byte(0xff), t, "TestEncodeInt32") 249 | } 250 | 251 | func TestEncodeInt64(t *testing.T) { 252 | buf := bytes.NewBuffer(nil) 253 | e := NewEncoder(buf) 254 | check(e.Encode(int64(-184467440737095516))) 255 | expect(Major(buf.Bytes()[0]>>5), cborNegativeInt, t, "TestEncodeInt64") 256 | expect(buf.Bytes()[0]&0x1f, uint8(cborUint64), t, "TestEncodeInt64") 257 | expect(buf.Bytes()[1], byte(0x02), t, "TestEncodeInt64") 258 | expect(buf.Bytes()[2], byte(0x8f), t, "TestEncodeInt64") 259 | expect(buf.Bytes()[3], byte(0x5c), t, "TestEncodeInt64") 260 | expect(buf.Bytes()[4], byte(0x28), t, "TestEncodeInt64") 261 | expect(buf.Bytes()[5], byte(0xf5), t, "TestEncodeInt64") 262 | expect(buf.Bytes()[6], byte(0xc2), t, "TestEncodeInt64") 263 | expect(buf.Bytes()[7], byte(0x8f), t, "TestEncodeInt64") 264 | expect(buf.Bytes()[8], byte(0x5b), t, "TestEncodeInt64") 265 | check(e.Encode(int64(184467440737095516))) 266 | expect(buf.Bytes()[9], byte(cborUint64), t, "TestEncodeInt64") 267 | expect(buf.Bytes()[10], byte(0x02), t, "TestEncodeInt64") 268 | expect(buf.Bytes()[11], byte(0x8f), t, "TestEncodeInt64") 269 | expect(buf.Bytes()[12], byte(0x5c), t, "TestEncodeInt64") 270 | expect(buf.Bytes()[13], byte(0x28), t, "TestEncodeInt64") 271 | expect(buf.Bytes()[14], byte(0xf5), t, "TestEncodeInt64") 272 | expect(buf.Bytes()[15], byte(0xc2), t, "TestEncodeInt64") 273 | expect(buf.Bytes()[16], byte(0x8f), t, "TestEncodeInt64") 274 | expect(buf.Bytes()[17], byte(0x5c), t, "TestEncodeInt64") 275 | } 276 | 277 | func TestEncodePointerToInt64(t *testing.T) { 278 | buf := bytes.NewBuffer(nil) 279 | e := NewEncoder(buf) 280 | var v int64 = -184467440737095516 281 | check(e.Encode(&v)) 282 | expect(Major(buf.Bytes()[0]>>5), cborNegativeInt, t, "TestEncodePointerToInt64") 283 | expect(buf.Bytes()[0]&0x1f, uint8(cborUint64), t, "TestEncodePointerToInt64") 284 | expect(buf.Bytes()[1], byte(0x02), t, "TestEncodePointerToInt64") 285 | expect(buf.Bytes()[2], byte(0x8f), t, "TestEncodePointerToInt64") 286 | expect(buf.Bytes()[3], byte(0x5c), t, "TestEncodePointerToInt64") 287 | expect(buf.Bytes()[4], byte(0x28), t, "TestEncodePointerToInt64") 288 | expect(buf.Bytes()[5], byte(0xf5), t, "TestEncodePointerToInt64") 289 | expect(buf.Bytes()[6], byte(0xc2), t, "TestEncodePointerToInt64") 290 | expect(buf.Bytes()[7], byte(0x8f), t, "TestEncodePointerToInt64") 291 | expect(buf.Bytes()[8], byte(0x5b), t, "TestEncodePointerToInt64") 292 | v = 184467440737095516 293 | check(e.Encode(&v)) 294 | expect(buf.Bytes()[9], byte(cborUint64), t, "TestEncodePointerToInt64") 295 | expect(buf.Bytes()[10], byte(0x02), t, "TestEncodePointerToInt64") 296 | expect(buf.Bytes()[11], byte(0x8f), t, "TestEncodePointerToInt64") 297 | expect(buf.Bytes()[12], byte(0x5c), t, "TestEncodePointerToInt64") 298 | expect(buf.Bytes()[13], byte(0x28), t, "TestEncodePointerToInt64") 299 | expect(buf.Bytes()[14], byte(0xf5), t, "TestEncodePointerToInt64") 300 | expect(buf.Bytes()[15], byte(0xc2), t, "TestEncodePointerToInt64") 301 | expect(buf.Bytes()[16], byte(0x8f), t, "TestEncodePointerToInt64") 302 | expect(buf.Bytes()[17], byte(0x5c), t, "TestEncodePointerToInt64") 303 | } 304 | 305 | func TestEncodeUint(t *testing.T) { 306 | buf := bytes.NewBuffer(nil) 307 | e := NewEncoder(buf) 308 | check(e.Encode(uint(23))) 309 | expect(buf.Bytes()[0], byte(0x17), t, "TestEncodeUint") 310 | check(e.Encode(uint(1000000))) 311 | expect(buf.Bytes()[1], byte(0x1a), t, "TestEncodeUint") 312 | expect(buf.Bytes()[2], byte(0x00), t, "TestEncodeUint") 313 | expect(buf.Bytes()[3], byte(0x0f), t, "TestEncodeUint") 314 | expect(buf.Bytes()[4], byte(0x42), t, "TestEncodeUint") 315 | expect(buf.Bytes()[5], byte(0x40), t, "TestEncodeUint") 316 | } 317 | 318 | func TestEncodePointerToUint(t *testing.T) { 319 | buf := bytes.NewBuffer(nil) 320 | e := NewEncoder(buf) 321 | var v uint = 23 322 | check(e.Encode(&v)) 323 | expect(buf.Bytes()[0], byte(0x17), t, "TestEncodePointerToUint") 324 | v = 1000000 325 | check(e.Encode(&v)) 326 | expect(buf.Bytes()[1], byte(0x1a), t, "TestEncodePointerToUint") 327 | expect(buf.Bytes()[2], byte(0x00), t, "TestEncodePointerToUint") 328 | expect(buf.Bytes()[3], byte(0x0f), t, "TestEncodePointerToUint") 329 | expect(buf.Bytes()[4], byte(0x42), t, "TestEncodePointerToUint") 330 | expect(buf.Bytes()[5], byte(0x40), t, "TestEncodePointerToUint") 331 | } 332 | 333 | func TestEncodeInt(t *testing.T) { 334 | buf := bytes.NewBuffer(nil) 335 | e := NewEncoder(buf) 336 | check(e.Encode(int(-10))) 337 | expect(buf.Bytes()[0], byte(0x29), t, "TestEncodeInt") 338 | check(e.Encode(int(-1000))) 339 | expect(buf.Bytes()[1], byte(0x39), t, "TestEncodeInt") 340 | expect(buf.Bytes()[2], byte(0x03), t, "TestEncodeInt") 341 | expect(buf.Bytes()[3], byte(0xe7), t, "TestEncodeInt") 342 | check(e.Encode(int(23))) 343 | expect(buf.Bytes()[4], byte(0x17), t, "TestEncodeInt") 344 | check(e.Encode(int(24))) 345 | expect(buf.Bytes()[5], byte(0x18), t, "TestEncodeInt") 346 | expect(buf.Bytes()[6], byte(0x18), t, "TestEncodeInt") 347 | } 348 | 349 | func TestEncodePointerToInt(t *testing.T) { 350 | buf := bytes.NewBuffer(nil) 351 | e := NewEncoder(buf) 352 | var v int = -10 353 | check(e.Encode(&v)) 354 | expect(buf.Bytes()[0], byte(0x29), t, "TestEncodePointerToInt") 355 | v = -1000 356 | check(e.Encode(&v)) 357 | expect(buf.Bytes()[1], byte(0x39), t, "TestEncodePointerToInt") 358 | expect(buf.Bytes()[2], byte(0x03), t, "TestEncodePointerToInt") 359 | expect(buf.Bytes()[3], byte(0xe7), t, "TestEncodePointerToInt") 360 | v = 23 361 | check(e.Encode(&v)) 362 | expect(buf.Bytes()[4], byte(0x17), t, "TestEncodeInt") 363 | v = 24 364 | check(e.Encode(&v)) 365 | expect(buf.Bytes()[5], byte(0x18), t, "TestEncodeInt") 366 | expect(buf.Bytes()[6], byte(0x18), t, "TestEncodeInt") 367 | } 368 | 369 | func TestEncodeFloat16(t *testing.T) { 370 | buf := bytes.NewBuffer(nil) 371 | e := NewEncoder(buf) 372 | check(e.Encode(float16(1.5))) 373 | expect(buf.Bytes()[0], byte(0xf9), t, "TestEncodeFloat16") 374 | expect(buf.Bytes()[1], byte(0x3e), t, "TestEncodeFloat16") 375 | expect(buf.Bytes()[2], byte(0x00), t, "TestEncodeFloat16") 376 | check(e.Encode(float16(1.0))) 377 | expect(buf.Bytes()[3], byte(0xf9), t, "TestEncodeFloat16") 378 | expect(buf.Bytes()[4], byte(0x3c), t, "TestEncodeFloat16") 379 | expect(buf.Bytes()[5], byte(0x00), t, "TestEncodeFloat16") 380 | check(e.Encode(float16(65504.0))) 381 | expect(buf.Bytes()[6], byte(0xf9), t, "TestEncodeFloat16") 382 | expect(buf.Bytes()[7], byte(0x7b), t, "TestEncodeFloat16") 383 | expect(buf.Bytes()[8], byte(0xff), t, "TestEncodeFloat16") 384 | check(e.Encode(float16(0.00006103515625))) 385 | expect(buf.Bytes()[9], byte(0xf9), t, "TestEncodeFloat16") 386 | expect(buf.Bytes()[10], byte(0x04), t, "TestEncodeFloat16") 387 | expect(buf.Bytes()[11], byte(0x00), t, "TestEncodeFloat16") 388 | } 389 | 390 | func TestEncodePointerToFloat16(t *testing.T) { 391 | buf := bytes.NewBuffer(nil) 392 | e := NewEncoder(buf) 393 | var v float16 = 1.5 394 | check(e.Encode(&v)) 395 | expect(buf.Bytes()[0], byte(0xf9), t, "TestEncodePointerToFloat16") 396 | expect(buf.Bytes()[1], byte(0x3e), t, "TestEncodePointerToFloat16") 397 | expect(buf.Bytes()[2], byte(0x00), t, "TestEncodePointerToFloat16") 398 | v = 1.0 399 | check(e.Encode(&v)) 400 | expect(buf.Bytes()[3], byte(0xf9), t, "TestEncodePointerToFloat16") 401 | expect(buf.Bytes()[4], byte(0x3c), t, "TestEncodePointerToFloat16") 402 | expect(buf.Bytes()[5], byte(0x00), t, "TestEncodePointerToFloat16") 403 | v = 65504.0 404 | check(e.Encode(&v)) 405 | expect(buf.Bytes()[6], byte(0xf9), t, "TestEncodePointerToFloat16") 406 | expect(buf.Bytes()[7], byte(0x7b), t, "TestEncodePointerToFloat16") 407 | expect(buf.Bytes()[8], byte(0xff), t, "TestEncodePointerToFloat16") 408 | v = 0.00006103515625 409 | check(e.Encode(&v)) 410 | expect(buf.Bytes()[9], byte(0xf9), t, "TestEncodePointerToFloat16") 411 | expect(buf.Bytes()[10], byte(0x04), t, "TestEncodePointerToFloat16") 412 | expect(buf.Bytes()[11], byte(0x00), t, "TestEncodePointerToFloat16") 413 | } 414 | 415 | func TestEncodeFloat32(t *testing.T) { 416 | buf := bytes.NewBuffer(nil) 417 | e := NewEncoder(buf) 418 | check(e.Encode(float32(100000.0))) 419 | expect(buf.Bytes()[0], byte(0xfa), t, "TestEncodeFloat32") 420 | expect(buf.Bytes()[1], byte(0x47), t, "TestEncodeFloat32") 421 | expect(buf.Bytes()[2], byte(0xc3), t, "TestEncodeFloat32") 422 | expect(buf.Bytes()[3], byte(0x50), t, "TestEncodeFloat32") 423 | expect(buf.Bytes()[4], byte(0x00), t, "TestEncodeFloat32") 424 | check(e.Encode(float32(3.4028234663852886e+38))) 425 | expect(buf.Bytes()[5], byte(0xfa), t, "TestEncodeFloat32") 426 | expect(buf.Bytes()[6], byte(0x7f), t, "TestEncodeFloat32") 427 | expect(buf.Bytes()[7], byte(0x7f), t, "TestEncodeFloat32") 428 | expect(buf.Bytes()[8], byte(0xff), t, "TestEncodeFloat32") 429 | expect(buf.Bytes()[9], byte(0xff), t, "TestEncodeFloat32") 430 | } 431 | 432 | func TestEncodePointerToFloat32(t *testing.T) { 433 | buf := bytes.NewBuffer(nil) 434 | e := NewEncoder(buf) 435 | var v float32 = 100000.0 436 | check(e.Encode(&v)) 437 | expect(buf.Bytes()[0], byte(0xfa), t, "TestEncodePointerToFloat32") 438 | expect(buf.Bytes()[1], byte(0x47), t, "TestEncodePointerToFloat32") 439 | expect(buf.Bytes()[2], byte(0xc3), t, "TestEncodePointerToFloat32") 440 | expect(buf.Bytes()[3], byte(0x50), t, "TestEncodePointerToFloat32") 441 | expect(buf.Bytes()[4], byte(0x00), t, "TestEncodePointerToFloat32") 442 | v = 3.4028234663852886e+38 443 | check(e.Encode(&v)) 444 | expect(buf.Bytes()[5], byte(0xfa), t, "TestEncodePointerToFloat32") 445 | expect(buf.Bytes()[6], byte(0x7f), t, "TestEncodePointerToFloat32") 446 | expect(buf.Bytes()[7], byte(0x7f), t, "TestEncodePointerToFloat32") 447 | expect(buf.Bytes()[8], byte(0xff), t, "TestEncodePointerToFloat32") 448 | expect(buf.Bytes()[9], byte(0xff), t, "TestEncodePointerToFloat32") 449 | } 450 | 451 | func TestEncodeFloat64(t *testing.T) { 452 | buf := bytes.NewBuffer(nil) 453 | e := NewEncoder(buf) 454 | check(e.Encode(float64(1.1))) 455 | expect(buf.Bytes()[0], byte(0xfb), t, "TestEncodeFloat64") 456 | expect(buf.Bytes()[1], byte(0x3f), t, "TestEncodeFloat64") 457 | expect(buf.Bytes()[2], byte(0xf1), t, "TestEncodeFloat64") 458 | expect(buf.Bytes()[3], byte(0x99), t, "TestEncodeFloat64") 459 | expect(buf.Bytes()[4], byte(0x99), t, "TestEncodeFloat64") 460 | expect(buf.Bytes()[5], byte(0x99), t, "TestEncodeFloat64") 461 | expect(buf.Bytes()[6], byte(0x99), t, "TestEncodeFloat64") 462 | expect(buf.Bytes()[7], byte(0x99), t, "TestEncodeFloat64") 463 | expect(buf.Bytes()[8], byte(0x9a), t, "TestEncodeFloat64") 464 | check(e.Encode(float64(-4.1))) 465 | expect(buf.Bytes()[9], byte(0xfb), t, "TestEncodeFloat64") 466 | expect(buf.Bytes()[10], byte(0xc0), t, "TestEncodeFloat64") 467 | expect(buf.Bytes()[11], byte(0x10), t, "TestEncodeFloat64") 468 | expect(buf.Bytes()[12], byte(0x66), t, "TestEncodeFloat64") 469 | expect(buf.Bytes()[13], byte(0x66), t, "TestEncodeFloat64") 470 | expect(buf.Bytes()[14], byte(0x66), t, "TestEncodeFloat64") 471 | expect(buf.Bytes()[15], byte(0x66), t, "TestEncodeFloat64") 472 | expect(buf.Bytes()[16], byte(0x66), t, "TestEncodeFloat64") 473 | expect(buf.Bytes()[17], byte(0x66), t, "TestEncodeFloat64") 474 | check(e.Encode(float64(1.0e+300))) 475 | expect(buf.Bytes()[18], byte(0xfb), t, "TestEncodeFloat64") 476 | expect(buf.Bytes()[19], byte(0x7e), t, "TestEncodeFloat64") 477 | expect(buf.Bytes()[20], byte(0x37), t, "TestEncodeFloat64") 478 | expect(buf.Bytes()[21], byte(0xe4), t, "TestEncodeFloat64") 479 | expect(buf.Bytes()[22], byte(0x3c), t, "TestEncodeFloat64") 480 | expect(buf.Bytes()[23], byte(0x88), t, "TestEncodeFloat64") 481 | expect(buf.Bytes()[24], byte(0x00), t, "TestEncodeFloat64") 482 | expect(buf.Bytes()[25], byte(0x75), t, "TestEncodeFloat64") 483 | expect(buf.Bytes()[26], byte(0x9c), t, "TestEncodeFloat64") 484 | } 485 | 486 | func TestEncodePointerToFloat64(t *testing.T) { 487 | buf := bytes.NewBuffer(nil) 488 | e := NewEncoder(buf) 489 | var v float64 = 1.1 490 | check(e.Encode(&v)) 491 | expect(buf.Bytes()[0], byte(0xfb), t, "TestEncodePointerToFloat64") 492 | expect(buf.Bytes()[1], byte(0x3f), t, "TestEncodePointerToFloat64") 493 | expect(buf.Bytes()[2], byte(0xf1), t, "TestEncodePointerToFloat64") 494 | expect(buf.Bytes()[3], byte(0x99), t, "TestEncodePointerToFloat64") 495 | expect(buf.Bytes()[4], byte(0x99), t, "TestEncodePointerToFloat64") 496 | expect(buf.Bytes()[5], byte(0x99), t, "TestEncodePointerToFloat64") 497 | expect(buf.Bytes()[6], byte(0x99), t, "TestEncodePointerToFloat64") 498 | expect(buf.Bytes()[7], byte(0x99), t, "TestEncodePointerToFloat64") 499 | expect(buf.Bytes()[8], byte(0x9a), t, "TestEncodePointerToFloat64") 500 | v = -4.1 501 | check(e.Encode(&v)) 502 | expect(buf.Bytes()[9], byte(0xfb), t, "TestEncodePointerToFloat64") 503 | expect(buf.Bytes()[10], byte(0xc0), t, "TestEncodePointerToFloat64") 504 | expect(buf.Bytes()[11], byte(0x10), t, "TestEncodePointerToFloat64") 505 | expect(buf.Bytes()[12], byte(0x66), t, "TestEncodePointerToFloat64") 506 | expect(buf.Bytes()[13], byte(0x66), t, "TestEncodePointerToFloat64") 507 | expect(buf.Bytes()[14], byte(0x66), t, "TestEncodePointerToFloat64") 508 | expect(buf.Bytes()[15], byte(0x66), t, "TestEncodePointerToFloat64") 509 | expect(buf.Bytes()[16], byte(0x66), t, "TestEncodePointerToFloat64") 510 | expect(buf.Bytes()[17], byte(0x66), t, "TestEncodePointerToFloat64") 511 | v = 1.0e+300 512 | check(e.Encode(&v)) 513 | expect(buf.Bytes()[18], byte(0xfb), t, "TestEncodePointerToFloat64") 514 | expect(buf.Bytes()[19], byte(0x7e), t, "TestEncodePointerToFloat64") 515 | expect(buf.Bytes()[20], byte(0x37), t, "TestEncodePointerToFloat64") 516 | expect(buf.Bytes()[21], byte(0xe4), t, "TestEncodePointerToFloat64") 517 | expect(buf.Bytes()[22], byte(0x3c), t, "TestEncodePointerToFloat64") 518 | expect(buf.Bytes()[23], byte(0x88), t, "TestEncodePointerToFloat64") 519 | expect(buf.Bytes()[24], byte(0x00), t, "TestEncodePointerToFloat64") 520 | expect(buf.Bytes()[25], byte(0x75), t, "TestEncodePointerToFloat64") 521 | expect(buf.Bytes()[26], byte(0x9c), t, "TestEncodePointerToFloat64") 522 | } 523 | 524 | func TestEncodeByteString(t *testing.T) { 525 | buf := bytes.NewBuffer(nil) 526 | e := NewEncoder(buf) 527 | check(e.Encode([]byte("byte string"))) 528 | b := []byte{0x4b, 0x62, 0x79, 0x74, 0x65, 0x20, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67} 529 | for i, c := range b { 530 | expect(buf.Bytes()[i], c, t, "TestEncodeByteString") 531 | } 532 | } 533 | 534 | func TestEncodePointerToByteString(t *testing.T) { 535 | buf := bytes.NewBuffer(nil) 536 | e := NewEncoder(buf) 537 | var v []byte = []byte("byte string") 538 | check(e.Encode(&v)) 539 | b := []byte{0x4b, 0x62, 0x79, 0x74, 0x65, 0x20, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67} 540 | for i, c := range b { 541 | expect(buf.Bytes()[i], c, t, "TestEncodePointerToByteString") 542 | } 543 | } 544 | 545 | func TestEncodePositiveBigNum(t *testing.T) { 546 | buf := bytes.NewBuffer(nil) 547 | e := NewEncoder(buf) 548 | bn := new(big.Int) 549 | bn.SetString("18446744073709551616", 10) 550 | check(e.Encode(*bn)) 551 | expect(buf.Bytes()[0], byte(0xc2), t, "TestEncodePositiveBigNum") 552 | expect(buf.Bytes()[1], byte(0x49), t, "TestEncodePositiveBigNum") 553 | expect(buf.Bytes()[2], byte(0x01), t, "TestEncodePositiveBigNum") 554 | expect(buf.Bytes()[3], byte(0x00), t, "TestEncodePositiveBigNum") 555 | expect(buf.Bytes()[4], byte(0x00), t, "TestEncodePositiveBigNum") 556 | expect(buf.Bytes()[5], byte(0x00), t, "TestEncodePositiveBigNum") 557 | expect(buf.Bytes()[6], byte(0x00), t, "TestEncodePositiveBigNum") 558 | expect(buf.Bytes()[7], byte(0x00), t, "TestEncodePositiveBigNum") 559 | expect(buf.Bytes()[8], byte(0x00), t, "TestEncodePositiveBigNum") 560 | expect(buf.Bytes()[9], byte(0x00), t, "TestEncodePositiveBigNum") 561 | expect(buf.Bytes()[10], byte(0x00), t, "TestEncodePositiveBigNum") 562 | } 563 | 564 | func TestEncodePointerToPositiveBigNum(t *testing.T) { 565 | buf := bytes.NewBuffer(nil) 566 | e := NewEncoder(buf) 567 | bn := new(big.Int) 568 | bn.SetString("18446744073709551616", 10) 569 | check(e.Encode(bn)) 570 | expect(buf.Bytes()[0], byte(0xc2), t, "TestEncodePointerToPositiveBigNum") 571 | expect(buf.Bytes()[1], byte(0x49), t, "TestEncodePointerToPositiveBigNum") 572 | expect(buf.Bytes()[2], byte(0x01), t, "TestEncodePointerToPositiveBigNum") 573 | expect(buf.Bytes()[3], byte(0x00), t, "TestEncodePointerToPositiveBigNum") 574 | expect(buf.Bytes()[4], byte(0x00), t, "TestEncodePointerToPositiveBigNum") 575 | expect(buf.Bytes()[5], byte(0x00), t, "TestEncodePointerToPositiveBigNum") 576 | expect(buf.Bytes()[6], byte(0x00), t, "TestEncodePointerToPositiveBigNum") 577 | expect(buf.Bytes()[7], byte(0x00), t, "TestEncodePointerToPositiveBigNum") 578 | expect(buf.Bytes()[8], byte(0x00), t, "TestEncodePointerToPositiveBigNum") 579 | expect(buf.Bytes()[9], byte(0x00), t, "TestEncodePointerToPositiveBigNum") 580 | expect(buf.Bytes()[10], byte(0x00), t, "TestEncodePointerToPositiveBigNum") 581 | } 582 | 583 | func TestEncodeNegativeBigNum(t *testing.T) { 584 | buf := bytes.NewBuffer(nil) 585 | e := NewEncoder(buf) 586 | bn := new(big.Int) 587 | bn.SetString("-18446744073709551617", 10) 588 | check(e.Encode(*bn)) 589 | expect(buf.Bytes()[0], byte(0xc3), t, "TestEncodeNegativeBigNum") 590 | expect(buf.Bytes()[1], byte(0x49), t, "TestEncodeNegativeBigNum") 591 | expect(buf.Bytes()[2], byte(0x01), t, "TestEncodeNegativeBigNum") 592 | expect(buf.Bytes()[3], byte(0x00), t, "TestEncodeNegativeBigNum") 593 | expect(buf.Bytes()[4], byte(0x00), t, "TestEncodeNegativeBigNum") 594 | expect(buf.Bytes()[5], byte(0x00), t, "TestEncodeNegativeBigNum") 595 | expect(buf.Bytes()[6], byte(0x00), t, "TestEncodeNegativeBigNum") 596 | expect(buf.Bytes()[7], byte(0x00), t, "TestEncodeNegativeBigNum") 597 | expect(buf.Bytes()[8], byte(0x00), t, "TestEncodeNegativeBigNum") 598 | expect(buf.Bytes()[9], byte(0x00), t, "TestEncodeNegativeBigNum") 599 | expect(buf.Bytes()[10], byte(0x00), t, "TestEncodeNegativeBigNum") 600 | } 601 | 602 | func TestEncodePoiinterToNegativeBigNum(t *testing.T) { 603 | buf := bytes.NewBuffer(nil) 604 | e := NewEncoder(buf) 605 | bn := new(big.Int) 606 | bn.SetString("-18446744073709551617", 10) 607 | check(e.Encode(bn)) 608 | expect(buf.Bytes()[0], byte(0xc3), t, "TestEncodePoiinterToNegativeBigNum") 609 | expect(buf.Bytes()[1], byte(0x49), t, "TestEncodePoiinterToNegativeBigNum") 610 | expect(buf.Bytes()[2], byte(0x01), t, "TestEncodePoiinterToNegativeBigNum") 611 | expect(buf.Bytes()[3], byte(0x00), t, "TestEncodePoiinterToNegativeBigNum") 612 | expect(buf.Bytes()[4], byte(0x00), t, "TestEncodePoiinterToNegativeBigNum") 613 | expect(buf.Bytes()[5], byte(0x00), t, "TestEncodePoiinterToNegativeBigNum") 614 | expect(buf.Bytes()[6], byte(0x00), t, "TestEncodePoiinterToNegativeBigNum") 615 | expect(buf.Bytes()[7], byte(0x00), t, "TestEncodePoiinterToNegativeBigNum") 616 | expect(buf.Bytes()[8], byte(0x00), t, "TestEncodePoiinterToNegativeBigNum") 617 | expect(buf.Bytes()[9], byte(0x00), t, "TestEncodePoiinterToNegativeBigNum") 618 | expect(buf.Bytes()[10], byte(0x00), t, "TestEncodePoiinterToNegativeBigNum") 619 | } 620 | 621 | func TestEncodeEpochDateTime(t *testing.T) { 622 | buf := bytes.NewBuffer(nil) 623 | e := NewEncoder(buf) 624 | check(e.Encode(time.Unix(1363896240, int64(0)))) 625 | expect(buf.Bytes()[0], byte(0xc1), t, "TestEncodeEpochDateTime") 626 | expect(buf.Bytes()[1], byte(0x1a), t, "TestEncodeEpochDateTime") 627 | expect(buf.Bytes()[2], byte(0x51), t, "TestEncodeEpochDateTime") 628 | expect(buf.Bytes()[3], byte(0x4b), t, "TestEncodeEpochDateTime") 629 | expect(buf.Bytes()[4], byte(0x67), t, "TestEncodeEpochDateTime") 630 | expect(buf.Bytes()[5], byte(0xb0), t, "TestEncodeEpochDateTime") 631 | } 632 | 633 | func TestEncodePointerToEpochDateTime(t *testing.T) { 634 | buf := bytes.NewBuffer(nil) 635 | e := NewEncoder(buf) 636 | var v time.Time = time.Unix(1363896240, int64(0)) 637 | check(e.Encode(&v)) 638 | expect(buf.Bytes()[0], byte(0xc1), t, "TestEncodePointerToEpochDateTime") 639 | expect(buf.Bytes()[1], byte(0x1a), t, "TestEncodePointerToEpochDateTime") 640 | expect(buf.Bytes()[2], byte(0x51), t, "TestEncodePointerToEpochDateTime") 641 | expect(buf.Bytes()[3], byte(0x4b), t, "TestEncodePointerToEpochDateTime") 642 | expect(buf.Bytes()[4], byte(0x67), t, "TestEncodePointerToEpochDateTime") 643 | expect(buf.Bytes()[5], byte(0xb0), t, "TestEncodePointerToEpochDateTime") 644 | } 645 | 646 | func TestEncodeBigFloat(t *testing.T) { 647 | buf := bytes.NewBuffer(nil) 648 | e := NewEncoder(buf) 649 | var v *big.Rat = big.NewRat(3, 2) 650 | check(e.Encode(*v)) 651 | expect(buf.Bytes()[0], byte(0xc5), t, "TestEncodeBigFloat") 652 | expect(buf.Bytes()[1], byte(0x82), t, "TestEncodeBigFloat") 653 | expect(buf.Bytes()[2], byte(0x01), t, "TestEncodeBigFloat") 654 | expect(buf.Bytes()[3], byte(0xfb), t, "TestEncodeBigFloat") 655 | expect(buf.Bytes()[4], byte(0x3f), t, "TestEncodeBigFloat") 656 | expect(buf.Bytes()[5], byte(0xe8), t, "TestEncodeBigFloat") 657 | expect(buf.Bytes()[6], byte(0x00), t, "TestEncodeBigFloat") 658 | expect(buf.Bytes()[7], byte(0x00), t, "TestEncodeBigFloat") 659 | expect(buf.Bytes()[8], byte(0x00), t, "TestEncodeBigFloat") 660 | expect(buf.Bytes()[9], byte(0x00), t, "TestEncodeBigFloat") 661 | expect(buf.Bytes()[10], byte(0x00), t, "TestEncodeBigFloat") 662 | expect(buf.Bytes()[11], byte(0x00), t, "TestEncodeBigFloat") 663 | } 664 | 665 | func TestEncodePointerToBigFloat(t *testing.T) { 666 | buf := bytes.NewBuffer(nil) 667 | e := NewEncoder(buf) 668 | var v *big.Rat = big.NewRat(3, 2) 669 | check(e.Encode(v)) 670 | expect(buf.Bytes()[0], byte(0xc5), t, "TestEncodePointerToBigFloat") 671 | expect(buf.Bytes()[1], byte(0x82), t, "TestEncodePointerToBigFloat") 672 | expect(buf.Bytes()[2], byte(0x01), t, "TestEncodePointerToBigFloat") 673 | expect(buf.Bytes()[3], byte(0xfb), t, "TestEncodePointerToBigFloat") 674 | expect(buf.Bytes()[4], byte(0x3f), t, "TestEncodePointerToBigFloat") 675 | expect(buf.Bytes()[5], byte(0xe8), t, "TestEncodePointerToBigFloat") 676 | expect(buf.Bytes()[6], byte(0x00), t, "TestEncodePointerToBigFloat") 677 | expect(buf.Bytes()[7], byte(0x00), t, "TestEncodePointerToBigFloat") 678 | expect(buf.Bytes()[8], byte(0x00), t, "TestEncodePointerToBigFloat") 679 | expect(buf.Bytes()[9], byte(0x00), t, "TestEncodePointerToBigFloat") 680 | expect(buf.Bytes()[10], byte(0x00), t, "TestEncodePointerToBigFloat") 681 | expect(buf.Bytes()[11], byte(0x00), t, "TestEncodePointerToBigFloat") 682 | } 683 | 684 | func TestEncodeString(t *testing.T) { 685 | buf := bytes.NewBuffer(nil) 686 | e := NewEncoder(buf) 687 | check(e.Encode("水")) 688 | expect(buf.Bytes()[0], byte(0x63), t, "TestEncodeString") 689 | expect(buf.Bytes()[1], byte(0xe6), t, "TestEncodeString") 690 | expect(buf.Bytes()[2], byte(0xb0), t, "TestEncodeString") 691 | expect(buf.Bytes()[3], byte(0xb4), t, "TestEncodeString") 692 | check(e.Encode("𐅑")) 693 | expect(buf.Bytes()[4], byte(0x64), t, "TestEncodeString") 694 | expect(buf.Bytes()[5], byte(0xf0), t, "TestEncodeString") 695 | expect(buf.Bytes()[6], byte(0x90), t, "TestEncodeString") 696 | expect(buf.Bytes()[7], byte(0x85), t, "TestEncodeString") 697 | expect(buf.Bytes()[8], byte(0x91), t, "TestEncodeString") 698 | } 699 | 700 | func TestEncodePointerToString(t *testing.T) { 701 | buf := bytes.NewBuffer(nil) 702 | e := NewEncoder(buf) 703 | var v string = "水" 704 | check(e.Encode(&v)) 705 | expect(buf.Bytes()[0], byte(0x63), t, "TestEncodePointerToString") 706 | expect(buf.Bytes()[1], byte(0xe6), t, "TestEncodePointerToString") 707 | expect(buf.Bytes()[2], byte(0xb0), t, "TestEncodePointerToString") 708 | expect(buf.Bytes()[3], byte(0xb4), t, "TestEncodePointerToString") 709 | v = "𐅑" 710 | check(e.Encode(&v)) 711 | expect(buf.Bytes()[4], byte(0x64), t, "TestEncodePointerToString") 712 | expect(buf.Bytes()[5], byte(0xf0), t, "TestEncodePointerToString") 713 | expect(buf.Bytes()[6], byte(0x90), t, "TestEncodePointerToString") 714 | expect(buf.Bytes()[7], byte(0x85), t, "TestEncodePointerToString") 715 | expect(buf.Bytes()[8], byte(0x91), t, "TestEncodePointerToString") 716 | } 717 | 718 | func TestEncodeNilPointer(t *testing.T) { 719 | buf := bytes.NewBuffer(nil) 720 | e := NewEncoder(buf) 721 | var v *int32 = nil 722 | check(e.Encode(v)) 723 | expect(buf.Bytes()[0], absoluteNil, t, "TestEncodeNil") 724 | type MyType struct{ a int32 } 725 | var m *MyType 726 | check(e.Encode(m)) 727 | expect(buf.Bytes()[1], absoluteNil, t, "TestEncodeNil") 728 | } 729 | 730 | func TestEncodeBoolInterface(t *testing.T) { 731 | buf := bytes.NewBuffer(nil) 732 | e := NewEncoder(buf) 733 | var v interface{} = false 734 | check(e.Encode(v)) 735 | expect(buf.Bytes()[0], absoluteFalse, t, "TestEncodeBoolInterface") 736 | v = true 737 | check(e.Encode(v)) 738 | expect(buf.Bytes()[1], absoluteTrue, t, "TestEncodeBoolInterface") 739 | } 740 | 741 | func TestEncodeUintInterface(t *testing.T) { 742 | buf := bytes.NewBuffer(nil) 743 | e := NewEncoder(buf) 744 | var v interface{} = uint8(10) 745 | check(e.Encode(v)) 746 | expect(buf.Bytes()[0], byte(0x0a), t, "TestEncodeUintInterface") 747 | v = uint16(1000) 748 | check(e.Encode(v)) 749 | expect(buf.Bytes()[1], byte(0x19), t, "TestEncodeUintInterface") 750 | expect(buf.Bytes()[2], byte(0x03), t, "TestEncodeUintInterface") 751 | expect(buf.Bytes()[3], byte(0xe8), t, "TestEncodeUintInterface") 752 | v = uint32(1000000) 753 | check(e.Encode(v)) 754 | expect(buf.Bytes()[4], byte(0x1a), t, "TestEncodeUintInterface") 755 | expect(buf.Bytes()[5], byte(0x00), t, "TestEncodeUintInterface") 756 | expect(buf.Bytes()[6], byte(0x0f), t, "TestEncodeUintInterface") 757 | expect(buf.Bytes()[7], byte(0x42), t, "TestEncodeUintInterface") 758 | expect(buf.Bytes()[8], byte(0x40), t, "TestEncodeUintInterface") 759 | v = uint64(18446744073709551615) 760 | check(e.Encode(v)) 761 | expect(buf.Bytes()[9], byte(0x1b), t, "TestEncodeUintInterface") 762 | expect(buf.Bytes()[10], byte(0xff), t, "TestEncodeUintInterface") 763 | expect(buf.Bytes()[11], byte(0xff), t, "TestEncodeUintInterface") 764 | expect(buf.Bytes()[12], byte(0xff), t, "TestEncodeUintInterface") 765 | expect(buf.Bytes()[13], byte(0xff), t, "TestEncodeUintInterface") 766 | expect(buf.Bytes()[14], byte(0xff), t, "TestEncodeUintInterface") 767 | expect(buf.Bytes()[15], byte(0xff), t, "TestEncodeUintInterface") 768 | expect(buf.Bytes()[16], byte(0xff), t, "TestEncodeUintInterface") 769 | expect(buf.Bytes()[17], byte(0xff), t, "TestEncodeUintInterface") 770 | } 771 | 772 | func TestEncodeIntInterface(t *testing.T) { 773 | buf := bytes.NewBuffer(nil) 774 | e := NewEncoder(buf) 775 | var v interface{} = int8(-10) 776 | check(e.Encode(v)) 777 | expect(buf.Bytes()[0], byte(0x29), t, "TestEncodeIntInterface") 778 | v = int16(-1000) 779 | check(e.Encode(v)) 780 | expect(buf.Bytes()[1], byte(0x39), t, "TestEncodeIntInterface") 781 | expect(buf.Bytes()[2], byte(0x03), t, "TestEncodeIntInterface") 782 | expect(buf.Bytes()[3], byte(0xe7), t, "TestEncodeIntInterface") 783 | v = int32(-1000000) 784 | check(e.Encode(v)) 785 | expect(buf.Bytes()[4], byte(0x3a), t, "TestEncodeIntInterface") 786 | expect(buf.Bytes()[5], byte(0x00), t, "TestEncodeIntInterface") 787 | expect(buf.Bytes()[6], byte(0x0f), t, "TestEncodeIntInterface") 788 | expect(buf.Bytes()[7], byte(0x42), t, "TestEncodeIntInterface") 789 | expect(buf.Bytes()[8], byte(0x3f), t, "TestEncodeIntInterface") 790 | v = int64(-18446744073709551) 791 | check(e.Encode(v)) 792 | expect(buf.Bytes()[9], byte(0x3b), t, "TestEncodeIntInterface") 793 | expect(buf.Bytes()[10], byte(0x00), t, "TestEncodeIntInterface") 794 | expect(buf.Bytes()[11], byte(0x41), t, "TestEncodeIntInterface") 795 | expect(buf.Bytes()[12], byte(0x89), t, "TestEncodeIntInterface") 796 | expect(buf.Bytes()[13], byte(0x37), t, "TestEncodeIntInterface") 797 | expect(buf.Bytes()[14], byte(0x4b), t, "TestEncodeIntInterface") 798 | expect(buf.Bytes()[15], byte(0xc6), t, "TestEncodeIntInterface") 799 | expect(buf.Bytes()[16], byte(0xa7), t, "TestEncodeIntInterface") 800 | expect(buf.Bytes()[17], byte(0xee), t, "TestEncodeIntInterface") 801 | } 802 | 803 | func TestEncodeFloat32Interface(t *testing.T) { 804 | buf := bytes.NewBuffer(nil) 805 | e := NewEncoder(buf) 806 | var v interface{} = float32(3.4028234663852886e+38) 807 | check(e.Encode(v)) 808 | expect(buf.Bytes()[0], byte(0xfa), t, "TestEncodeFloat32Interface") 809 | expect(buf.Bytes()[1], byte(0x7f), t, "TestEncodeFloat32Interface") 810 | expect(buf.Bytes()[2], byte(0x7f), t, "TestEncodeFloat32Interface") 811 | expect(buf.Bytes()[3], byte(0xff), t, "TestEncodeFloat32Interface") 812 | expect(buf.Bytes()[4], byte(0xff), t, "TestEncodeFloat32Interface") 813 | } 814 | 815 | func TestEncodeFloat64Interface(t *testing.T) { 816 | buf := bytes.NewBuffer(nil) 817 | e := NewEncoder(buf) 818 | var v interface{} = float64(1.0e+300) 819 | check(e.Encode(v)) 820 | expect(buf.Bytes()[0], byte(0xfb), t, "TestEncodeFloat64Interface") 821 | expect(buf.Bytes()[1], byte(0x7e), t, "TestEncodeFloat64Interface") 822 | expect(buf.Bytes()[2], byte(0x37), t, "TestEncodeFloat64Interface") 823 | expect(buf.Bytes()[3], byte(0xe4), t, "TestEncodeFloat64Interface") 824 | expect(buf.Bytes()[4], byte(0x3c), t, "TestEncodeFloat64Interface") 825 | expect(buf.Bytes()[5], byte(0x88), t, "TestEncodeFloat64Interface") 826 | expect(buf.Bytes()[6], byte(0x00), t, "TestEncodeFloat64Interface") 827 | expect(buf.Bytes()[7], byte(0x75), t, "TestEncodeFloat64Interface") 828 | expect(buf.Bytes()[8], byte(0x9c), t, "TestEncodeFloat64Interface") 829 | } 830 | 831 | func TestEncodeSlice(t *testing.T) { 832 | buf := bytes.NewBuffer(nil) 833 | e := NewEncoder(buf) 834 | check(e.Encode([]int32{-10, 1000, 10, -1000})) 835 | expect(buf.Bytes()[0], byte(0x84), t, "TestEncodeSlice") 836 | expect(buf.Bytes()[1], byte(0x29), t, "TestEncodeSlice") 837 | expect(buf.Bytes()[2], byte(0x19), t, "TestEncodeSlice") 838 | expect(buf.Bytes()[3], byte(0x03), t, "TestEncodeSlice") 839 | expect(buf.Bytes()[4], byte(0xe8), t, "TestEncodeSlice") 840 | expect(buf.Bytes()[5], byte(0x0a), t, "TestEncodeSlice") 841 | expect(buf.Bytes()[6], byte(0x39), t, "TestEncodeSlice") 842 | expect(buf.Bytes()[7], byte(0x03), t, "TestEncodeSlice") 843 | expect(buf.Bytes()[8], byte(0xe7), t, "TestEncodeSlice") 844 | } 845 | 846 | func TestEncodePointerToSlice(t *testing.T) { 847 | buf := bytes.NewBuffer(nil) 848 | e := NewEncoder(buf) 849 | v := []int32{-10, 1000, 10, -1000} 850 | check(e.Encode(&v)) 851 | expect(buf.Bytes()[0], byte(0x84), t, "TestEncodePointerToSlice") 852 | expect(buf.Bytes()[1], byte(0x29), t, "TestEncodePointerToSlice") 853 | expect(buf.Bytes()[2], byte(0x19), t, "TestEncodePointerToSlice") 854 | expect(buf.Bytes()[3], byte(0x03), t, "TestEncodePointerToSlice") 855 | expect(buf.Bytes()[4], byte(0xe8), t, "TestEncodePointerToSlice") 856 | expect(buf.Bytes()[5], byte(0x0a), t, "TestEncodePointerToSlice") 857 | expect(buf.Bytes()[6], byte(0x39), t, "TestEncodePointerToSlice") 858 | expect(buf.Bytes()[7], byte(0x03), t, "TestEncodePointerToSlice") 859 | expect(buf.Bytes()[8], byte(0xe7), t, "TestEncodePointerToSlice") 860 | } 861 | 862 | func TestEncodeSliceOfSlicesOfBools(t *testing.T) { 863 | buf := bytes.NewBuffer(nil) 864 | e := NewEncoder(buf) 865 | v := [][]bool{ 866 | []bool{true, false, false, false}, 867 | []bool{}, 868 | []bool{false, true}, 869 | } 870 | check(e.Encode(v)) 871 | expect(buf.Bytes()[0], byte(0x83), t, "TestEncodeSliceOfSliceOfBools") 872 | expect(buf.Bytes()[1], byte(0x84), t, "TestEncodeSliceOfSliceOfBools") 873 | expect(buf.Bytes()[2], absoluteTrue, t, "TestEncodeSliceOfSliceOfBools") 874 | expect(buf.Bytes()[3], absoluteFalse, t, "TestEncodeSliceOfSliceOfBools") 875 | expect(buf.Bytes()[4], absoluteFalse, t, "TestEncodeSliceOfSliceOfBools") 876 | expect(buf.Bytes()[5], absoluteFalse, t, "TestEncodeSliceOfSliceOfBools") 877 | expect(buf.Bytes()[6], byte(0x80), t, "TestEncodeSliceOfSliceOfBools") 878 | expect(buf.Bytes()[7], byte(0x82), t, "TestEncodeSliceOfSliceOfBools") 879 | expect(buf.Bytes()[8], absoluteFalse, t, "TestEncodeSliceOfSliceOfBools") 880 | expect(buf.Bytes()[9], absoluteTrue, t, "TestEncodeSliceOfSliceOfBools") 881 | } 882 | 883 | func TestEncodeMapOfStringInt(t *testing.T) { 884 | buf := bytes.NewBuffer(nil) 885 | e := NewEncoder(buf) 886 | v := map[string]int{"One": 1} 887 | check(e.Encode(v)) 888 | expect(buf.Bytes()[0], byte(0xa1), t, "TestEncodeMapOfStringInt") 889 | expect(buf.Bytes()[1], byte(0x63), t, "TestEncodeMapOfStringInt") 890 | expect(buf.Bytes()[2], byte(0x4f), t, "TestEncodeMapOfStringInt") 891 | expect(buf.Bytes()[3], byte(0x6e), t, "TestEncodeMapOfStringInt") 892 | expect(buf.Bytes()[4], byte(0x65), t, "TestEncodeMapOfStringInt") 893 | expect(buf.Bytes()[5], byte(0x01), t, "TestEncodeMapOfStringInt") 894 | } 895 | 896 | func TestEncodeStruct(t *testing.T) { 897 | buf := bytes.NewBuffer(nil) 898 | e := NewEncoder(buf) 899 | type MyType struct { 900 | polla int 901 | Name string 902 | Age uint8 903 | Address1 []byte 904 | Address2 []byte 905 | Married bool 906 | Height float64 907 | } 908 | v := MyType{ 909 | Name: "Test Person", 910 | Age: 34, 911 | Address1: []byte("4 CBOR St"), 912 | Married: false, 913 | Height: 1.77, 914 | } 915 | check(e.Encode(v)) 916 | fmt.Printf("%#v\n", buf.Bytes()) 917 | expect(buf.Bytes()[0], byte(0xa6), t, "TestEncodeStruct") 918 | expect(buf.Bytes()[1], byte(0x64), t, "TestEncodeStruct") 919 | name := []byte{0x4e, 0x61, 0x6d, 0x65} 920 | for i := 0; i < len(name); i++ { 921 | expect(buf.Bytes()[i+2], name[i], t, "TestEncodeStruct") 922 | } 923 | expect(buf.Bytes()[6], byte(0x6b), t, "TestEncodeStruct") 924 | test_person := []byte{0x54, 0x65, 0x73, 0x74, 0x20, 0x50, 0x65, 0x72, 0x73, 0x6f, 0x6e} 925 | for i := 0; i < len(test_person); i++ { 926 | expect(buf.Bytes()[i+7], test_person[i], t, "TestEncodeStruct") 927 | } 928 | // age := []byte{0x41, 0x67, 0x65} 929 | } 930 | 931 | // benchmarks 932 | func BenchmarkEncodeBool(b *testing.B) { 933 | buf := bytes.NewBuffer(nil) 934 | e := NewEncoder(buf) 935 | for i := 0; i < b.N; i++ { 936 | e.Encode(false) 937 | } 938 | } 939 | 940 | func BenchmarkEncodeUint(b *testing.B) { 941 | buf := bytes.NewBuffer(nil) 942 | e := NewEncoder(buf) 943 | for i := 0; i < b.N; i++ { 944 | e.Encode(uint64(6500000000)) 945 | } 946 | } 947 | 948 | func BenchmarkEncodeInt(b *testing.B) { 949 | buf := bytes.NewBuffer(nil) 950 | e := NewEncoder(buf) 951 | v := int32(-650000) 952 | for i := 0; i < b.N; i++ { 953 | e.Encode(&v) 954 | } 955 | } 956 | 957 | func BenchmarkEncodeFloat16(b *testing.B) { 958 | buf := bytes.NewBuffer(nil) 959 | e := NewEncoder(buf) 960 | 961 | for i := 0; i < b.N; i++ { 962 | e.Encode(float16(1.5)) 963 | } 964 | } 965 | 966 | func BenchmarkEncodeFloat32(b *testing.B) { 967 | buf := bytes.NewBuffer(nil) 968 | e := NewEncoder(buf) 969 | 970 | for i := 0; i < b.N; i++ { 971 | e.Encode(float32(100000.0)) 972 | } 973 | } 974 | 975 | func BenchmarkEncodeFloat64(b *testing.B) { 976 | buf := bytes.NewBuffer(nil) 977 | e := NewEncoder(buf) 978 | 979 | for i := 0; i < b.N; i++ { 980 | check(e.Encode(float64(1.0e+300))) 981 | } 982 | } 983 | 984 | func BenchmarkEncodeBytes(b *testing.B) { 985 | buf := bytes.NewBuffer(nil) 986 | e := NewEncoder(buf) 987 | 988 | for i := 0; i < b.N; i++ { 989 | e.Encode([]byte("byte string")) 990 | } 991 | } 992 | 993 | func BenchmarkEncodePositiveBigNum(b *testing.B) { 994 | bn := new(big.Int) 995 | bn.SetString("18446744073709551616", 10) 996 | buf := bytes.NewBuffer(nil) 997 | e := NewEncoder(buf) 998 | 999 | for i := 0; i < b.N; i++ { 1000 | e.Encode(*bn) 1001 | } 1002 | } 1003 | 1004 | func BenchmarkEncodeNegativeBigNum(b *testing.B) { 1005 | bn := new(big.Int) 1006 | bn.SetString("-18446744073709551617", 10) 1007 | buf := bytes.NewBuffer(nil) 1008 | e := NewEncoder(buf) 1009 | 1010 | for i := 0; i < b.N; i++ { 1011 | e.Encode(*bn) 1012 | } 1013 | } 1014 | 1015 | func BenchmarkEncodeEpochDateTime(b *testing.B) { 1016 | buf := bytes.NewBuffer(nil) 1017 | e := NewEncoder(buf) 1018 | var v time.Time = time.Unix(1363896240, int64(0)) 1019 | 1020 | for i := 0; i < b.N; i++ { 1021 | e.Encode(v) 1022 | } 1023 | } 1024 | 1025 | func BenchmarkEncodeBigFloat(b *testing.B) { 1026 | buf := bytes.NewBuffer(nil) 1027 | e := NewEncoder(buf) 1028 | var v *big.Rat = big.NewRat(3, 2) 1029 | 1030 | for i := 0; i < b.N; i++ { 1031 | e.Encode(v) 1032 | } 1033 | } 1034 | 1035 | func BenchmarkEncodeString(b *testing.B) { 1036 | buf := bytes.NewBuffer(nil) 1037 | e := NewEncoder(buf) 1038 | for i := 0; i < b.N; i++ { 1039 | e.Encode("水") 1040 | } 1041 | } 1042 | 1043 | func BenchmarkEncodeBoolInterface(b *testing.B) { 1044 | buf := bytes.NewBuffer(nil) 1045 | e := NewEncoder(buf) 1046 | var v interface{} = false 1047 | for i := 0; i < b.N; i++ { 1048 | e.Encode(v) 1049 | } 1050 | } 1051 | 1052 | func becnhmarkInterfaceHelper(b *testing.B, v interface{}) { 1053 | buf := bytes.NewBuffer(nil) 1054 | e := NewEncoder(buf) 1055 | for i := 0; i < b.N; i++ { 1056 | e.Encode(v) 1057 | } 1058 | } 1059 | 1060 | func BenchmarkEncodeUintInterface(b *testing.B) { 1061 | var v interface{} = uint8(10) 1062 | becnhmarkInterfaceHelper(b, v) 1063 | } 1064 | 1065 | func BenchmarkEncodeIntInterface(b *testing.B) { 1066 | var v interface{} = int8(-10) 1067 | becnhmarkInterfaceHelper(b, v) 1068 | } 1069 | 1070 | func BenchmarkEncodeFloat32Interface(b *testing.B) { 1071 | var v interface{} = float32(3.4028234663852886e+38) 1072 | becnhmarkInterfaceHelper(b, v) 1073 | } 1074 | 1075 | func BenchmarkEncodeFloat64Interface(b *testing.B) { 1076 | var v interface{} = float64(1.0e+300) 1077 | becnhmarkInterfaceHelper(b, v) 1078 | } 1079 | 1080 | func BenchmarkEncodeSliceFourInts32(b *testing.B) { 1081 | buf := bytes.NewBuffer(nil) 1082 | e := NewEncoder(buf) 1083 | v := []int32{-10, 1000, 10, -1000} 1084 | for i := 0; i < b.N; i++ { 1085 | e.Encode(v) 1086 | } 1087 | } 1088 | 1089 | func BenchmarkEncodeSliceOfSlicesOfBools(b *testing.B) { 1090 | buf := bytes.NewBuffer(nil) 1091 | e := NewEncoder(buf) 1092 | v := [][]bool{ 1093 | []bool{true, false, false, false}, 1094 | []bool{}, 1095 | []bool{false, true}, 1096 | } 1097 | for i := 0; i < b.N; i++ { 1098 | e.Encode(v) 1099 | } 1100 | } 1101 | -------------------------------------------------------------------------------- /error.go: -------------------------------------------------------------------------------- 1 | // A Golang RFC7049 implementation 2 | // Copyright (C) 2015 Oscar Campos 3 | 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | 16 | package cbor 17 | 18 | import ( 19 | "fmt" 20 | "reflect" 21 | ) 22 | 23 | // An InvalidDecoderError describes an invalid argument passed to Decode 24 | // (The argument to Decode must be a non nil pointer) 25 | type InvalidDecodeError struct { 26 | Type reflect.Type 27 | } 28 | 29 | func (e *InvalidDecodeError) Error() string { 30 | if e.Type == nil { 31 | return "cbor: Decocde(nil)" 32 | } 33 | if e.Type.Kind() != reflect.Ptr { 34 | return fmt.Sprintf("cbor: Decode(non-pointer %s\n", e.Type) 35 | } 36 | return fmt.Sprintf("cbor: Decode(nil %s)\n", e.Type) 37 | } 38 | 39 | // An StrictModeError describes an invalid operation that violates 40 | // the section 3.10. Strict Mode definition of the RFC7049 41 | type StrictModeError struct { 42 | Msg string 43 | } 44 | 45 | func NewStrictModeError(msg string) *StrictModeError { 46 | return &StrictModeError{Msg: fmt.Sprintf("strict-mode: %s", msg)} 47 | } 48 | 49 | func (e *StrictModeError) Error() string { 50 | return e.Msg 51 | } 52 | 53 | // A CanonicalModeError describes an invalid operation that violates 54 | // the section 3.9. Canonical CBOR definition of the RFC7049 55 | type CanonicalModeError struct { 56 | Msg string 57 | } 58 | 59 | func NewCanonicalModeError(msg string) *CanonicalModeError { 60 | return &CanonicalModeError{Msg: fmt.Sprintf("canonical-mode: %s", msg)} 61 | } 62 | 63 | func (e *CanonicalModeError) Error() string { 64 | return e.Msg 65 | } 66 | -------------------------------------------------------------------------------- /kind_decoder.go: -------------------------------------------------------------------------------- 1 | // A Golang RFC7049 implementation 2 | // Copyright (C) 2015 Oscar Campos 3 | 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | 16 | package cbor 17 | 18 | import ( 19 | "errors" 20 | "fmt" 21 | "io" 22 | "log" 23 | "reflect" 24 | "strings" 25 | ) 26 | 27 | // magic error to force the decoder to continue in non strict mode 28 | var forceContinueError = errors.New("") 29 | 30 | const ( 31 | d_NOP uint = iota 32 | d_BREAK 33 | d_CONTINUE 34 | ) 35 | 36 | func (dec *Decoder) decodekInt(rv reflect.Value) error { 37 | rv.SetInt(^int64(dec.parser.buflen())) 38 | return nil 39 | } 40 | 41 | func (dec *Decoder) decodekUint(rv reflect.Value) error { 42 | rv.SetUint(dec.parser.buflen()) 43 | return nil 44 | } 45 | 46 | func (dec *Decoder) decodekInt8(rv reflect.Value) error { 47 | rv.SetInt(int64(dec.decodeInt8())) 48 | return nil 49 | } 50 | 51 | func (dec *Decoder) decodekUint8(rv reflect.Value) error { 52 | rv.SetUint(uint64(dec.decodeUint8())) 53 | return nil 54 | } 55 | 56 | func (dec *Decoder) decodekInt16(rv reflect.Value) error { 57 | rv.SetInt(int64(dec.decodeInt16())) 58 | return nil 59 | } 60 | 61 | func (dec *Decoder) decodekUint16(rv reflect.Value) error { 62 | rv.SetUint(uint64(dec.decodeUint16())) 63 | return nil 64 | } 65 | 66 | func (dec *Decoder) decodekInt32(rv reflect.Value) error { 67 | rv.SetInt(int64(dec.decodeInt32())) 68 | return nil 69 | } 70 | 71 | func (dec *Decoder) decodekUint32(rv reflect.Value) error { 72 | rv.SetUint(uint64(dec.decodeUint32())) 73 | return nil 74 | } 75 | 76 | func (dec *Decoder) decodekInt64(rv reflect.Value) error { 77 | rv.SetInt(int64(dec.decodeInt64())) 78 | return nil 79 | } 80 | 81 | func (dec *Decoder) decodekUint64(rv reflect.Value) error { 82 | rv.SetUint(uint64(dec.decodeUint64())) 83 | return nil 84 | } 85 | 86 | func (dec *Decoder) decodekFloat32(rv reflect.Value) error { 87 | rv.SetFloat(float64(dec.decodeFloat32())) 88 | return nil 89 | } 90 | 91 | func (dec *Decoder) decodekFloat64(rv reflect.Value) error { 92 | rv.SetFloat(dec.decodeFloat64()) 93 | return nil 94 | } 95 | 96 | func (dec *Decoder) decodekString(rv reflect.Value) error { 97 | rv.SetString(dec.decodeString()) 98 | return nil 99 | } 100 | 101 | func (dec *Decoder) decodekBool(rv reflect.Value) error { 102 | rv.SetBool(dec.decodeBool()) 103 | return nil 104 | } 105 | 106 | func (dec *Decoder) decodekInterface(rv reflect.Value) error { 107 | if !rv.IsNil() { 108 | return dec.decode(rv.Elem()) 109 | } 110 | 111 | // blind decoding 112 | v, vk, err := dec.blind() 113 | if err != nil { 114 | return err 115 | } 116 | decodeFurther := false 117 | if v == nil { 118 | decodeFurther = true 119 | } 120 | 121 | // check for nil and undef values 122 | if vk == reflect.Invalid { 123 | return nil 124 | } 125 | 126 | // process the data 127 | switch vk { 128 | case reflect.Slice: 129 | v = new([]interface{}) 130 | case reflect.Map: 131 | v = new(map[interface{}]interface{}) 132 | } 133 | 134 | if decodeFurther { 135 | if v != nil { 136 | dec.decode(reflect.ValueOf(v).Elem()) 137 | } 138 | } 139 | if v != nil { 140 | rv.Set(reflect.ValueOf(v)) 141 | } 142 | return nil 143 | } 144 | 145 | // Decoce into a slice 146 | func (dec *Decoder) decodekSlice(rv reflect.Value) error { 147 | _, info := dec.parser.parseHeader() 148 | rvt := rv.Type() 149 | if info != cborIndefinite { 150 | length := int(dec.parser.buflen()) 151 | if rv.IsNil() { 152 | rv.Set(reflect.MakeSlice(rvt, length, length)) 153 | } 154 | for i := 0; i < length; i++ { 155 | if _, _, err := dec.parser.parseInformation(); err != nil { 156 | return err 157 | } 158 | if err := dec.decode(rv.Index(i)); err != nil { 159 | return err 160 | } 161 | } 162 | } else { 163 | rvti := rvt.Elem() // elements type for the slice 164 | rv.Set(reflect.MakeSlice(rvt, 0, 0)) 165 | for i := 0; ; i++ { 166 | if _, _, err := dec.parser.parseInformation(); err != nil { 167 | return err 168 | } 169 | if dec.parser.isBreak() { 170 | break 171 | } 172 | rv.Set(reflect.Append(rv, reflect.Zero(rvti))) 173 | if err := dec.decode(rv.Index(i)); err != nil { 174 | return err 175 | } 176 | } 177 | } 178 | return nil 179 | } 180 | 181 | func (dec *Decoder) decodekArray(rv reflect.Value) error { 182 | return dec.decodekSlice(rv.Slice(0, rv.Len())) 183 | } 184 | 185 | // Decode into a map, if the strict mode is not enforced and 186 | // there is a duplicated key in the map, the behavior is 187 | // undefined, if the values are all of the same type then the 188 | // key should be probably overwritten, if the values are empty 189 | // interfaces, then probably the first value assigned to the 190 | // key will be stuck but there is nothing that guarantee this 191 | // 192 | // For more information about the strict mode take a look at 193 | // the RFC7049 in the secton 3.10. Strict Mode 194 | func (dec *Decoder) decodekMap(rv reflect.Value) error { 195 | rvt := rv.Type() 196 | if rv.IsNil() { 197 | rv.Set(reflect.MakeMap(rvt)) 198 | } 199 | keytype := rvt.Key() 200 | valtype := rvt.Elem() 201 | 202 | _, info := dec.parser.parseHeader() 203 | if info != cborIndefinite { 204 | lenght := int(dec.parser.buflen()) 205 | for i := 0; i < lenght; i++ { 206 | if err := dec.generateKeyValue(keytype, valtype, rv); err != nil { 207 | return err 208 | } 209 | } 210 | } else { 211 | for { 212 | if err := dec.generateKeyValue(keytype, valtype, rv); err != nil { 213 | if err != io.EOF { 214 | return err 215 | } 216 | if dec.parser.isBreak() { // check again to make sure we are all right 217 | break 218 | } 219 | return err 220 | } 221 | } 222 | } 223 | return nil 224 | } 225 | 226 | // Decode into an struct 227 | // 228 | // CBOR arrays and maps can be decoded into structs using a 229 | // simple series of rules and conventions. If the strict mode 230 | // is not enforced and there is a duplicated key in the map 231 | // (or array) , the behavior is totally undefined 232 | // 233 | // If the underlying CBOR structure is an array the convention 234 | // is to use odds indexes as keys and even indexes as value as 235 | // it was a map 236 | // 237 | // So in the example below, the first value read from the CBOR 238 | // data will be mapped into the `Name` field, the second into 239 | // the Age field using their types. 240 | // 241 | // Tags can be used with maps as well in case that the keys 242 | // names doesn't match with out struct fields names, 243 | // type MyOtherType struct { 244 | // Name string `cbor:"name"` 245 | // Age uint8 `cbor:"how_old"` 246 | // } 247 | // 248 | // If the Strict Mode is used, will also fail if it receives a 249 | // key that doesn't match with any field of the struct or if 250 | // there are more indexes than fields in the struct 251 | // Note: that last behavior is not part of the RFC7049 252 | // 253 | // For more information about the strict mode take a look at 254 | // the RFC7049 in the secton 3.10. Strict Mode 255 | func (dec *Decoder) decodekStruct(rv reflect.Value) error { 256 | rv.Set(reflect.New(rv.Type()).Elem()) 257 | major, _ := dec.parser.parseHeader() 258 | length := 0 259 | numFields := rv.NumField() 260 | array := true 261 | if major == cborDataMap { 262 | array = false 263 | } 264 | err := dec.checkStructLength(numFields, &length, array) 265 | if err != nil { 266 | return err 267 | } 268 | return dec.decodeInner(rv, numFields, length, array) 269 | } 270 | 271 | func (dec *Decoder) decodeInner(rv reflect.Value, nf, length int, array bool) error { 272 | shownKeys := map[string]struct{}{} 273 | for i := 0; ; i++ { 274 | if length == 0 && !dec.parser.indefinite { 275 | break 276 | } 277 | op, err := dec.checkRtStructLength(i, nf) 278 | if err != nil { 279 | return err 280 | } 281 | if op == d_BREAK { 282 | break 283 | } else if op == d_CONTINUE { 284 | length-- 285 | continue 286 | } 287 | 288 | major, _, err := dec.parser.parseInformation() 289 | if err != nil { 290 | return err 291 | } 292 | if dec.parser.indefinite && dec.parser.isBreak() { 293 | break 294 | } 295 | 296 | // key must be a string 297 | if major < cborByteString || major > cborTextString { 298 | t := "map" 299 | if array { 300 | t = "array" 301 | } 302 | return fmt.Errorf("%s keys must be string, %s received", t, major) 303 | } 304 | key, err := dec.decodeStructFieldKey(shownKeys) 305 | if err != nil { 306 | return err 307 | } 308 | 309 | // let's decode the value and assign it to the struct field 310 | if err := dec.decodeStructFieldValue(rv, key, array); err != nil { 311 | if err == forceContinueError && !dec.strict { 312 | length-- 313 | continue 314 | } 315 | return err 316 | } 317 | length-- 318 | } 319 | return nil 320 | } 321 | 322 | // helper function to generate a pair key, value to decode into maps 323 | func (dec *Decoder) generateKeyValue(ktype, vtype reflect.Type, rv reflect.Value) error { 324 | if _, _, err := dec.parser.parseInformation(); err != nil { 325 | return err 326 | } 327 | if dec.parser.isBreak() { 328 | return io.EOF 329 | } 330 | key := reflect.New(ktype).Elem() 331 | dec.decode(key) 332 | // check if the key exists when we are in strict mode 333 | if dec.strict { 334 | if rv.MapIndex(key).IsValid() { 335 | return NewStrictModeError(fmt.Sprintf("duplicated key %s in map", key)) 336 | } 337 | } 338 | if _, _, err := dec.parser.parseInformation(); err != nil { 339 | return err 340 | } 341 | val := rv.MapIndex(key) 342 | if !val.IsValid() { 343 | val = reflect.New(vtype).Elem() 344 | } 345 | dec.decode(val) 346 | rv.SetMapIndex(key, val) 347 | return nil 348 | } 349 | 350 | // helper function that iterates over the fields 351 | // of a struct looking for a specific tag 352 | func (dec *Decoder) lookupStructTag(st reflect.Value, tag string, array bool) string { 353 | for i := 0; i < st.NumField(); i++ { 354 | field := st.Type().Field(i) 355 | t := field.Tag.Get("cbor") 356 | if t != "" { 357 | if strings.Contains(t, tag) { 358 | return field.Name 359 | } 360 | } 361 | } 362 | return "" 363 | } 364 | 365 | // common length checks for struct decoders 366 | func (dec *Decoder) checkStructLength(nf int, length *int, array bool) error { 367 | if !dec.parser.indefinite { 368 | l := int(dec.parser.buflen()) 369 | nlen := l 370 | if array { 371 | nlen /= 2 372 | } 373 | if nlen != nf { 374 | if dec.strict { 375 | msg := fmt.Sprintf( 376 | "destination struct fields num %d doesn't match map length %d", 377 | nf, nlen, 378 | ) 379 | return NewStrictModeError(msg) 380 | } 381 | } 382 | *length = nlen 383 | } 384 | return nil 385 | } 386 | 387 | // common length in runtime check for struct decoders 388 | func (dec *Decoder) checkRtStructLength(i, nf int) (uint, error) { 389 | if i > nf { 390 | // if strict mode is on, check for the right number of fields 391 | msg := fmt.Sprintf( 392 | "destination struct fields num %d doesn't match map length %d", nf, i) 393 | if dec.strict { 394 | return d_NOP, NewStrictModeError(msg) 395 | } 396 | log.Printf("warning strict-mode: %s\n", msg) 397 | if dec.parser.indefinite && dec.parser.isBreak() { 398 | return d_BREAK, nil 399 | } 400 | if _, _, err := dec.parser.parseInformation(); err != nil { 401 | return d_NOP, err 402 | } 403 | return d_CONTINUE, nil 404 | } 405 | return d_NOP, nil 406 | } 407 | 408 | // decodes a key to be used as a struct field in struct decoders 409 | func (dec *Decoder) decodeStructFieldKey(shownKeys map[string]struct{}) (string, error) { 410 | key := dec.decodeString() 411 | if dec.strict { 412 | if _, ok := shownKeys[key]; ok { 413 | return "", NewStrictModeError( 414 | fmt.Sprintf("duplicated key %s in map", key)) 415 | } 416 | shownKeys[key] = struct{}{} 417 | } 418 | return key, nil 419 | } 420 | 421 | // decode a value to be used as a struct field value in struct decoders 422 | func (dec *Decoder) decodeStructFieldValue(rv reflect.Value, key string, array bool) error { 423 | var field reflect.Value 424 | if field = rv.FieldByName(key); !field.IsValid() { 425 | if field = rv.FieldByName(dec.lookupStructTag(rv, key, array)); !field.IsValid() { 426 | msg := fmt.Sprintf("key %s doesn't match with any field", key) 427 | if dec.strict { 428 | return NewStrictModeError(msg) 429 | } 430 | log.Printf("warning strict-mode: %s skipping...\n", msg) 431 | if _, _, err := dec.parser.parseInformation(); err != nil { 432 | return err 433 | } 434 | return forceContinueError 435 | } 436 | } 437 | if _, _, err := dec.parser.parseInformation(); err != nil { 438 | return err 439 | } 440 | err := dec.decode(field) 441 | return err 442 | } 443 | -------------------------------------------------------------------------------- /major_string.go: -------------------------------------------------------------------------------- 1 | // generated by stringer -type=Major; DO NOT EDIT 2 | 3 | package cbor 4 | 5 | import "fmt" 6 | 7 | const _Major_name = "cborUnsignedIntcborNegativeIntcborByteStringcborTextStringcborDataArraycborDataMapcborTagcborNC" 8 | 9 | var _Major_index = [...]uint8{0, 15, 30, 44, 58, 71, 82, 89, 95} 10 | 11 | func (i Major) String() string { 12 | if i+1 >= Major(len(_Major_index)) { 13 | return fmt.Sprintf("Major(%d)", i) 14 | } 15 | return _Major_name[_Major_index[i]:_Major_index[i+1]] 16 | } 17 | -------------------------------------------------------------------------------- /maps.go: -------------------------------------------------------------------------------- 1 | // A Golang RFC7049 implementation 2 | // Copyright (C) 2015 Oscar Campos 3 | 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | 16 | package cbor 17 | 18 | import "reflect" 19 | 20 | // type map 21 | type typeMap map[Major]map[byte]reflect.Type 22 | 23 | var expectedTypesMap typeMap = typeMap{ 24 | cborUnsignedInt: map[byte]reflect.Type{ 25 | cborUint8: reflect.TypeOf(uint8(0)), 26 | cborUint16: reflect.TypeOf(uint16(0)), 27 | cborUint32: reflect.TypeOf(uint32(0)), 28 | cborUint64: reflect.TypeOf(uint64(0)), 29 | }, 30 | cborNegativeInt: map[byte]reflect.Type{ 31 | cborUint8: reflect.TypeOf(int8(0)), 32 | cborUint16: reflect.TypeOf(int16(0)), 33 | cborUint32: reflect.TypeOf(int32(0)), 34 | cborUint64: reflect.TypeOf(int64(0)), 35 | }, 36 | cborByteString: map[byte]reflect.Type{ 37 | cborUint8: reflect.TypeOf([]byte{}), 38 | cborUint16: reflect.TypeOf([]byte{}), 39 | cborUint32: reflect.TypeOf([]byte{}), 40 | cborUint64: reflect.TypeOf([]byte{}), 41 | }, 42 | cborTextString: map[byte]reflect.Type{ 43 | cborSmallInt: reflect.TypeOf(string("")), 44 | cborUint8: reflect.TypeOf(string("")), 45 | cborUint16: reflect.TypeOf(string("")), 46 | cborUint32: reflect.TypeOf(string("")), 47 | cborUint64: reflect.TypeOf(string("")), 48 | }, 49 | cborNC: map[byte]reflect.Type{ 50 | cborUint8: reflect.TypeOf(byte(0)), 51 | cborUint16: reflect.TypeOf(float16(0)), 52 | cborUint32: reflect.TypeOf(float32(0)), 53 | cborUint64: reflect.TypeOf(float64(0)), 54 | }, 55 | } 56 | -------------------------------------------------------------------------------- /parser.go: -------------------------------------------------------------------------------- 1 | // A Golang RFC7049 implementation 2 | // Copyright (C) 2015 Oscar Campos 3 | 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | 16 | package cbor 17 | 18 | import ( 19 | "encoding/binary" 20 | "fmt" 21 | "io" 22 | "math" 23 | ) 24 | 25 | // errors returned by the parser 26 | type ParserErr struct { 27 | Msg string 28 | } 29 | 30 | // implements the Error interface 31 | func (pe ParserErr) Error() string { 32 | return pe.Msg 33 | } 34 | 35 | // creates a new ParseErr component and return it back 36 | func NewParseErr(msg string) ParserErr { 37 | return ParserErr{msg} 38 | } 39 | 40 | // Parses a 'data item' and checks it's well-formedness 41 | // 42 | // It defines an internal buffer that is used to check 43 | // the well-formedness of the 'data item' and to store 44 | // data to be processed later 45 | type Parser struct { 46 | header byte 47 | r io.Reader 48 | indefinite bool 49 | buf []byte 50 | off int // the offset inside the buf 51 | } 52 | 53 | // Create a new Parser with the given 54 | // io.Reader and resturns back it's address 55 | func NewParser(r io.Reader) *Parser { 56 | return &Parser{r: r} 57 | } 58 | 59 | // Returns true if the header is the 60 | // break opcode, returns false otherwise 61 | func (p *Parser) isBreak() bool { 62 | return p.header == cborBreak 63 | } 64 | 65 | // Returns true if the header is the 66 | // nil opcode, returns false otherwise 67 | func (p *Parser) isNil() bool { 68 | return p.header == absoluteNil 69 | } 70 | 71 | // Returns true if the header is the 72 | // undef opcode, returns false otherwise 73 | func (p *Parser) isUndef() bool { 74 | return p.header == absoluteUndef 75 | } 76 | 77 | // Parses the information part of a 'data item' for any Major type 78 | // 79 | // It also populates the internal buffer if major is not Tag (6) and the 80 | // additional information is not an undefinite (streamed data) type (31) 81 | func (p *Parser) parseInformation() (major Major, info byte, err error) { 82 | p.header, err = p.scan1() 83 | if err != nil { 84 | return 0, 0, err 85 | } 86 | major, infotype := p.parseHeader() 87 | if infotype <= cborSmallInt { 88 | p.buf = []byte{infotype} 89 | return major, infotype, nil 90 | } 91 | if infotype == cborIndefinite { 92 | if major < cborByteString || major > cborDataMap && major != cborNC { 93 | return major, info, NewParseErr(fmt.Sprintf( 94 | "received additional info 31 (indefinite) for wrong major %d\n", major)) 95 | } 96 | p.indefinite = true 97 | return major, infotype, nil 98 | } 99 | if (infotype >= 28 && infotype <= 30) || infotype > 31 { 100 | return major, info, NewParseErr( 101 | fmt.Sprintf("invalid additional info %d", infotype)) 102 | } 103 | bytes := 1 << uint(3-(0x1b-uint(infotype))) 104 | _, p.buf, err = p.scan(bytes) 105 | return major, infotype, err 106 | } 107 | 108 | // Parses the header returning back major and additional information 109 | func (p *Parser) parseHeader() (Major, byte) { 110 | return Major(p.header >> 5), p.header & 0x1f 111 | } 112 | 113 | // returns back the lenght of the buffer 114 | func (p *Parser) buflen() uint64 { 115 | var v uint64 116 | info := p.header & 0x1f 117 | if info <= cborSmallInt { 118 | v = uint64(info) 119 | } else { 120 | switch len(p.buf) { 121 | case 1: 122 | v = uint64(p.parseUint8()) 123 | case 2: 124 | v = uint64(p.parseUint16()) 125 | case 4: 126 | v = uint64(p.parseUint32()) 127 | case 8: 128 | v = uint64(p.parseUint64()) 129 | } 130 | } 131 | return v 132 | } 133 | 134 | // Read N bytes from the internal buffer 135 | // If the buffer doesn't contains that many 136 | // bytes, the function just panic (as it had 137 | // to be checked already during the scanning) 138 | func (p *Parser) read(n int) []byte { 139 | a := (len(p.buf) - p.off) 140 | if n > a { 141 | panic(fmt.Sprintf( 142 | "can't read %d bytes from buffer as only %d are available\n", n, a)) 143 | } 144 | oldOff := p.off 145 | p.off += n 146 | return p.buf[oldOff:p.off] 147 | } 148 | 149 | // Reads N bytes from the parser io.Reader 150 | // 151 | // Returns the number of bytes readed or zero when errors and a bytes slice 152 | // containing the data that has been readed from the io.Reader 153 | func (p *Parser) scan(n int) (numbytes int, data []byte, err error) { 154 | if n <= 0 { 155 | return 156 | } 157 | data = make([]byte, n) 158 | if numbytes, err = p.r.Read(data); err != nil { 159 | return 0, nil, err 160 | } 161 | if numbytes < n { 162 | return 0, nil, NewParseErr(fmt.Sprintf( 163 | "can't scan %d bytes from buffer as only %d are available\n", n, numbytes)) 164 | } 165 | p.off = 0 166 | return numbytes, data, nil 167 | } 168 | 169 | // Reads a single byte from the parser io.Reader 170 | func (p *Parser) scan1() (byte, error) { 171 | _, tmpdata, err := p.scan(1) 172 | if err != nil { 173 | return 0, err 174 | } 175 | return tmpdata[0], nil 176 | } 177 | 178 | // Read a single byte from the internal 179 | // buffer and returns it back as an uint8 180 | func (p *Parser) parseUint8() uint8 { 181 | return uint8(p.read(1)[0]) 182 | } 183 | 184 | // Read two bytes from the internal 185 | // buffer and returns it back as uint16 186 | func (p *Parser) parseUint16() uint16 { 187 | return binary.BigEndian.Uint16(p.read(2)) 188 | } 189 | 190 | // Read four bytes from the internal 191 | // buffer and returns it back as uint32 192 | func (p *Parser) parseUint32() uint32 { 193 | return binary.BigEndian.Uint32(p.read(4)) 194 | } 195 | 196 | // Read eight bytes from the internal 197 | // buffer and returns it back as uint64 198 | func (p *Parser) parseUint64() uint64 { 199 | return binary.BigEndian.Uint64(p.read(8)) 200 | } 201 | 202 | // Read two bytes from the internal 203 | // buffer and returns it back as float16 204 | func (p *Parser) parseFloat16() float16 { 205 | return float16( 206 | math.Float32frombits(float16toUint32(binary.BigEndian.Uint16(p.read(2))))) 207 | } 208 | 209 | // Read four bytes from the internal 210 | // buffer and returns it back as float32 211 | func (p *Parser) parseFloat32() float32 { 212 | return math.Float32frombits(binary.BigEndian.Uint32(p.read(4))) 213 | } 214 | 215 | // Read eight bytes from the internal 216 | // buffer and returns it back as float64 217 | func (p *Parser) parseFloat64() float64 { 218 | return math.Float64frombits(binary.BigEndian.Uint64(p.read(8))) 219 | } 220 | 221 | // Read a boolean value from the internal buffer 222 | func (p *Parser) parseBool() bool { 223 | v := true 224 | if uint8(p.buflen()) == cborFalse { 225 | v = false 226 | } 227 | return v 228 | } 229 | -------------------------------------------------------------------------------- /parser_test.go: -------------------------------------------------------------------------------- 1 | // A Golang RFC7049 implementation 2 | // Copyright (C) 2015 Oscar Campos 3 | 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | 16 | package cbor 17 | 18 | import ( 19 | "bytes" 20 | "io" 21 | "testing" 22 | ) 23 | 24 | func TestScan(t *testing.T) { 25 | buf := []byte{'t', 'e', 's', 't'} 26 | r := bytes.NewBuffer(buf) 27 | 28 | p := NewParser(r) 29 | n, value, err := p.scan(1) 30 | check(err) 31 | expect(1, n, t) 32 | expect(byte('t'), value[0], t, "TestScan") 33 | 34 | r = bytes.NewBuffer(buf) 35 | p = NewParser(r) 36 | n, value, err = p.scan(3) 37 | check(err) 38 | expect(byte('t'), value[0], t, "TestScan") 39 | expect(byte('e'), value[1], t, "TestScan") 40 | expect(byte('s'), value[2], t, "TestScan") 41 | 42 | r = bytes.NewBuffer(buf) 43 | p = NewParser(r) 44 | n, value, err = p.scan(4) 45 | check(err) 46 | expect(string(buf), string(value), t, "TestScan") 47 | 48 | r = bytes.NewBuffer(buf) 49 | p = NewParser(r) 50 | n, _, err = p.scan(5) 51 | expect(err, NewParseErr("can't scan 5 bytes from buffer as only 4 are available\n"), t, "TestScan") 52 | } 53 | 54 | func TestScan1(t *testing.T) { 55 | buf := []byte{'t', 'e', 's', 't'} 56 | r := bytes.NewBuffer(buf) 57 | p := NewParser(r) 58 | 59 | value, err := p.scan1() 60 | check(err) 61 | expect(byte('t'), value, t, "TestScan1") 62 | value, err = p.scan1() 63 | check(err) 64 | expect(byte('e'), value, t, "TestScan1") 65 | value, err = p.scan1() 66 | check(err) 67 | expect(byte('s'), value, t, "TestScan1") 68 | value, err = p.scan1() 69 | check(err) 70 | expect(byte('t'), value, t, "TestScan1") 71 | 72 | // read beyond limits returns io.EOF 73 | _, err = p.scan1() 74 | expect(err, io.EOF, t, "TestScan1") 75 | } 76 | 77 | func TestParseUint8(t *testing.T) { 78 | buf := []byte{0x6f} 79 | p := new(Parser) 80 | p.buf = buf 81 | expect(uint8(111), p.parseUint8(), t, "TestParseUint8") 82 | } 83 | 84 | func TestParseUint16(t *testing.T) { 85 | buf := []byte{0x45, 0xab} 86 | p := new(Parser) 87 | p.buf = buf 88 | expect(uint16(17835), p.parseUint16(), t, "TestParseUint16") 89 | } 90 | 91 | func TestParseUint32(t *testing.T) { 92 | buf := []byte{0x8c, 0x7e, 0xe1, 0x38} 93 | p := new(Parser) 94 | p.buf = buf 95 | expect(uint32(2357125432), p.parseUint32(), t, "TestParseUint32") 96 | } 97 | 98 | func TestParseUint64(t *testing.T) { 99 | buf := []byte{0xb6, 0x70, 0x0f, 0xa8, 0xcd, 0x99, 0x87, 0x8d} 100 | p := new(Parser) 101 | p.buf = buf 102 | expect(uint64(13146024529972791181), p.parseUint64(), t, "TestParseUint64") 103 | } 104 | 105 | func TestParseBool(t *testing.T) { 106 | p := new(Parser) 107 | p.header = byte(0xf4) 108 | expect(false, p.parseBool(), t, "TestParseBool") 109 | } 110 | 111 | func TestParseInformation(t *testing.T) { 112 | buf := []byte{0x19, 0x10, 0x23} 113 | r := bytes.NewBuffer(buf) 114 | p := NewParser(r) 115 | _, info, err := p.parseInformation() 116 | check(err) 117 | expect(byte(cborUint16), info, t, "TestParseInformation") 118 | d := p.read(2) 119 | for i, b := range buf[1:] { 120 | expect(b, d[i], t, "TestParseInformation") 121 | } 122 | 123 | buf = []byte{0x1b, 0xb6, 0x70, 0x0f, 0xa8, 0xcd, 0x99, 0x87, 0x8d} 124 | r = bytes.NewBuffer(buf) 125 | p = NewParser(r) 126 | _, info, err = p.parseInformation() 127 | check(err) 128 | expect(byte(cborUint64), info, t, "TestParseInformation") 129 | d = p.read(8) 130 | for i, b := range buf[1:] { 131 | expect(b, d[i], t, "TestParseInformation") 132 | } 133 | 134 | buf = []byte{0x5f} 135 | r = bytes.NewBuffer(buf) 136 | p = NewParser(r) 137 | _, info, err = p.parseInformation() 138 | check(err) 139 | expect(byte(cborIndefinite), info, t, "TestParseInformation") 140 | 141 | buf = []byte{0x3f} 142 | r = bytes.NewBuffer(buf) 143 | p = NewParser(r) 144 | _, info, err = p.parseInformation() 145 | expect(err, NewParseErr("received additional info 31 (indefinite) for wrong major 1\n"), t, "TestParseInformation") 146 | } 147 | --------------------------------------------------------------------------------