diff options
author | obscuren <obscuren@obscura.com> | 2013-12-28 06:48:44 +0800 |
---|---|---|
committer | obscuren <obscuren@obscura.com> | 2013-12-28 06:48:44 +0800 |
commit | 0f656652e6d76deebcfc7834923adf99eadc050f (patch) | |
tree | 7909794c5b829261452c6156f33876528810e2ea /rlp.go | |
parent | 323ba36869126520c294b6c8acacfa9877cde5c7 (diff) | |
download | go-tangerine-0f656652e6d76deebcfc7834923adf99eadc050f.tar.gz go-tangerine-0f656652e6d76deebcfc7834923adf99eadc050f.tar.zst go-tangerine-0f656652e6d76deebcfc7834923adf99eadc050f.zip |
Implemented decoding rlp
Diffstat (limited to 'rlp.go')
-rw-r--r-- | rlp.go | 51 |
1 files changed, 47 insertions, 4 deletions
@@ -1,7 +1,7 @@ package main import ( - _"fmt" + "fmt" "bytes" "math" ) @@ -40,11 +40,53 @@ func FromBin(data []byte) uint64 { return FromBin(data[:len(data)-1]) * 256 + uint64(data[len(data)-1]) } -func Decode(data []byte, pos int) { +func Decode(data []byte, pos int) (interface{}, int) { char := int(data[pos]) + slice := make([]interface{}, 0) switch { case char < 24: + return append(slice, data[pos]), pos + 1 + case char < 56: + b := int(data[pos]) - 23 + return FromBin(data[pos+1 : pos+1+b]), pos + 1 + b + case char < 64: + b := int(data[pos]) - 55 + b2 := int(FromBin(data[pos+1 : pos+1+b])) + return FromBin(data[pos+1+b : pos+1+b+b2]), pos+1+b+b2 + case char < 120: + b := int(data[pos]) - 64 + return data[pos+1:pos+1+b], pos+1+b + case char < 128: + b := int(data[pos]) - 119 + b2 := int(FromBin(data[pos+1 : pos+1+b])) + return data[pos+1+b : pos+1+b+b2], pos+1+b+b2 + case char < 184: + b := int(data[pos]) - 128 + pos++ + for i := 0; i < b; i++ { + var obj interface{} + + obj, pos = Decode(data, pos) + slice = append(slice, obj) + } + return slice, pos + case char < 192: + b := int(data[pos]) - 183 + //b2 := int(FromBin(data[pos+1 : pos+1+b])) (ref imprementation has an unused variable) + pos = pos+1+b + for i := 0; i < b; i++ { + var obj interface{} + + obj, pos = Decode(data, pos) + slice = append(slice, obj) + } + return slice, pos + + default: + panic(fmt.Sprintf("byte not supported: %q", char)) } + + return slice, 0 } func Encode(object interface{}) []byte { @@ -86,10 +128,11 @@ func Encode(object interface{}) []byte { // Inline function for writing the slice header WriteSliceHeader := func(length int) { if length < 56 { - buff.WriteString(string(length + 128)) + buff.WriteByte(byte(length + 128)) } else { b2 := ToBin(uint64(length), 0) - buff.WriteString(string(len(b2) + 183) + b2) + buff.WriteByte(byte(len(b2) + 183)) + buff.WriteString(b2) } } |