Skip to content

Commit

Permalink
Struct encoding
Browse files Browse the repository at this point in the history
  • Loading branch information
2tvenom committed Feb 13, 2014
1 parent 74b30a9 commit cbe4b94
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 4 deletions.
18 changes: 14 additions & 4 deletions src/cbor.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,26 @@ package main
import (
"fmt"
"cbor"
"io/ioutil"
// "io/ioutil"
// "bytes"
)

type Vector struct {
X, Y, Z int
}

func main() {
buff, _ := ioutil.ReadFile("/tmp/cbor")
// var buffTest bytes.Buffer
//
// encoder := cbor.NewEncoder(&buffTest)
// encoder.Encode(Vector{1,2,3})
v := Vector{1,2,3}
buff, error := cbor.Encode(v)

decodedData, error := cbor.Decode(&buff)
if error != nil {
fmt.Errorf("Error decoding %s", error)
} else {
fmt.Printf("Variable = %v\n", decodedData)
fmt.Printf("Variable Hex = % x\n", buff)
fmt.Printf("Variable = %v\n", buff)
}
}
44 changes: 44 additions & 0 deletions src/cbor/cbor.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"bytes"
"unicode/utf8"
"reflect"
"strings"
)

const (
Expand Down Expand Up @@ -215,6 +216,8 @@ func Encode(variable interface{}) ([]byte, error) {
return encodeArray(variable)
case reflect.Map:
return encodeMap(variable)
case reflect.Struct:
return encodeStruct(variable)
case reflect.Bool:
return encodeBool(variable.(bool))
case reflect.Float32:
Expand Down Expand Up @@ -303,6 +306,47 @@ func encodeArray(variable interface{}) ([]byte, error) {
return buff, nil
}

func encodeStruct(variable interface{}) ([]byte, error) {
majorType := majorTypeMap

inputStructValue:= reflect.ValueOf(variable)
inputStructType:= inputStructValue.Type()

length := inputStructValue.NumField()

buff, err := packNumber(majorType, uint64(length))

if err != nil {
return nil, err
}

//struct encode
for i:=0; i<length; i++ {
fieldType := inputStructType.Field(i)
if fieldType.PkgPath != "" {
continue
}

keyBuff, keyErr := Encode(strings.ToLower(fieldType.Name))

if keyErr != nil {
return nil, keyErr
}

buff = append(buff, keyBuff...)

elementBuff, elemErr := Encode(inputStructValue.Field(i).Interface())

if elemErr != nil {
return nil, elemErr
}

buff = append(buff, elementBuff...)
}

return buff, nil
}

/**
Encode map to CBOR binary string
*/
Expand Down
18 changes: 18 additions & 0 deletions src/cbor/cborEncode.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package cbor

import (
"bytes"

)

type cborEncode struct {
buff *bytes.Buffer
}

func NewEncoder(buff *bytes.Buffer) (cborEncode){
return cborEncode{buff}
}

func (encoder *cborEncode) Encode(value interface{}) {

}

0 comments on commit cbe4b94

Please sign in to comment.