├── LICENSE.txt ├── NOTICE.txt ├── README.md ├── codecconst.go ├── decoder.go ├── decoder_test.go ├── encoder.go ├── encoder_test.go ├── hessian_test.go └── serializer.go /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | -------------------------------------------------------------------------------- /NOTICE.txt: -------------------------------------------------------------------------------- 1 | Viant, inc. gohessian 2 | Copyright 2012-2016 Viant 3 | 4 | This product includes software developed at 5 | Viant (http://viantinc.com/) 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## gohessian 2 | 3 | This is a serializer that uses the Hessian protocol, implemented using the Go language. It was designed at [Viant Inc](http://viantinc.com/ "Viant Inc."). It can be used for many purposes, including with other open source projects, such as [CacheStore](https://github.com/viant/CacheStore "CacheStore"). Usage is fairly simple. 4 | 5 | ## Features: 6 | * Use of [Hessian](http://hessian.caucho.com/ "Hessian") Binary Web Service protocol 7 | * Uses the [Go](https://golang.org/ "Go") Language 8 | * Compatible with other projects 9 | 10 | ## Usage: 11 | * Ensure your Go environment is setup properly 12 | * Go can be downloaded [here](https://golang.org/dl/ "Go download") 13 | * Ensure your `GOPATH` environment variable is properly set. It may be set to colon-separated paths where Go code, packages, and executables may be found. 14 | * Ensure your 'GOROOT' environment variable is properly set. It may be set to the location of your Go installation. 15 | * For more details on how to install Go, click [here](https://golang.org/doc/install "Go installation instructions") 16 | * Install with `go get github.com/viant/gohessian` 17 | * All test files can be run with 'go test' 18 | * User guide is located here: http://viant.github.io/gohessian 19 | 20 | ## Latest Version 21 | The latest stable version is GoHessian 1.0.0. GoHessian Code Base: https://github.com/viant/gohessian 22 | 23 | ## Copyright and Licensing: 24 | The source code is available under the Apache 2.0 license. We are actively looking for contributors. If you have ideas, code, bug reports, or fixes that you would like to contribute, please do so. Pull requests will be handled by Mickey Hsieh. 25 | 26 | ## Credits and Acknowledgements 27 | 28 | [GoHessian Creator: Mickey Hsieh] 29 | 30 | [Technical Writer: Allen Wang supervised by Mike Yang] 31 | 32 | [Open-source Admin: Allen Wang supervised by Mike Yang] 33 | 34 | [GoHessian Website: Allen Wang supervised by the Viant Engineering Team ] 35 | 36 | For more, check out our [website](http://viant.github.io/ "Viant Engineering site")! 37 | -------------------------------------------------------------------------------- /codecconst.go: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright 2012-2016 Viant. 4 | * * 5 | * * Licensed under the Apache License, Version 2.0 (the "License"); you may not 6 | * * use this file except in compliance with the License. You may obtain a copy of 7 | * * the License at 8 | * * 9 | * * http://www.apache.org/licenses/LICENSE-2.0 10 | * * 11 | * * Unless required by applicable law or agreed to in writing, software 12 | * * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | * * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | * * License for the specific language governing permissions and limitations under 15 | * * the License. 16 | * 17 | */ 18 | 19 | package hessian 20 | 21 | const ( 22 | mask = byte(127) 23 | flag = byte(128) 24 | ) 25 | 26 | const ( 27 | TAG_READ = int32(-1) 28 | ASCII_GAP = 32 29 | CHUNK_SIZE = 4096 30 | BC_BINARY = byte('B') // final chunk 31 | BC_BINARY_CHUNK = byte('A') // non-final chunk 32 | 33 | BC_BINARY_DIRECT = byte(0x20) // 1-byte length binary 34 | BINARY_DIRECT_MAX = byte(0x0f) 35 | BC_BINARY_SHORT = byte(0x34) // 2-byte length binary 36 | BINARY_SHORT_MAX = 0x3ff // 0-1023 binary 37 | 38 | BC_DATE = byte(0x4a) // 64-bit millisecond UTC date 39 | BC_DATE_MINUTE = byte(0x4b) // 32-bit minute UTC date 40 | 41 | BC_DOUBLE = byte('D') // IEEE 64-bit double 42 | 43 | BC_DOUBLE_ZERO = byte(0x5b) 44 | BC_DOUBLE_ONE = byte(0x5c) 45 | BC_DOUBLE_BYTE = byte(0x5d) 46 | BC_DOUBLE_SHORT = byte(0x5e) 47 | BC_DOUBLE_MILL = byte(0x5f) 48 | 49 | BC_FALSE = byte('F') // boolean false 50 | 51 | BC_INT = byte('I') // 32-bit int 52 | 53 | INT_DIRECT_MIN = -0x10 54 | INT_DIRECT_MAX = byte(0x2f) 55 | BC_INT_ZERO = byte(0x90) 56 | 57 | INT_BYTE_MIN = -0x800 58 | INT_BYTE_MAX = 0x7ff 59 | BC_INT_BYTE_ZERO = byte(0xc8) 60 | 61 | BC_END = byte('Z') 62 | 63 | INT_SHORT_MIN = -0x40000 64 | INT_SHORT_MAX = 0x3ffff 65 | BC_INT_SHORT_ZERO = byte(0xd4) 66 | 67 | BC_LIST_VARIABLE = byte(0x55) 68 | BC_LIST_FIXED = byte('V') 69 | BC_LIST_VARIABLE_UNTYPED = byte(0x57) 70 | BC_LIST_FIXED_UNTYPED = byte(0x58) 71 | 72 | BC_LIST_DIRECT = byte(0x70) 73 | BC_LIST_DIRECT_UNTYPED = byte(0x78) 74 | LIST_DIRECT_MAX = byte(0x7) 75 | 76 | BC_LONG = byte('L') // 64-bit signed integer 77 | LONG_DIRECT_MIN = -0x08 78 | LONG_DIRECT_MAX = byte(0x0f) 79 | BC_LONG_ZERO = byte(0xe0) 80 | 81 | LONG_BYTE_MIN = -0x800 82 | LONG_BYTE_MAX = 0x7ff 83 | BC_LONG_BYTE_ZERO = byte(0xf8) 84 | 85 | LONG_SHORT_MIN = -0x40000 86 | LONG_SHORT_MAX = 0x3ffff 87 | BC_LONG_SHORT_ZERO = byte(0x3c) 88 | 89 | BC_LONG_INT = byte(0x59) 90 | 91 | BC_MAP = byte('M') 92 | BC_MAP_UNTYPED = byte('H') 93 | 94 | BC_NULL = byte('N') 95 | 96 | BC_OBJECT = byte('O') 97 | BC_OBJECT_DEF = byte('C') 98 | 99 | BC_OBJECT_DIRECT = byte(0x60) 100 | OBJECT_DIRECT_MAX = byte(0x0f) 101 | 102 | BC_REF = byte(0x51) 103 | 104 | BC_STRING = byte('S') // final string 105 | BC_STRING_CHUNK = byte('R') // non-final string 106 | 107 | BC_STRING_DIRECT = byte(0x00) 108 | STRING_DIRECT_MAX = byte(0x1f) 109 | BC_STRING_SHORT = byte(0x30) 110 | STRING_SHORT_MAX = 0x3ff 111 | 112 | BC_TRUE = byte('T') 113 | 114 | P_PACKET_CHUNK = byte(0x4f) 115 | P_PACKET = byte('P') 116 | 117 | P_PACKET_DIRECT = byte(0x80) 118 | PACKET_DIRECT_MAX = byte(0x7f) 119 | 120 | P_PACKET_SHORT = byte(0x70) 121 | PACKET_SHORT_MAX = 0xfff 122 | ARRAY_STRING = "[string" 123 | ARRAY_INT = "[int" 124 | ARRAY_DOUBLE = "[double" 125 | ARRAY_FLOAT = "[float" 126 | ARRAY_BOOL = "[boolean" 127 | ARRAY_LONG = "[long" 128 | ) 129 | -------------------------------------------------------------------------------- /decoder.go: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright 2012-2016 Viant. 4 | * * 5 | * * Licensed under the Apache License, Version 2.0 (the "License"); you may not 6 | * * use this file except in compliance with the License. You may obtain a copy of 7 | * * the License at 8 | * * 9 | * * http://www.apache.org/licenses/LICENSE-2.0 10 | * * 11 | * * Unless required by applicable law or agreed to in writing, software 12 | * * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | * * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | * * License for the specific language governing permissions and limitations under 15 | * * the License. 16 | * 17 | */ 18 | 19 | /* 20 | decoder implement hessian 2 protocol, It follows java hessian package standard. 21 | It assume that you using the java name convention 22 | baisca difference between java and go 23 | fully qualify java class name is composed of package + class name 24 | Go assume upper case of field name is exportable and java did not have that constrain 25 | but in general java using camo camlecase. So it did conversion of field name from 26 | the first letter of from upper to lower case 27 | typMap{string]reflect.Type contain full java package+class name and go relfect.Type 28 | must provide in order to correctly decode to galang interface 29 | 30 | 31 | */ 32 | package hessian 33 | 34 | import ( 35 | "bytes" 36 | "encoding/binary" 37 | "fmt" 38 | "io" 39 | "log" 40 | "math" 41 | "reflect" 42 | "strings" 43 | ) 44 | 45 | var _ = bytes.MinRead 46 | var _ = reflect.Value{} 47 | 48 | // ErrDecoder is returned when the encoder encounters an error. 49 | type ErrDecoder struct { 50 | Message string 51 | Err error 52 | } 53 | 54 | type ClassDef struct { 55 | FullClassName string 56 | FieldName []string 57 | } 58 | 59 | type decoder struct { 60 | reader io.Reader 61 | typMap map[string]reflect.Type 62 | typList []string 63 | refList []interface{} 64 | clsDefList []ClassDef 65 | } 66 | 67 | func NewDecoder(r io.Reader, typ map[string]reflect.Type) *decoder { 68 | if typ == nil { 69 | typ = make(map[string]reflect.Type, 17) 70 | } 71 | decode := &decoder{r, typ, make([]string, 0, 17), make([]interface{}, 0, 17), make([]ClassDef, 0, 17)} 72 | return decode 73 | } 74 | 75 | func (d *decoder) RegisterType(key string, value reflect.Type) { 76 | d.typMap[key] = value 77 | } 78 | 79 | func (d *decoder) RegisterTypeMap(mp map[string]reflect.Type) { 80 | d.typMap = mp 81 | } 82 | 83 | func (d *decoder) RegisterVal(key string, val interface{}) { 84 | d.typMap[key] = reflect.TypeOf(val) 85 | } 86 | 87 | func (d *decoder) Reset() { 88 | d.typMap = make(map[string]reflect.Type, 17) 89 | d.clsDefList = make([]ClassDef, 0, 17) 90 | d.refList = make([]interface{}, 17) 91 | } 92 | 93 | func (e ErrDecoder) Error() string { 94 | if e.Err == nil { 95 | return "cannot decode " + e.Message 96 | } 97 | return "cannot decode " + e.Message + ": " + e.Err.Error() 98 | } 99 | 100 | func newCodecError(dataType string, a ...interface{}) *ErrDecoder { 101 | var err error 102 | var format, message string 103 | var ok bool 104 | if len(a) == 0 { 105 | return &ErrDecoder{dataType + ": no reason given", nil} 106 | } 107 | // if last item is error: save it 108 | if err, ok = a[len(a)-1].(error); ok { 109 | a = a[:len(a)-1] // pop it 110 | } 111 | // if items left, first ought to be format string 112 | if len(a) > 0 { 113 | if format, ok = a[0].(string); ok { 114 | a = a[1:] // unshift 115 | message = fmt.Sprintf(format, a...) 116 | } 117 | } 118 | if message != "" { 119 | message = ": " + message 120 | } 121 | return &ErrDecoder{dataType + message, err} 122 | } 123 | 124 | func (d *decoder) readBufByte() (byte, error) { 125 | buf := make([]byte, 1) 126 | _, err := io.ReadFull(d.reader, buf) 127 | if err != nil { 128 | return 0, newCodecError("readBufByte", err) 129 | } 130 | return buf[0], nil 131 | } 132 | 133 | func (d *decoder) readBuf(s int) ([]byte, error) { 134 | buf := make([]byte, s) 135 | _, err := io.ReadFull(d.reader, buf) 136 | if err != nil { 137 | return nil, newCodecError("readBuf", err) 138 | } 139 | return buf, nil 140 | } 141 | 142 | //name is option, if it is nil, use type.Name() 143 | func (d *decoder) ReadObjectWithType(typ reflect.Type, name string) (interface{}, error) { 144 | //register the type if it did exist 145 | if _, ok := d.typMap[name]; ok { 146 | log.Println("over write existing type") 147 | } 148 | d.typMap[name] = typ 149 | return d.ReadObject() 150 | } 151 | 152 | func (d *decoder) readInt(flag int32) (interface{}, error) { 153 | var tag byte 154 | if flag != TAG_READ { 155 | tag = byte(flag) 156 | } else { 157 | tag, _ = d.readBufByte() 158 | } 159 | 160 | switch { 161 | //direct integer 162 | case tag >= 0x80 && tag <= 0xbf: 163 | return int32(tag - BC_INT_ZERO), nil 164 | case tag >= 0xc0 && tag <= 0xcf: 165 | bf := make([]byte, 1) 166 | if _, err := io.ReadFull(d.reader, bf); err != nil { 167 | return nil, newCodecError("short integer", err) 168 | } 169 | return int32(tag-BC_INT_BYTE_ZERO)<<8 + int32(bf[0]), nil 170 | case tag >= 0xd0 && tag <= 0xd7: 171 | bf := make([]byte, 2) 172 | if _, err := io.ReadFull(d.reader, bf); err != nil { 173 | return nil, newCodecError("short integer", err) 174 | } 175 | i := int32(tag-BC_INT_SHORT_ZERO)<<16 + int32(bf[1])<<8 + int32(bf[0]) 176 | return i, nil 177 | case tag == BC_INT: 178 | buf := make([]byte, 4) 179 | if _, err := io.ReadFull(d.reader, buf); err != nil { 180 | return nil, newCodecError("parse int", err) 181 | } 182 | i := int32(buf[0])<<24 + int32(buf[1])<<16 + int32(buf[2])<<8 + int32(buf[3]) 183 | return i, nil 184 | default: 185 | return nil, newCodecError("integer wrong tag ", tag) 186 | 187 | } 188 | } 189 | 190 | func (d *decoder) readLong(flag int32) (interface{}, error) { 191 | var tag byte 192 | if flag != TAG_READ { 193 | tag = byte(flag) 194 | } else { 195 | tag, _ = d.readBufByte() 196 | } 197 | 198 | switch { 199 | case tag >= 0xd8 && tag <= 0xef: 200 | return int64(tag - BC_LONG_ZERO), nil 201 | case tag >= 0xf4 && tag <= 0xff: 202 | 203 | bf := make([]byte, 1) 204 | if _, err := io.ReadFull(d.reader, bf); err != nil { 205 | return nil, newCodecError("short integer", err) 206 | } 207 | i := int64(tag-BC_LONG_BYTE_ZERO)<<8 + int64(bf[0]) 208 | return i, nil 209 | case tag >= 0x38 && tag <= 0x3f: 210 | bf := make([]byte, 2) 211 | if _, err := io.ReadFull(d.reader, bf); err != nil { 212 | return nil, newCodecError("short integer", err) 213 | } 214 | 215 | i := int64(tag-BC_LONG_SHORT_ZERO)<<16 + int64(bf[1])<<8 + int64(bf[0]) 216 | return i, nil 217 | case tag == BC_LONG: 218 | buf := make([]byte, 8) 219 | if _, err := io.ReadFull(d.reader, buf); err != nil { 220 | return nil, newCodecError("parse long", err) 221 | } 222 | i := int64(buf[0])<<56 + int64(buf[1])<<48 + int64(buf[2]) + int64(buf[3]) + 223 | int64(buf[4])<<24 + int64(buf[5])<<16 + int64(buf[6])<<8 + int64(buf[7]) 224 | return i, nil 225 | default: 226 | return nil, newCodecError("long wrong tag " + string(tag)) 227 | } 228 | 229 | } 230 | 231 | func (d *decoder) readDouble(flag int32) (interface{}, error) { 232 | var tag byte 233 | if flag != TAG_READ { 234 | tag = byte(flag) 235 | } else { 236 | tag, _ = d.readBufByte() 237 | } 238 | switch tag { 239 | case BC_LONG_INT: 240 | return d.readInt(TAG_READ) 241 | case BC_DOUBLE_ZERO: 242 | return float64(0), nil 243 | case BC_DOUBLE_ONE: 244 | return float64(1), nil 245 | case BC_DOUBLE_BYTE: 246 | bt, _ := d.readBufByte() 247 | return float64(bt), nil 248 | case BC_DOUBLE_SHORT: 249 | bf, _ := d.readBuf(2) 250 | return float64(int(bf[0])*256 + int(bf[1])), nil 251 | case BC_DOUBLE_MILL: 252 | i, _ := d.readInt(TAG_READ) 253 | return float64(i.(int32)), nil 254 | case BC_DOUBLE: 255 | buf, _ := d.readBuf(8) 256 | bits := binary.BigEndian.Uint64(buf) 257 | datum := math.Float64frombits(bits) 258 | return datum, nil 259 | } 260 | return nil, newCodecError("parse double wrong tag " + string(tag)) 261 | } 262 | 263 | func (d *decoder) readString(flag int32) (interface{}, error) { 264 | var tag byte 265 | if flag != TAG_READ { 266 | tag = byte(flag) 267 | } else { 268 | tag, _ = d.readBufByte() 269 | } 270 | last := true 271 | var len int32 272 | if (tag >= BC_STRING_DIRECT && tag <= STRING_DIRECT_MAX) || (tag >= 0x30 && tag <= 0x33) || (tag == BC_STRING_CHUNK || tag == BC_STRING) { 273 | //fmt.Println("inside ", tag) 274 | if tag == BC_STRING_CHUNK { 275 | last = false 276 | } else { 277 | last = true 278 | } 279 | l, err := d.getStrLen(tag) 280 | if err != nil { 281 | return nil, newCodecError("getStrLen", err) 282 | } 283 | len = l 284 | data := make([]byte, len) 285 | for i := 0; ; { 286 | if int32(i) == len { 287 | if last { 288 | //fmt.Println("last ", last, "i", i, "len", len) 289 | return string(data), nil 290 | } 291 | 292 | buf := make([]byte, 1) 293 | _, err := io.ReadFull(d.reader, buf) 294 | 295 | if err != nil { 296 | return nil, newCodecError("byte1 integer", err) 297 | } 298 | b := buf[0] 299 | switch { 300 | case b == BC_STRING_CHUNK || b == BC_STRING: 301 | if b == BC_STRING_CHUNK { 302 | last = false 303 | } else { 304 | last = true 305 | } 306 | l, err := d.getStrLen(b) 307 | if err != nil { 308 | return nil, newCodecError("getStrLen", err) 309 | } 310 | len += l 311 | bs := make([]byte, 0, len) 312 | copy(bs, data) 313 | data = bs 314 | default: 315 | return nil, newCodecError("tag error ", err) 316 | } 317 | } else { 318 | buf := make([]byte, 1) 319 | _, err := io.ReadFull(d.reader, buf) 320 | if err != nil { 321 | return nil, newCodecError("byte2 integer", err) 322 | } 323 | data[i] = buf[0] 324 | i++ 325 | } 326 | } 327 | return string(data), nil 328 | } else { 329 | fmt.Println(tag, len, last) 330 | return nil, newCodecError("byte3 integer") 331 | } 332 | 333 | } 334 | 335 | func (d *decoder) getStrLen(tag byte) (int32, error) { 336 | switch { 337 | case tag >= BC_STRING_DIRECT && tag <= STRING_DIRECT_MAX: 338 | return int32(tag - 0x00), nil 339 | case tag >= 0x30 && tag <= 0x33: 340 | buf := make([]byte, 1) 341 | _, err := io.ReadFull(d.reader, buf) 342 | if err != nil { 343 | return -1, newCodecError("byte4 integer", err) 344 | } 345 | len := int32(tag-0x30)<<8 + int32(buf[0]) 346 | return len, nil 347 | 348 | case tag == BC_STRING_CHUNK || tag == BC_STRING: 349 | buf := make([]byte, 1) 350 | _, err := io.ReadFull(d.reader, buf) 351 | if err != nil { 352 | return -1, newCodecError("byte5 integer", err) 353 | } 354 | len := int32(tag)<<8 + int32(buf[0]) 355 | return len, nil 356 | default: 357 | return -1, newCodecError("getStrLen") 358 | } 359 | } 360 | 361 | func (d *decoder) readInstance(typ reflect.Type, cls ClassDef) (interface{}, error) { 362 | if typ.Kind() != reflect.Struct { 363 | return nil, newCodecError("wrong type expect Struct but get " + typ.String()) 364 | } 365 | vv := reflect.New(typ) 366 | st := reflect.ValueOf(vv.Interface()).Elem() 367 | for i := 0; i < len(cls.FieldName); i++ { 368 | fldName := cls.FieldName[i] 369 | index, err := findField(fldName, typ) 370 | if err != nil { 371 | log.Printf("%s is not found, will ski type ->p %v", fldName, typ) 372 | continue 373 | } 374 | fldValue := st.Field(index) 375 | //fmt.Println("fld", fldName, fldValue, fldValue.Kind()) 376 | if !fldValue.CanSet() { 377 | return nil, newCodecError("CanSet false for " + fldName) 378 | } 379 | kind := fldValue.Kind() 380 | switch { 381 | case kind == reflect.String: 382 | str, err := d.readString(TAG_READ) 383 | if err != nil { 384 | return nil, newCodecError("ReadString "+fldName, err) 385 | } 386 | fldValue.SetString(str.(string)) 387 | case kind == reflect.Int32 || kind == reflect.Int || kind == reflect.Int16: 388 | i, err := d.readInt(TAG_READ) 389 | if err != nil { 390 | return nil, newCodecError("ParseInt"+fldName, err) 391 | } 392 | v := int64(i.(int32)) 393 | fldValue.SetInt(v) 394 | case kind == reflect.Int64 || kind == reflect.Uint64: 395 | i, err := d.readLong(TAG_READ) 396 | if err != nil { 397 | return nil, newCodecError("decode error "+fldName, err) 398 | } 399 | fldValue.SetInt(i.(int64)) 400 | case kind == reflect.Bool: 401 | b, err := d.ReadObject() 402 | if err != nil { 403 | return nil, newCodecError("decode error "+fldName, err) 404 | } 405 | fldValue.SetBool(b.(bool)) 406 | case kind == reflect.Float32 || kind == reflect.Float64: 407 | d, err := d.readDouble(TAG_READ) 408 | if err != nil { 409 | return nil, newCodecError("decode error "+fldName, err) 410 | } 411 | fldValue.SetFloat(d.(float64)) 412 | case kind == reflect.Struct: 413 | s, err := d.ReadObject() 414 | if err != nil { 415 | fmt.Println("struct error", err) 416 | } 417 | fldValue.Set(reflect.Indirect(s.(reflect.Value))) 418 | fmt.Println("s with struct", s) 419 | case kind == reflect.Map: 420 | //m, _ := d.ReadObject() 421 | //fmt.Println("struct map", m) 422 | d.readMap(fldValue) 423 | case kind == reflect.Slice || kind == reflect.Array: 424 | m, _ := d.ReadObject() 425 | v := reflect.ValueOf(m) 426 | if v.Len() > 0 { 427 | sl := reflect.MakeSlice(fldValue.Type(), v.Len(), v.Len()) 428 | for i := 0; i < v.Len(); i++ { 429 | sl.Index(i).Set(reflect.ValueOf(v.Index(i).Interface())) 430 | } 431 | fldValue.Set(sl) 432 | } 433 | } 434 | 435 | } 436 | return vv, nil 437 | } 438 | 439 | func (d *decoder) readMap(value reflect.Value) error { 440 | tag, _ := d.readBufByte() 441 | if tag == BC_MAP { 442 | d.readString(TAG_READ) 443 | } else if tag == BC_MAP_UNTYPED { 444 | //do nothing 445 | } else { 446 | return newCodecError("wrong header BC_MAP_UNTYPED") 447 | } 448 | m := reflect.MakeMap(value.Type()) 449 | //read key and value 450 | for { 451 | key, err := d.ReadObject() 452 | if err != nil { 453 | if err == io.EOF { 454 | //fmt.Println("endMamp") 455 | break 456 | } else { 457 | return newCodecError("ReadType", err) 458 | } 459 | } 460 | vl, err := d.ReadObject() 461 | fmt.Println(key, vl) 462 | m.SetMapIndex(reflect.ValueOf(key), reflect.ValueOf(vl)) 463 | } 464 | value.Set(m) 465 | return nil 466 | } 467 | 468 | func (d *decoder) readSlice(value reflect.Value) (interface{}, error) { 469 | tag, _ := d.readBufByte() 470 | var i int 471 | if tag >= BC_LIST_DIRECT_UNTYPED && tag <= 0x7f { 472 | i = int(tag - BC_LIST_DIRECT_UNTYPED) 473 | } else { 474 | ii, err := d.readInt(TAG_READ) 475 | if err != nil { 476 | return nil, newCodecError("ReadType", err) 477 | } 478 | i = int(ii.(int32)) 479 | } 480 | //fmt.Println("list len ", i) 481 | ary := reflect.MakeSlice(value.Type(), i, i) 482 | for j := 0; j < i; j++ { 483 | it, err := d.ReadObject() 484 | if err != nil { 485 | return nil, newCodecError("ReadList", err) 486 | } 487 | ary.Index(j).Set(reflect.ValueOf(it)) 488 | //fmt.Println("j", j, "it", it) 489 | } 490 | d.readBufByte() 491 | //fmt.Println("endList", bt) 492 | value.Set(ary) 493 | return ary, nil 494 | } 495 | 496 | func CapitalizeName(name string) string { 497 | if name[0] >= 'A' && name[0] <= 'Z' { 498 | return name 499 | } 500 | if name[0] >= 'a' && name[0] <= 'z' { 501 | bs := make([]byte, len(name)) 502 | bs[0] = byte(name[0] - ASCII_GAP) 503 | copy(bs[1:], name[1:]) 504 | return string(bs) 505 | } else { 506 | return name 507 | } 508 | 509 | } 510 | 511 | func findField(name string, typ reflect.Type) (int, error) { 512 | for i := 0; i < typ.NumField(); i++ { 513 | str := typ.Field(i).Name 514 | if strings.Compare(str, name) == 0 { 515 | return i, nil 516 | } 517 | str1 := CapitalizeName(name) 518 | if strings.Compare(str, str1) == 0 { 519 | return i, nil 520 | } 521 | } 522 | return 0, newCodecError("findField") 523 | } 524 | 525 | func (d *decoder) readType() (interface{}, error) { 526 | buf := make([]byte, 1) 527 | _, err := io.ReadFull(d.reader, buf) 528 | if err != nil { 529 | return nil, newCodecError("reading tag", err) 530 | } 531 | tag := buf[0] 532 | if (tag >= BC_STRING_DIRECT && tag <= STRING_DIRECT_MAX) || (tag >= 0x30 && tag <= 0x33) || (tag == BC_STRING || tag == BC_STRING_CHUNK) { 533 | return d.readString(int32(tag)) 534 | } else { 535 | i, err := d.readInt(TAG_READ) 536 | if err != nil { 537 | return nil, newCodecError("reading tag", err) 538 | } 539 | index := int(i.(int32)) 540 | return d.typList[index], nil 541 | } 542 | } 543 | 544 | func (d *decoder) ReadObject() (interface{}, error) { 545 | tag, err := d.readBufByte() 546 | if err != nil { 547 | return nil, newCodecError("reading tag", err) 548 | } 549 | //fmt.Println("tag ", tag) 550 | switch { 551 | case tag == BC_END: 552 | return nil, io.EOF 553 | case tag == BC_NULL: 554 | return nil, nil 555 | case tag == BC_TRUE: 556 | return true, nil 557 | case tag == BC_FALSE: 558 | return false, nil 559 | //direct integer 560 | case tag == BC_MAP: 561 | _, err := d.readType() 562 | if err != nil { 563 | return nil, newCodecError("ReadType", err) 564 | } 565 | m := make(map[interface{}]interface{}) 566 | //read key and value 567 | key, _ := d.ReadObject() 568 | value, _ := d.ReadObject() 569 | m[key] = value 570 | return m, nil 571 | case tag == BC_MAP_UNTYPED: 572 | m := make(map[interface{}]interface{}) 573 | //read key and value 574 | for { 575 | key, err := d.ReadObject() 576 | if err != nil { 577 | if err == io.EOF { 578 | //fmt.Println("endMamp") 579 | return m, nil 580 | } else { 581 | return nil, newCodecError("ReadType", err) 582 | } 583 | } 584 | value, err := d.ReadObject() 585 | fmt.Println(key, value) 586 | m[key] = value 587 | } 588 | case tag == BC_OBJECT_DEF: 589 | //fmt.Println("BC_OBJECT_DEF") 590 | clsDef, err := d.readClassDef() 591 | if err != nil { 592 | return nil, newCodecError("byte double", err) 593 | } 594 | clsD, _ := clsDef.(ClassDef) 595 | //add to slice 596 | d.clsDefList = append(d.clsDefList, clsD) 597 | //fmt.Println("clsD", clsD) 598 | //read from refList of ClassDef 599 | return d.ReadObject() 600 | case tag == BC_OBJECT: 601 | //fmt.Println("BC_OBJECT ") 602 | i, _ := d.readInt(TAG_READ) 603 | idx := int(i.(int32)) 604 | clsD := d.clsDefList[idx] 605 | typ, ok := d.typMap[clsD.FullClassName] 606 | if !ok { 607 | return nil, newCodecError("undefine type for "+clsD.FullClassName, err) 608 | } 609 | return d.readInstance(typ, clsD) 610 | case (tag >= 0x80 && tag <= 0xbf) || (tag >= 0xc0 && tag <= 0xcf) || 611 | (tag >= 0xd0 && tag <= 0xd7) || (tag == BC_INT): 612 | return d.readInt(int32(tag)) 613 | 614 | case (tag >= 0xd8 && tag <= 0xef) || (tag >= 0xf4 && tag <= 0xff) || 615 | (tag >= 0x38 && tag <= 0x3f) || (tag == BC_LONG_INT) || 616 | (tag == BC_LONG): 617 | return d.readLong(int32(tag)) 618 | case tag == BC_DOUBLE_ZERO: 619 | return float64(0), nil 620 | case tag == BC_DOUBLE_ONE: 621 | return float64(1), nil 622 | case tag == BC_DOUBLE_BYTE: 623 | bf1 := make([]byte, 1) 624 | if _, err := io.ReadFull(d.reader, bf1); err != nil { 625 | return nil, newCodecError("byte double", err) 626 | } 627 | i := float64(bf1[0]) 628 | return i, nil 629 | case tag == BC_DOUBLE_SHORT: 630 | bf1 := make([]byte, 2) 631 | if _, err := io.ReadFull(d.reader, bf1); err != nil { 632 | return nil, newCodecError("short long", err) 633 | } 634 | i := float64(bf1[0])*256 + float64(bf1[0]) 635 | return i, nil 636 | case tag == BC_DOUBLE_MILL: 637 | t, err := d.readInt(int32(tag)) 638 | if err == nil { 639 | return t, err 640 | } else { 641 | return nil, newCodecError("double mill", err) 642 | } 643 | case tag == BC_DOUBLE: 644 | return d.readDouble(int32(tag)) 645 | case tag == BC_DATE: 646 | _, err := d.readLong(int32(tag)) 647 | if err != nil { 648 | return nil, newCodecError("date", err) 649 | } else { 650 | return nil, newCodecError("not yet implementd") 651 | } 652 | case tag == BC_DATE_MINUTE: 653 | return nil, newCodecError("not yet implementd") 654 | case (tag == BC_STRING_CHUNK || tag == BC_STRING) || 655 | (tag >= BC_STRING_DIRECT && tag <= STRING_DIRECT_MAX) || 656 | (tag >= 0x30 && tag <= 0x33): 657 | return d.readString(int32(tag)) 658 | case (tag >= 0x60 && tag <= 0x6f): 659 | //fmt.Println("ReadInstance") 660 | i := int(tag - 0x60) 661 | clsD := d.clsDefList[i] 662 | typ, ok := d.typMap[clsD.FullClassName] 663 | if !ok { 664 | return nil, newCodecError("undefine type for "+clsD.FullClassName, err) 665 | } 666 | return d.readInstance(typ, clsD) 667 | 668 | case (tag == BC_BINARY || tag == BC_BINARY_CHUNK) || (tag >= 0x20 && tag <= 0x2f): 669 | return d.readBinary(int32(tag)) 670 | case (tag >= BC_LIST_DIRECT && tag <= 0x77) || (tag == BC_LIST_FIXED || tag == BC_LIST_VARIABLE): 671 | str, err := d.readType() 672 | if err != nil { 673 | return nil, newCodecError("ReadType", err) 674 | } 675 | var i int 676 | if tag >= BC_LIST_DIRECT && tag <= 0x77 { 677 | i = int(tag - BC_LIST_DIRECT) 678 | } else { 679 | ii, err := d.readInt(TAG_READ) 680 | if err != nil { 681 | return nil, newCodecError("ReadType", err) 682 | } 683 | i = int(ii.(int32)) 684 | } 685 | ary := make([]interface{}, i) 686 | bl := isBuildInType(str.(string)) 687 | if bl == false { 688 | for j := 0; j < i; j++ { 689 | it, err := d.ReadObject() 690 | if err != nil { 691 | return nil, newCodecError("ReadList", err) 692 | } 693 | ary[j] = it 694 | //fmt.Println("j", j, "it", it) 695 | } 696 | } else { 697 | for j := 0; j < i; j++ { 698 | it, err := d.ReadObject() 699 | if err != nil { 700 | return nil, newCodecError("ReadList", err) 701 | } 702 | ary[j] = it 703 | //fmt.Println("j", j, "it", it) 704 | } 705 | } 706 | return ary, nil 707 | case (tag >= BC_LIST_DIRECT_UNTYPED && tag <= 0x7f) || (tag == BC_LIST_FIXED_UNTYPED || tag == BC_LIST_VARIABLE_UNTYPED): 708 | var i int 709 | if tag >= BC_LIST_DIRECT_UNTYPED && tag <= 0x7f { 710 | i = int(tag - BC_LIST_DIRECT_UNTYPED) 711 | } else { 712 | ii, err := d.readInt(TAG_READ) 713 | if err != nil { 714 | return nil, newCodecError("ReadType", err) 715 | } 716 | i = int(ii.(int32)) 717 | } 718 | //fmt.Println("list len ", i) 719 | ary := make([]interface{}, i) 720 | for j := 0; j < i; j++ { 721 | it, err := d.ReadObject() 722 | if err != nil { 723 | return nil, newCodecError("ReadList", err) 724 | } 725 | ary[j] = it 726 | //fmt.Println("j", j, "it", it) 727 | } 728 | //read the endbyte of list 729 | d.readBufByte() 730 | //fmt.Println("endList", bt) 731 | return ary, nil 732 | default: 733 | return nil, newCodecError("unkonw tag") 734 | } 735 | return nil, newCodecError("wrong tag") 736 | } 737 | 738 | func isBuildInType(typeStr string) bool { 739 | switch typeStr { 740 | case ARRAY_STRING: 741 | return true 742 | case ARRAY_INT: 743 | return true 744 | case ARRAY_FLOAT: 745 | return true 746 | case ARRAY_DOUBLE: 747 | return true 748 | case ARRAY_BOOL: 749 | return true 750 | case ARRAY_LONG: 751 | return true 752 | default: 753 | return false 754 | } 755 | } 756 | 757 | func (d *decoder) readBinary(flag int32) (interface{}, error) { 758 | var tag byte 759 | if flag != TAG_READ { 760 | tag = byte(flag) 761 | } else { 762 | tag, _ = d.readBufByte() 763 | } 764 | last := true 765 | var len int32 766 | if (tag >= BC_BINARY_DIRECT && tag <= INT_DIRECT_MAX) || (tag == BC_BINARY || tag == BC_BINARY_CHUNK) { 767 | if tag == BC_BINARY_CHUNK { 768 | last = false 769 | } else { 770 | last = true 771 | } 772 | l, err := d.getBinLen(tag) 773 | if err != nil { 774 | return nil, newCodecError("getStrLen", err) 775 | } 776 | len = int32(l) 777 | data := make([]byte, len) 778 | for i := 0; ; { 779 | if int32(i) == len { 780 | if last { 781 | //fmt.Println("last ", last, "i", i, "len", len) 782 | return string(data), nil 783 | } 784 | 785 | buf := make([]byte, 1) 786 | _, err := io.ReadFull(d.reader, buf) 787 | 788 | if err != nil { 789 | return nil, newCodecError("byte1 integer", err) 790 | } 791 | b := buf[0] 792 | switch { 793 | case b == BC_BINARY_CHUNK || b == BC_BINARY: 794 | if b == BC_BINARY_CHUNK { 795 | last = false 796 | } else { 797 | last = true 798 | } 799 | l, err := d.getStrLen(b) 800 | if err != nil { 801 | return nil, newCodecError("getStrLen", err) 802 | } 803 | len += l 804 | bs := make([]byte, 0, len) 805 | copy(bs, data) 806 | data = bs 807 | default: 808 | return nil, newCodecError("tag error ", err) 809 | } 810 | } else { 811 | buf := make([]byte, 1) 812 | _, err := io.ReadFull(d.reader, buf) 813 | 814 | if err != nil { 815 | return nil, newCodecError("byte2 integer", err) 816 | } 817 | data[i] = buf[0] 818 | i++ 819 | } 820 | } 821 | return data, nil 822 | } else { 823 | //fmt.Println(tag, len, last) 824 | return nil, newCodecError("byte3 integer") 825 | } 826 | 827 | } 828 | 829 | func (d *decoder) getBinLen(tag byte) (int, error) { 830 | if tag >= BC_BINARY_DIRECT && tag <= INT_DIRECT_MAX { 831 | return int(tag - BC_BINARY_DIRECT), nil 832 | } 833 | bs := make([]byte, 2) 834 | _, err := io.ReadFull(d.reader, bs) 835 | if err != nil { 836 | return 0, newCodecError("parse binary", err) 837 | } 838 | return int(bs[0]<<8 + bs[1]), nil 839 | } 840 | 841 | func (d *decoder) readClassDef() (interface{}, error) { 842 | f, err := d.readString(TAG_READ) 843 | if err != nil { 844 | return nil, newCodecError("ReadClassDef", err) 845 | } 846 | clsName, ok := f.(string) 847 | if !ok { 848 | return nil, newCodecError("wrong type") 849 | } 850 | fmt.Println("clsName", clsName) 851 | n, err := d.readInt(TAG_READ) 852 | if err != nil { 853 | return nil, newCodecError("ReadClassDef", err) 854 | } 855 | no, ok := n.(int32) 856 | fields := make([]string, no) 857 | for i := 0; i < int(no); i++ { 858 | s, err := d.readString(TAG_READ) 859 | if err != nil { 860 | return nil, newCodecError("ReadClassDef", err) 861 | } 862 | s1, ok := s.(string) 863 | if !ok { 864 | return nil, newCodecError("wrong type") 865 | } 866 | fields[i] = s1 867 | } 868 | cls := ClassDef{clsName, fields} 869 | return cls, nil 870 | } 871 | 872 | //func floatDecoder(r io.Reader) (interface{}, error) { 873 | // buf := make([]byte, 4) 874 | // if _, err := io.ReadFull(r, buf); err != nil { 875 | // return nil, newCodecError("float", err) 876 | // } 877 | // bits := binary.LittleEndian.Uint32(buf) 878 | // datum := math.Float32frombits(bits) 879 | // return datum, nil 880 | //} 881 | -------------------------------------------------------------------------------- /decoder_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright 2012=2016 Viant. 4 | * * 5 | * * Licensed under the Apache License, Version 2.0 (the "License"); you may not 6 | * * use this file except in compliance with the License. You may obtain a copy of 7 | * * the License at 8 | * * 9 | * * http://www.apache.org/licenses/LICENSE-2.0 10 | * * 11 | * * Unless required by applicable law or agreed to in writing, software 12 | * * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | * * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | * * License for the specific language governing permissions and limitations under 15 | * * the License. 16 | * 17 | */ 18 | 19 | package hessian 20 | 21 | import ( 22 | "bytes" 23 | "fmt" 24 | "reflect" 25 | "testing" 26 | ) 27 | 28 | func makeInt(ps []int32) []interface{} { 29 | rt := make([]interface{}, len(ps)) 30 | for i, t := range ps { 31 | rt[i] = t 32 | } 33 | return rt 34 | } 35 | 36 | /* 37 | Commented out at Michael's request. Delete this or not? 38 | func TestDecoder_Invoker(t *testing.T) { 39 | file3, err := os.Open("/Users/mhsieh/test/files/msg.hs") 40 | if err != nil { 41 | log.Fatal(err) 42 | } 43 | d := NewDecoder(file3, nil) 44 | iv := message.Invoker{} 45 | d.RegisterType("com.sm.message.Invoker", reflect.TypeOf(iv)) 46 | ts1, _ := d.ReadObject() 47 | fmt.Println("ts1 ", ts1) 48 | pv := []int32{1, 2} 49 | iv = message.Invoker{"Math", "Add", makeInt(pv)} 50 | br := bytes.NewBuffer(nil) 51 | e := NewEncoder(br, message.DefaultNameMap()) 52 | e.WriteObject(iv) 53 | bt := bytes.NewReader(br.Bytes()) 54 | d = NewDecoder(bt, message.DefaultTypeMap()) 55 | ts1, _ = d.ReadObject() 56 | fmt.Println("ts1 ", ts1) 57 | } 58 | */ 59 | 60 | /* 61 | Commented out at michael's request. Delete this or not? 62 | func TestDecoder_Double(t *testing.T) { 63 | file3, err := os.Open("/Users/mhsieh/test/files/dbl.hs") 64 | if err != nil { 65 | log.Fatal(err) 66 | } 67 | d := NewDecoder(file3, nil) 68 | ts1, _ := d.ReadObject() 69 | fmt.Println("ts1 ", ts1) 70 | ts2, _ := d.ReadObject() 71 | fmt.Println("ts2 ", ts2) 72 | //ts3, _ := d.ReadObject() 73 | ts3, _ := d.readDouble(TAG_READ) 74 | fmt.Println("ts3 ", ts3) 75 | fmt.Println(reflect.TypeOf(ts2), reflect.ValueOf(ts2)) 76 | } 77 | */ 78 | 79 | func TestMethod_pkg(t *testing.T) { 80 | br := bytes.NewBuffer(nil) 81 | e := NewEncoder(br, nil) 82 | typ := reflect.TypeOf(e) 83 | for m := 0; m < typ.NumMethod(); m++ { 84 | method := typ.Method(m) 85 | mtype := method.Type 86 | mname := method.Name 87 | fmt.Println("pkg", method.PkgPath, len(method.PkgPath), "type", mtype, mname) 88 | } 89 | 90 | } 91 | -------------------------------------------------------------------------------- /encoder.go: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright 2012-2016 Viant. 4 | * * 5 | * * Licensed under the Apache License, Version 2.0 (the "License"); you may not 6 | * * use this file except in compliance with the License. You may obtain a copy of 7 | * * the License at 8 | * * 9 | * * http://www.apache.org/licenses/LICENSE-2.0 10 | * * 11 | * * Unless required by applicable law or agreed to in writing, software 12 | * * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | * * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | * * License for the specific language governing permissions and limitations under 15 | * * the License. 16 | * 17 | */ 18 | 19 | package hessian 20 | 21 | import ( 22 | "fmt" 23 | "io" 24 | "math" 25 | "reflect" 26 | "strings" 27 | ) 28 | 29 | type encoder struct { 30 | writer io.Writer 31 | clsDefList []ClassDef 32 | nameMap map[string]string 33 | } 34 | 35 | func NewEncoder(w io.Writer, np map[string]string) *encoder { 36 | if w == nil { 37 | return nil 38 | } 39 | if np == nil { 40 | np = make(map[string]string, 17) 41 | } 42 | encoder := &encoder{w, make([]ClassDef, 0, 17), np} 43 | return encoder 44 | } 45 | 46 | func (e *encoder) RegisterNameType(key string, javaClsName string) { 47 | e.nameMap[key] = javaClsName 48 | } 49 | 50 | func (e *encoder) RegisterNameMap(mp map[string]string) { 51 | e.nameMap = mp 52 | } 53 | 54 | func (e *encoder) Reset() { 55 | e.nameMap = make(map[string]string, 17) 56 | e.clsDefList = make([]ClassDef, 0, 17) 57 | } 58 | 59 | func (e *encoder) WriteObject(data interface{}) (int, error) { 60 | if data == nil { 61 | io.WriteString(e.writer, "N") 62 | return 1, nil 63 | } 64 | typ := reflect.TypeOf(data) 65 | 66 | switch typ.Kind() { 67 | case reflect.String: 68 | value := data.(string) 69 | return e.writeString(value) 70 | case reflect.Int32: 71 | value := data.(int32) 72 | return e.writeInt(value) 73 | case reflect.Int64: 74 | value := data.(int64) 75 | return e.writeLong(value) 76 | case reflect.Slice, reflect.Array: 77 | return e.writeList(data) 78 | case reflect.Float32: 79 | value := data.(float32) 80 | return e.writeDouble(float64(value)) 81 | case reflect.Float64: 82 | value := data.(float64) 83 | return e.writeDouble(value) 84 | //case reflect.Uint8: 85 | case reflect.Map: 86 | return e.writeMap(data) 87 | case reflect.Bool: 88 | value := data.(bool) 89 | return e.writeBoolean(value) 90 | case reflect.Struct: 91 | return e.writeInstance(data) 92 | } 93 | fmt.Println("error WriteObject", data, "kind", typ.Kind(), typ) 94 | return 0, nil 95 | } 96 | 97 | func (e *encoder) writeDouble(value float64) (int, error) { 98 | v := float64(int64(value)) 99 | if v == value { 100 | iv := int64(value) 101 | switch iv { 102 | case 0: 103 | return e.writeBT(BC_DOUBLE_ZERO) 104 | case 1: 105 | return e.writeBT(BC_DOUBLE_ONE) 106 | } 107 | if iv >= -0x80 && iv < 0x80 { 108 | e.writeBT(BC_DOUBLE_BYTE, byte(iv)) 109 | } else if iv >= -0x8000 && iv < 0x8000 { 110 | e.writeBT(BC_DOUBLE_BYTE, byte(iv>>8), byte(iv)) 111 | } 112 | } else { 113 | bits := uint64(math.Float64bits(value)) 114 | e.writeBT(BC_DOUBLE) 115 | e.writeBT(byte(bits>>56), byte(bits>>48), byte(bits>>40), byte(bits>>32), byte(bits>>24), 116 | byte(bits>>16), byte(bits>>8), byte(bits)) 117 | } 118 | return 8, nil 119 | 120 | } 121 | 122 | func (e *encoder) writeMap(data interface{}) (int, error) { 123 | e.writeBT(BC_MAP_UNTYPED) 124 | vv := reflect.ValueOf(data) 125 | typ := reflect.TypeOf(data).Key() 126 | keys := vv.MapKeys() 127 | for i := 0; i < len(keys); i++ { 128 | k := buildKey(keys[i], typ) 129 | e.WriteObject(k) 130 | //e.WriteObject(keys[i].Interface()) 131 | //v := buildValue(vv.MapIndex(keys[i])) 132 | //e.WriteObject(v) 133 | e.WriteObject(vv.MapIndex(keys[i]).Interface()) 134 | } 135 | e.writeBT(BC_END) 136 | return len(keys), nil 137 | } 138 | 139 | func buildKey(key reflect.Value, typ reflect.Type) interface{} { 140 | switch typ.Kind() { 141 | case reflect.String: 142 | return key.String() 143 | case reflect.Bool: 144 | return key.Bool() 145 | case reflect.Int: 146 | return int32(key.Int()) 147 | case reflect.Int8: 148 | return int8(key.Int()) 149 | case reflect.Int16: 150 | case reflect.Int32: 151 | return int32(key.Int()) 152 | case reflect.Int64: 153 | return key.Int() 154 | case reflect.Uint8: 155 | return byte(key.Uint()) 156 | case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64: 157 | return key.Uint() 158 | } 159 | return newCodecError("unsuport key kind " + typ.Kind().String()) 160 | } 161 | 162 | func (e *encoder) writeString(value string) (int, error) { 163 | dataBys := []byte(value) 164 | l := len(dataBys) 165 | sub := 0x8000 166 | begin := 0 167 | for l > sub { 168 | buf := make([]byte, 3) 169 | buf[0] = BC_STRING_CHUNK 170 | buf[1] = byte(sub >> 8) 171 | buf[2] = byte(sub) 172 | _, err := e.writer.Write(buf) 173 | if err != nil { 174 | return 0, newCodecError("writeString", err) 175 | } 176 | buf = make([]byte, sub) 177 | copy(buf, dataBys[begin:begin+sub]) 178 | _, err = e.writer.Write(buf) 179 | if err != nil { 180 | return 0, newCodecError("writeString", err) 181 | } 182 | l -= sub 183 | begin += sub 184 | } 185 | var buf []byte 186 | if l == 0 { 187 | return len(dataBys), nil 188 | } else if l <= int(STRING_DIRECT_MAX) { 189 | buf = make([]byte, 1) 190 | buf[0] = byte(l + int(BC_STRING_DIRECT)) 191 | } else if l <= int(STRING_SHORT_MAX) { 192 | buf = make([]byte, 2) 193 | buf[0] = byte((l >> 8) + int(BC_STRING_SHORT)) 194 | buf[1] = byte(l) 195 | } else { 196 | buf = make([]byte, 3) 197 | buf[0] = BC_STRING 198 | buf[0] = byte(l >> 8) 199 | buf[1] = byte(l) 200 | } 201 | bs := make([]byte, l+len(buf)) 202 | copy(bs[0:], buf) 203 | copy(bs[len(buf):], dataBys[begin:]) 204 | _, err := e.writer.Write(bs) 205 | if err != nil { 206 | return 0, newCodecError("writeString", err) 207 | } 208 | return l, nil 209 | } 210 | 211 | func (e *encoder) writeList(data interface{}) (int, error) { 212 | 213 | vv := reflect.ValueOf(data) 214 | e.writeBT(BC_LIST_FIXED_UNTYPED) 215 | e.writeInt(int32(vv.Len())) 216 | fmt.Println("list", vv.Len(), data) 217 | for i := 0; i < vv.Len(); i++ { 218 | e.WriteObject(vv.Index(i).Interface()) 219 | } 220 | e.writeBT(BC_END) 221 | return vv.Len(), nil 222 | } 223 | 224 | func (e *encoder) writeInt(value int32) (int, error) { 225 | var buf []byte 226 | if int32(INT_DIRECT_MIN) <= value && value <= int32(INT_DIRECT_MAX) { 227 | buf = make([]byte, 1) 228 | buf[0] = byte(value + int32(BC_INT_ZERO)) 229 | } else if int32(INT_BYTE_MIN) <= value && value <= int32(INT_BYTE_MAX) { 230 | buf = make([]byte, 2) 231 | buf[0] = byte(int32(BC_INT_BYTE_ZERO) + value>>8) 232 | buf[1] = byte(value) 233 | } else if int32(INT_SHORT_MIN) <= value && value <= int32(INT_SHORT_MAX) { 234 | buf = make([]byte, 3) 235 | buf[0] = byte(value>>16 + int32(BC_INT_SHORT_ZERO)) 236 | buf[1] = byte(value >> 8) 237 | buf[2] = byte(value) 238 | } else { 239 | buf = make([]byte, 5) 240 | buf[0] = byte('I') 241 | buf[1] = byte(value >> 24) 242 | buf[2] = byte(value >> 16) 243 | buf[3] = byte(value >> 8) 244 | buf[4] = byte(value) 245 | } 246 | l, err := e.writer.Write(buf) 247 | if err != nil { 248 | return 0, newCodecError("WriteInt", err) 249 | } 250 | return l, nil 251 | } 252 | 253 | func (e *encoder) writeLong(value int64) (int, error) { 254 | var buf []byte 255 | if int64(LONG_DIRECT_MIN) <= value && value <= int64(LONG_DIRECT_MAX) { 256 | buf = make([]byte, 1) 257 | buf[0] = byte(value - int64(BC_LONG_ZERO)) 258 | } else if int64(LONG_BYTE_MIN) <= value && value <= int64(LONG_BYTE_MAX) { 259 | buf = make([]byte, 2) 260 | buf[0] = byte(int64(BC_LONG_BYTE_ZERO) + (value >> 8)) 261 | buf[1] = byte(value) 262 | } else if int64(LONG_SHORT_MIN) <= value && value <= int64(LONG_SHORT_MAX) { 263 | buf = make([]byte, 3) 264 | buf[0] = byte(int64(BC_LONG_SHORT_ZERO) + (value >> 16)) 265 | buf[1] = byte(value >> 8) 266 | buf[2] = byte(value) 267 | } else if 0x80000000 <= value && value <= 0x7fffffff { 268 | buf = make([]byte, 5) 269 | buf[0] = BC_LONG_INT 270 | buf[1] = byte(value >> 24) 271 | buf[2] = byte(value >> 16) 272 | buf[3] = byte(value >> 8) 273 | buf[4] = byte(value) 274 | } else { 275 | buf = make([]byte, 9) 276 | buf[0] = 'L' 277 | buf[1] = byte(value >> 56) 278 | buf[2] = byte(value >> 48) 279 | buf[3] = byte(value >> 32) 280 | buf[4] = byte(value >> 24) 281 | buf[5] = byte(value >> 16) 282 | buf[6] = byte(value >> 8) 283 | buf[7] = byte(value) 284 | } 285 | l, err := e.writer.Write(buf) 286 | if err != nil { 287 | return 0, newCodecError("WriteLong", err) 288 | } 289 | return l, nil 290 | } 291 | 292 | func (e *encoder) writeBoolean(value bool) (int, error) { 293 | buf := make([]byte, 1) 294 | if value { 295 | buf[0] = BC_TRUE 296 | } else { 297 | buf[0] = BC_FALSE 298 | } 299 | l, err := e.writer.Write(buf) 300 | if err != nil { 301 | return 0, newCodecError("WriteBoolean", err) 302 | } 303 | return l, nil 304 | } 305 | 306 | func (e *encoder) writeBytes(value []byte) (int, error) { 307 | sub := CHUNK_SIZE 308 | l := len(value) 309 | begin := 0 310 | 311 | for l > sub { 312 | buf := make([]byte, 3+CHUNK_SIZE) 313 | buf[0] = byte(BC_BINARY_CHUNK) 314 | buf[1] = byte(sub >> 8) 315 | buf[2] = byte(sub) 316 | 317 | copy(buf[3:], value[begin:begin+CHUNK_SIZE]) 318 | _, err := e.writer.Write(buf) 319 | if err != nil { 320 | return 0, newCodecError("WriteBytes", err) 321 | } 322 | l -= CHUNK_SIZE 323 | begin += CHUNK_SIZE 324 | } 325 | var buf []byte 326 | if l == 0 { 327 | return len(value), nil 328 | } else if l <= int(BINARY_DIRECT_MAX) { 329 | buf := make([]byte, 1) 330 | buf[0] = byte(int(BC_BINARY_DIRECT) + l) 331 | } else if l <= int(BINARY_SHORT_MAX) { 332 | buf := make([]byte, 2) 333 | buf[0] = byte(int(BC_BINARY_SHORT) + l>>8) 334 | buf[1] = byte(l) 335 | } else { 336 | buf := make([]byte, 3) 337 | buf[0] = byte(BC_BINARY) 338 | buf[1] = byte(l >> 8) 339 | buf[2] = byte(l) 340 | } 341 | bs := make([]byte, l+len(buf)) 342 | copy(bs[0:], buf) 343 | copy(bs[len(buf):], value[begin:]) 344 | _, err := e.writer.Write(bs) 345 | if err != nil { 346 | return 0, newCodecError("WriteBytes", err) 347 | } 348 | return len(value), nil 349 | } 350 | 351 | func (e *encoder) writeBT(bs ...byte) (int, error) { 352 | return e.writer.Write(bs) 353 | } 354 | 355 | func (e *encoder) writeInstance(data interface{}) (int, error) { 356 | fmt.Println("struct", data) 357 | typ := reflect.TypeOf(data) 358 | vv := reflect.ValueOf(data) 359 | 360 | clsName, ok := e.nameMap[typ.Name()] 361 | if !ok { 362 | clsName = typ.Name() 363 | e.nameMap[clsName] = clsName 364 | } 365 | //fmt.Println("ok",ok, clsName) 366 | l, ok := e.existClassDef(clsName) 367 | //fmt.Println("ok 2 ->",ok, l) 368 | if !ok { 369 | l, _ = e.writeClsDef(typ, clsName) 370 | } 371 | if byte(l) <= OBJECT_DIRECT_MAX { 372 | e.writeBT(byte(l) + BC_OBJECT_DIRECT) 373 | } else { 374 | e.writeBT(BC_OBJECT) 375 | e.writeInt(int32(l)) 376 | } 377 | for i := 0; i < vv.NumField(); i++ { 378 | //if field.Field(i).Type().PkgPath() != "" { 379 | // continue 380 | //} 381 | e.writeField(vv.Field(i), vv.Field(i).Type().Kind()) 382 | } 383 | return vv.NumField(), nil 384 | } 385 | 386 | func (e *encoder) writeField(field reflect.Value, kind reflect.Kind) error { 387 | switch kind { 388 | case reflect.Struct: 389 | //fmt.Println("StructFiled", field.Interface(), "num", field.NumField()) 390 | e.WriteObject(field.Interface()) 391 | case reflect.String: 392 | v := field.String() 393 | e.writeString(v) 394 | case reflect.Int32: 395 | v := int32(field.Int()) 396 | e.writeInt(v) 397 | case reflect.Int64: 398 | v := int64(field.Int()) 399 | e.writeLong(v) 400 | case reflect.Bool: 401 | v := field.Bool() 402 | e.writeBoolean(v) 403 | case reflect.Map: 404 | v := field.Interface() 405 | //fmt.Println("Map", field.Type().Kind(), field.Interface()) 406 | e.writeMap(v) 407 | case reflect.Array, reflect.Slice: 408 | v := field.Interface() 409 | //fmt.Println("Slice", field.Type().Kind(), field.Interface()) 410 | e.WriteObject(v) 411 | case reflect.Int: 412 | v := int32(field.Int()) 413 | e.writeInt(v) 414 | } 415 | return newCodecError("writeField unspport kind " + kind.String()) 416 | } 417 | 418 | func (e *encoder) writeClsDef(typ reflect.Type, clsName string) (int, error) { 419 | e.writeBT(BC_OBJECT_DEF) 420 | e.writeString(clsName) 421 | fldList := make([]string, typ.NumField()) 422 | e.writeInt(int32(len(fldList))) 423 | for i := 0; i < len(fldList); i++ { 424 | str, _ := lowerName(typ.Field(i).Name) 425 | fldList[i] = str 426 | e.writeString(fldList[i]) 427 | } 428 | clsDef := ClassDef{clsName, fldList} 429 | l := len(e.clsDefList) 430 | e.clsDefList = append(e.clsDefList, clsDef) 431 | return l, nil 432 | } 433 | 434 | func lowerName(name string) (string, error) { 435 | if name[0] >= 'a' && name[0] <= 'c' { 436 | return name, nil 437 | } 438 | if name[0] >= 'A' && name[0] <= 'Z' { 439 | bs := make([]byte, len(name)) 440 | bs[0] = byte(name[0] + ASCII_GAP) 441 | copy(bs[1:], name[1:]) 442 | return string(bs), nil 443 | } else { 444 | return name, nil 445 | } 446 | 447 | } 448 | 449 | func (e *encoder) existClassDef(clsName string) (int, bool) { 450 | for i := 0; i < len(e.clsDefList); i++ { 451 | if strings.Compare(clsName, e.clsDefList[i].FullClassName) == 0 { 452 | return i, true 453 | } 454 | } 455 | return 0, false 456 | } 457 | -------------------------------------------------------------------------------- /encoder_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright 2012-2016 Viant. 4 | * * 5 | * * Licensed under the Apache License, Version 2.0 (the "License"); you may not 6 | * * use this file except in compliance with the License. You may obtain a copy of 7 | * * the License at 8 | * * 9 | * * http://www.apache.org/licenses/LICENSE-2.0 10 | * * 11 | * * Unless required by applicable law or agreed to in writing, software 12 | * * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | * * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | * * License for the specific language governing permissions and limitations under 15 | * * the License. 16 | * 17 | */ 18 | 19 | package hessian 20 | 21 | import ( 22 | "bytes" 23 | "fmt" 24 | "reflect" 25 | "strings" 26 | "testing" 27 | ) 28 | 29 | type P struct { 30 | X, Y, Z int 31 | Name string 32 | } 33 | 34 | type Box struct { 35 | Width int 36 | Height int 37 | Color string 38 | Open bool 39 | } 40 | 41 | type BB struct { 42 | Name string 43 | List []string 44 | Mp map[int32]string 45 | Pst P 46 | Number int32 47 | } 48 | 49 | func TestSerilazer(t *testing.T) { 50 | ts4 := []string{"t1", "t2", "t3"} 51 | mp1 := map[int32]string{1: "test1", 2: "test2", 3: "test3"} 52 | p := P{1, 2, 3, "ABC"} 53 | bb := BB{"AB", ts4, mp1, p, 4} 54 | gh := NewGoHessian(nil, nil) 55 | bt, _ := gh.ToBytes(bb) 56 | fmt.Println("bt", string(bt)) 57 | 58 | } 59 | 60 | func TestDecoder_Instance(t *testing.T) { 61 | ts4 := []string{"t1", "t2", "t3"} 62 | mp1 := map[int32]string{1: "test1", 2: "test2", 3: "test3"} 63 | p := P{1, 2, 3, "ABC"} 64 | bb := BB{"AB", ts4, mp1, p, 4} 65 | br := bytes.NewBuffer(nil) 66 | e := NewEncoder(br, nil) 67 | e.WriteObject(bb) 68 | fmt.Println("e", br) 69 | bt := bytes.NewReader(br.Bytes()) 70 | d := NewDecoder(bt, nil) 71 | d.RegisterType("BB", reflect.TypeOf(BB{})) 72 | d.RegisterType("P", reflect.TypeOf(P{})) 73 | it, err := d.ReadObject() 74 | if err != nil { 75 | fmt.Println("err", err) 76 | } 77 | fmt.Println("decode t", it, "bt len", len(br.Bytes())) 78 | } 79 | 80 | func TestEncoder_WriteObject(t *testing.T) { 81 | mp2 := make(map[int]string) 82 | mp2[1] = "test1" 83 | mp2[2] = "test2" 84 | mp2[3] = "test3" 85 | br := bytes.NewBuffer(nil) 86 | e7 := NewEncoder(br, nil) 87 | e7.WriteObject(mp2) 88 | fmt.Println("encode map buf->", string(br.Bytes()), len(br.Bytes()), br.Bytes()) 89 | bt2 := br.Bytes() 90 | br2 := bytes.NewReader(br.Bytes()) 91 | d7 := NewDecoder(br2, nil) 92 | t7, _ := d7.ReadObject() 93 | fmt.Println("decode map", t7, "bt2", len(bt2)) 94 | 95 | } 96 | 97 | func TestEncoder_WriteList(t *testing.T) { 98 | ts3 := [3]string{"t1", "t2", "t3"} 99 | br := bytes.NewBuffer(nil) 100 | e7 := NewEncoder(br, nil) 101 | e7.WriteObject(ts3) 102 | fmt.Println("encode array buf->", string(br.Bytes()), len(br.Bytes()), br.Bytes()) 103 | bt2 := br.Bytes() 104 | br2 := bytes.NewReader(br.Bytes()) 105 | d7 := NewDecoder(br2, nil) 106 | t7, _ := d7.ReadObject() 107 | fmt.Println("decode array", t7, "bt2", len(bt2)) 108 | 109 | } 110 | 111 | func TestEncoder_WriteString(t *testing.T) { 112 | str := "HessianSerializer" 113 | br := bytes.NewBuffer(nil) 114 | e7 := NewEncoder(br, nil) 115 | e7.WriteObject(str) 116 | bt2 := br.Bytes() 117 | br2 := bytes.NewReader(br.Bytes()) 118 | d7 := NewDecoder(br2, nil) 119 | t7, _ := d7.ReadObject() 120 | fmt.Println("decode string", t7, "bt2", len(bt2)) 121 | if strings.Compare(str, t7.(string)) == 0 { 122 | fmt.Println("succes for ", str) 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /hessian_test.go: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright 2012-2016 Viant. 4 | * * 5 | * * Licensed under the Apache License, Version 2.0 (the "License"); you may not 6 | * * use this file except in compliance with the License. You may obtain a copy of 7 | * * the License at 8 | * * 9 | * * http://www.apache.org/licenses/LICENSE-2.0 10 | * * 11 | * * Unless required by applicable law or agreed to in writing, software 12 | * * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | * * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | * * License for the specific language governing permissions and limitations under 15 | * * the License. 16 | * 17 | */ 18 | 19 | package hessian 20 | 21 | import ( 22 | "fmt" 23 | "testing" 24 | "reflect" 25 | ) 26 | 27 | type Person struct { 28 | firstName string 29 | lastName string 30 | } 31 | 32 | func TestSerializer(t *testing.T) { 33 | p := Person{"John","Doe"} 34 | gh := NewGoHessian(nil, nil) 35 | bt, _ := gh.ToBytes(p) 36 | p_new, _ := gh.ToObject(bt) 37 | fmt.Println("bt", string(bt)) 38 | reflect.DeepEqual(p, p_new) 39 | } 40 | -------------------------------------------------------------------------------- /serializer.go: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * * Copyright 2012-2016 Viant. 4 | * * 5 | * * Licensed under the Apache License, Version 2.0 (the "License"); you may not 6 | * * use this file except in compliance with the License. You may obtain a copy of 7 | * * the License at 8 | * * 9 | * * http://www.apache.org/licenses/LICENSE-2.0 10 | * * 11 | * * Unless required by applicable law or agreed to in writing, software 12 | * * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 13 | * * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 14 | * * License for the specific language governing permissions and limitations under 15 | * * the License. 16 | * 17 | */ 18 | 19 | package hessian 20 | 21 | import ( 22 | "bytes" 23 | "reflect" 24 | ) 25 | 26 | type Serializer interface { 27 | ToBytes(interface{}) ([]byte, error) 28 | ToObject([]byte) (interface{}, error) 29 | } 30 | 31 | type goHessian struct { 32 | typMap map[string]reflect.Type 33 | nameMap map[string]string 34 | } 35 | 36 | func NewGoHessian(typMap map[string]reflect.Type, nmeMap map[string]string) Serializer { 37 | if typMap == nil { 38 | typMap = make(map[string]reflect.Type, 17) 39 | } 40 | if nmeMap == nil { 41 | nmeMap = make(map[string]string, 17) 42 | } 43 | return &goHessian{typMap, nmeMap} 44 | } 45 | 46 | func (gh *goHessian) ToBytes(object interface{}) ([]byte, error) { 47 | btBufs := bytes.NewBuffer(nil) 48 | e := NewEncoder(btBufs, gh.nameMap) 49 | _, err := e.WriteObject(object) 50 | if err != nil { 51 | return nil, err 52 | } else { 53 | return btBufs.Bytes(), nil 54 | } 55 | } 56 | 57 | func (gh *goHessian) ToObject(ins []byte) (interface{}, error) { 58 | btBufs := bytes.NewReader(ins) 59 | d := NewDecoder(btBufs, gh.typMap) 60 | return d.ReadObject() 61 | } 62 | --------------------------------------------------------------------------------