@@ -32,6 +32,48 @@ type Encoder interface {
3232 EncodeRLP (io.Writer ) error
3333}
3434
35+ // Flat wraps a value (which must encode as a list) so
36+ // it encodes as the list's elements.
37+ //
38+ // Example: suppose you have defined a type
39+ //
40+ // type foo struct { A, B uint }
41+ //
42+ // Under normal encoding rules,
43+ //
44+ // rlp.Encode(foo{1, 2}) --> 0xC20102
45+ //
46+ // This function can help you achieve the following encoding:
47+ //
48+ // rlp.Encode(rlp.Flat(foo{1, 2})) --> 0x0102
49+ func Flat (val interface {}) Encoder {
50+ return flatenc {val }
51+ }
52+
53+ type flatenc struct { val interface {} }
54+
55+ func (e flatenc ) EncodeRLP (out io.Writer ) error {
56+ // record current output position
57+ var (
58+ eb = out .(* encbuf )
59+ prevstrsize = len (eb .str )
60+ prevnheads = len (eb .lheads )
61+ )
62+ if err := eb .encode (e .val ); err != nil {
63+ return err
64+ }
65+ // check that a new list header has appeared
66+ if len (eb .lheads ) == prevnheads || eb .lheads [prevnheads ].offset == prevstrsize - 1 {
67+ return fmt .Errorf ("rlp.Flat: %T did not encode as list" , e .val )
68+ }
69+ // remove the new list header
70+ newhead := eb .lheads [prevnheads ]
71+ copy (eb .lheads [prevnheads :], eb .lheads [prevnheads + 1 :])
72+ eb .lheads = eb .lheads [:len (eb .lheads )- 1 ]
73+ eb .lhsize -= newhead .tagsize ()
74+ return nil
75+ }
76+
3577// Encode writes the RLP encoding of val to w. Note that Encode may
3678// perform many small writes in some cases. Consider making w
3779// buffered.
@@ -123,6 +165,13 @@ func (head *listhead) encode(buf []byte) []byte {
123165 }
124166}
125167
168+ func (head * listhead ) tagsize () int {
169+ if head .size < 56 {
170+ return 1
171+ }
172+ return 1 + intsize (uint64 (head .size ))
173+ }
174+
126175func newencbuf () * encbuf {
127176 return & encbuf {sizebuf : make ([]byte , 9 )}
128177}
0 commit comments