github.com/amazechain/amc@v0.1.3/internal/avm/rlp/encode.go (about) 1 // Copyright 2023 The AmazeChain Authors 2 // This file is part of the AmazeChain library. 3 // 4 // The AmazeChain library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The AmazeChain library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the AmazeChain library. If not, see <http://www.gnu.org/licenses/>. 16 17 package rlp 18 19 import ( 20 "encoding/binary" 21 "fmt" 22 "io" 23 "math/big" 24 "math/bits" 25 "reflect" 26 "sync" 27 28 "github.com/holiman/uint256" 29 ) 30 31 // https://github.com/ethereum/wiki/wiki/RLP 32 const ( 33 // EmptyStringCode is the RLP code for empty strings. 34 EmptyStringCode = 0x80 35 // EmptyListCode is the RLP code for empty lists. 36 EmptyListCode = 0xC0 37 ) 38 39 var ( 40 // Common encoded values. 41 // These are useful when implementing EncodeRLP. 42 EmptyString = []byte{EmptyStringCode} 43 EmptyList = []byte{EmptyListCode} 44 ) 45 46 // Encoder is implemented by types that require custom 47 // encoding rules or want to encode private fields. 48 type Encoder interface { 49 // EncodeRLP should write the RLP encoding of its receiver to w. 50 // If the implementation is a pointer method, it may also be 51 // called for nil pointers. 52 // 53 // Implementations should generate valid RLP. The data written is 54 // not verified at the moment, but a future version might. It is 55 // recommended to write only a single value but writing multiple 56 // values or no value at all is also permitted. 57 EncodeRLP(io.Writer) error 58 } 59 60 // Encode writes the RLP encoding of val to w. Note that Encode may 61 // perform many small writes in some cases. Consider making w 62 // buffered. 63 // 64 // Please see package-level documentation of encoding rules. 65 func Encode(w io.Writer, val interface{}) error { 66 if outer, ok := w.(*encbuf); ok { 67 // Encode was called by some type's EncodeRLP. 68 // Avoid copying by writing to the outer encbuf directly. 69 return outer.encode(val) 70 } 71 eb := encbufPool.Get().(*encbuf) 72 defer encbufPool.Put(eb) 73 eb.reset() 74 if err := eb.encode(val); err != nil { 75 return err 76 } 77 return eb.toWriter(w) 78 } 79 80 func Write(w io.Writer, val []byte) error { 81 if outer, ok := w.(*encbuf); ok { 82 // Encode was called by some type's EncodeRLP. 83 // Avoid copying by writing to the outer encbuf directly. 84 _, err := outer.Write(val) 85 return err 86 } 87 88 _, err := w.Write(val) 89 return err 90 } 91 92 // EncodeToBytes returns the RLP encoding of val. 93 // Please see package-level documentation for the encoding rules. 94 func EncodeToBytes(val interface{}) ([]byte, error) { 95 eb := encbufPool.Get().(*encbuf) 96 defer encbufPool.Put(eb) 97 eb.reset() 98 if err := eb.encode(val); err != nil { 99 return nil, err 100 } 101 return eb.toBytes(), nil 102 } 103 104 // EncodeToReader returns a reader from which the RLP encoding of val 105 // can be read. The returned size is the total size of the encoded 106 // data. 107 // 108 // Please see the documentation of Encode for the encoding rules. 109 func EncodeToReader(val interface{}) (size int, r io.Reader, err error) { 110 eb := encbufPool.Get().(*encbuf) 111 eb.reset() 112 if err := eb.encode(val); err != nil { 113 return 0, nil, err 114 } 115 return eb.size(), &encReader{buf: eb}, nil 116 } 117 118 type listhead struct { 119 offset int // index of this header in string data 120 size int // total size of encoded data (including list headers) 121 } 122 123 // encode writes head to the given buffer, which must be at least 124 // 9 bytes long. It returns the encoded bytes. 125 func (head *listhead) encode(buf []byte) []byte { 126 return buf[:puthead(buf, 0xC0, 0xF7, uint64(head.size))] 127 } 128 129 // headsize returns the size of a list or string header 130 // for a value of the given size. 131 func headsize(size uint64) int { 132 if size < 56 { 133 return 1 134 } 135 return 1 + intsize(size) 136 } 137 138 // puthead writes a list or string header to buf. 139 // buf must be at least 9 bytes long. 140 func puthead(buf []byte, smalltag, largetag byte, size uint64) int { 141 if size < 56 { 142 buf[0] = smalltag + byte(size) 143 return 1 144 } 145 sizesize := putint(buf[1:], size) 146 buf[0] = largetag + byte(sizesize) 147 return sizesize + 1 148 } 149 150 type encbuf struct { 151 str []byte // string data, contains everything except list headers 152 lheads []listhead // all list headers 153 lhsize int // sum of sizes of all encoded list headers 154 sizebuf [9]byte // auxiliary buffer for uint encoding 155 bufvalue reflect.Value // used in writeByteArrayCopy 156 } 157 158 // encbufs are pooled. 159 var encbufPool = sync.Pool{ 160 New: func() interface{} { 161 var bytes []byte 162 return &encbuf{bufvalue: reflect.ValueOf(&bytes).Elem()} 163 }, 164 } 165 166 func (w *encbuf) reset() { 167 w.lhsize = 0 168 w.str = w.str[:0] 169 w.lheads = w.lheads[:0] 170 } 171 172 // encbuf implements io.Writer so it can be passed it into EncodeRLP. 173 func (w *encbuf) Write(b []byte) (int, error) { 174 w.str = append(w.str, b...) 175 return len(b), nil 176 } 177 178 func (w *encbuf) encode(val interface{}) error { 179 rval := reflect.ValueOf(val) 180 writer, err := cachedWriter(rval.Type()) 181 if err != nil { 182 return err 183 } 184 return writer(rval, w) 185 } 186 187 func (w *encbuf) encodeStringHeader(size int) { 188 if size < 56 { 189 w.str = append(w.str, EmptyStringCode+byte(size)) 190 } else { 191 sizesize := putint(w.sizebuf[1:], uint64(size)) 192 w.sizebuf[0] = 0xB7 + byte(sizesize) 193 w.str = append(w.str, w.sizebuf[:sizesize+1]...) 194 } 195 } 196 197 func (w *encbuf) encodeString(b []byte) { 198 if len(b) == 1 && b[0] <= 0x7F { 199 // fits single byte, no string header 200 w.str = append(w.str, b[0]) 201 } else { 202 w.encodeStringHeader(len(b)) 203 w.str = append(w.str, b...) 204 } 205 } 206 207 func (w *encbuf) encodeUint(i uint64) { 208 if i == 0 { 209 w.str = append(w.str, 0x80) 210 } else if i < 128 { 211 // fits single byte 212 w.str = append(w.str, byte(i)) 213 } else { 214 s := putint(w.sizebuf[1:], i) 215 w.sizebuf[0] = 0x80 + byte(s) 216 w.str = append(w.str, w.sizebuf[:s+1]...) 217 } 218 } 219 220 // list adds a new list header to the header stack. It returns the index 221 // of the header. The caller must call listEnd with this index after encoding 222 // the content of the list. 223 func (w *encbuf) list() int { 224 w.lheads = append(w.lheads, listhead{offset: len(w.str), size: w.lhsize}) 225 return len(w.lheads) - 1 226 } 227 228 func (w *encbuf) listEnd(index int) { 229 lh := &w.lheads[index] 230 lh.size = w.size() - lh.offset - lh.size 231 if lh.size < 56 { 232 w.lhsize++ // length encoded into kind tag 233 } else { 234 w.lhsize += 1 + intsize(uint64(lh.size)) 235 } 236 } 237 238 func (w *encbuf) size() int { 239 return len(w.str) + w.lhsize 240 } 241 242 func (w *encbuf) toBytes() []byte { 243 out := make([]byte, w.size()) 244 strpos := 0 245 pos := 0 246 for _, head := range w.lheads { 247 // write string data before header 248 n := copy(out[pos:], w.str[strpos:head.offset]) 249 pos += n 250 strpos += n 251 // write the header 252 enc := head.encode(out[pos:]) 253 pos += len(enc) 254 } 255 // copy string data after the last list header 256 copy(out[pos:], w.str[strpos:]) 257 return out 258 } 259 260 func (w *encbuf) toWriter(out io.Writer) (err error) { 261 strpos := 0 262 for _, head := range w.lheads { 263 // write string data before header 264 if head.offset-strpos > 0 { 265 n, nErr := out.Write(w.str[strpos:head.offset]) 266 strpos += n 267 if nErr != nil { 268 return nErr 269 } 270 } 271 // write the header 272 enc := head.encode(w.sizebuf[:]) 273 if _, wErr := out.Write(enc); wErr != nil { 274 return wErr 275 } 276 } 277 if strpos < len(w.str) { 278 // write string data after the last list header 279 _, err = out.Write(w.str[strpos:]) 280 } 281 return err 282 } 283 284 // encReader is the io.Reader returned by EncodeToReader. 285 // It releases its encbuf at EOF. 286 type encReader struct { 287 buf *encbuf // the buffer we're reading from. this is nil when we're at EOF. 288 lhpos int // index of list header that we're reading 289 strpos int // current position in string buffer 290 piece []byte // next piece to be read 291 } 292 293 func (r *encReader) Read(b []byte) (n int, err error) { 294 for { 295 if r.piece = r.next(); r.piece == nil { 296 // Put the encode buffer back into the pool at EOF when it 297 // is first encountered. Subsequent calls still return EOF 298 // as the error but the buffer is no longer valid. 299 if r.buf != nil { 300 encbufPool.Put(r.buf) 301 r.buf = nil 302 } 303 return n, io.EOF 304 } 305 nn := copy(b[n:], r.piece) 306 n += nn 307 if nn < len(r.piece) { 308 // piece didn't fit, see you next time. 309 r.piece = r.piece[nn:] 310 return n, nil 311 } 312 r.piece = nil 313 } 314 } 315 316 // next returns the next piece of data to be read. 317 // it returns nil at EOF. 318 func (r *encReader) next() []byte { 319 switch { 320 case r.buf == nil: 321 return nil 322 323 case r.piece != nil: 324 // There is still data available for reading. 325 return r.piece 326 327 case r.lhpos < len(r.buf.lheads): 328 // We're before the last list header. 329 head := r.buf.lheads[r.lhpos] 330 sizebefore := head.offset - r.strpos 331 if sizebefore > 0 { 332 // String data before header. 333 p := r.buf.str[r.strpos:head.offset] 334 r.strpos += sizebefore 335 return p 336 } 337 r.lhpos++ 338 return head.encode(r.buf.sizebuf[:]) 339 340 case r.strpos < len(r.buf.str): 341 // String data at the end, after all list headers. 342 p := r.buf.str[r.strpos:] 343 r.strpos = len(r.buf.str) 344 return p 345 346 default: 347 return nil 348 } 349 } 350 351 var encoderInterface = reflect.TypeOf(new(Encoder)).Elem() 352 353 // makeWriter creates a writer function for the given type. 354 func makeWriter(typ reflect.Type, ts tags) (writer, error) { 355 kind := typ.Kind() 356 switch { 357 case typ == rawValueType: 358 return writeRawValue, nil 359 case typ.AssignableTo(reflect.PtrTo(bigInt)): 360 return writeBigIntPtr, nil 361 case typ.AssignableTo(bigInt): 362 return writeBigIntNoPtr, nil 363 case typ.AssignableTo(reflect.PtrTo(uint256Int)): 364 return writeUint256Ptr, nil 365 case typ.AssignableTo(uint256Int): 366 return writeUint256NoPtr, nil 367 case kind == reflect.Ptr: 368 return makePtrWriter(typ, ts) 369 case reflect.PtrTo(typ).Implements(encoderInterface): 370 return makeEncoderWriter(typ), nil 371 case isUint(kind): 372 return writeUint, nil 373 case kind == reflect.Bool: 374 return writeBool, nil 375 case kind == reflect.String: 376 return writeString, nil 377 case kind == reflect.Slice && isByte(typ.Elem()): 378 return writeBytes, nil 379 case kind == reflect.Array && isByte(typ.Elem()): 380 return makeByteArrayWriter(typ), nil 381 case kind == reflect.Slice || kind == reflect.Array: 382 return makeSliceWriter(typ, ts) 383 case kind == reflect.Struct: 384 return makeStructWriter(typ) 385 case kind == reflect.Interface: 386 return writeInterface, nil 387 default: 388 return nil, fmt.Errorf("rlp: type %v is not RLP-serializable", typ) 389 } 390 } 391 392 func writeRawValue(val reflect.Value, w *encbuf) error { 393 w.str = append(w.str, val.Bytes()...) 394 return nil 395 } 396 397 func writeUint(val reflect.Value, w *encbuf) error { 398 w.encodeUint(val.Uint()) 399 return nil 400 } 401 402 func writeBool(val reflect.Value, w *encbuf) error { 403 if val.Bool() { 404 w.str = append(w.str, 0x01) 405 } else { 406 w.str = append(w.str, EmptyStringCode) 407 } 408 return nil 409 } 410 411 func writeBigIntPtr(val reflect.Value, w *encbuf) error { 412 ptr := val.Interface().(*big.Int) 413 if ptr == nil { 414 w.str = append(w.str, EmptyStringCode) 415 return nil 416 } 417 return writeBigInt(ptr, w) 418 } 419 420 func writeBigIntNoPtr(val reflect.Value, w *encbuf) error { 421 i := val.Interface().(big.Int) 422 return writeBigInt(&i, w) 423 } 424 425 // wordBytes is the number of bytes in a big.Word 426 const wordBytes = (32 << (uint64(^big.Word(0)) >> 63)) / 8 427 428 func writeBigInt(i *big.Int, w *encbuf) error { 429 if i.Sign() == -1 { 430 return fmt.Errorf("rlp: cannot encode negative *big.Int") 431 } 432 bitlen := i.BitLen() 433 if bitlen <= 64 { 434 w.encodeUint(i.Uint64()) 435 return nil 436 } 437 // Integer is larger than 64 bits, encode from i.Bits(). 438 // The minimal byte length is bitlen rounded up to the next 439 // multiple of 8, divided by 8. 440 length := ((bitlen + 7) & -8) >> 3 441 w.encodeStringHeader(length) 442 w.str = append(w.str, make([]byte, length)...) 443 index := length 444 buf := w.str[len(w.str)-length:] 445 for _, d := range i.Bits() { 446 for j := 0; j < wordBytes && index > 0; j++ { 447 index-- 448 buf[index] = byte(d) 449 d >>= 8 450 } 451 } 452 return nil 453 } 454 455 func writeUint256Ptr(val reflect.Value, w *encbuf) error { 456 ptr := val.Interface().(*uint256.Int) 457 if ptr == nil { 458 w.str = append(w.str, EmptyStringCode) 459 return nil 460 } 461 return writeUint256(ptr, w) 462 } 463 464 func writeUint256NoPtr(val reflect.Value, w *encbuf) error { 465 i := val.Interface().(uint256.Int) 466 return writeUint256(&i, w) 467 } 468 469 func writeUint256(i *uint256.Int, w *encbuf) error { 470 if i.IsZero() { 471 w.str = append(w.str, EmptyStringCode) 472 } else if i.LtUint64(0x80) { 473 w.str = append(w.str, byte(i.Uint64())) 474 } else { 475 n := i.ByteLen() 476 w.str = append(w.str, EmptyStringCode+byte(n)) 477 pos := len(w.str) 478 w.str = append(w.str, make([]byte, n)...) 479 i.WriteToSlice(w.str[pos:]) 480 } 481 return nil 482 } 483 484 func writeBytes(val reflect.Value, w *encbuf) error { 485 w.encodeString(val.Bytes()) 486 return nil 487 } 488 489 var byteType = reflect.TypeOf(byte(0)) 490 491 func makeByteArrayWriter(typ reflect.Type) writer { 492 length := typ.Len() 493 if length == 0 { 494 return writeLengthZeroByteArray 495 } else if length == 1 { 496 return writeLengthOneByteArray 497 } 498 if typ.Elem() != byteType { 499 return writeNamedByteArray 500 } 501 return func(val reflect.Value, w *encbuf) error { 502 writeByteArrayCopy(length, val, w) 503 return nil 504 } 505 } 506 507 func writeLengthZeroByteArray(val reflect.Value, w *encbuf) error { 508 w.str = append(w.str, 0x80) 509 return nil 510 } 511 512 func writeLengthOneByteArray(val reflect.Value, w *encbuf) error { 513 b := byte(val.Index(0).Uint()) 514 if b <= 0x7f { 515 w.str = append(w.str, b) 516 } else { 517 w.str = append(w.str, 0x81, b) 518 } 519 return nil 520 } 521 522 // writeByteArrayCopy encodes byte arrays using reflect.Copy. This is 523 // the fast path for [N]byte where N > 1. 524 func writeByteArrayCopy(length int, val reflect.Value, w *encbuf) { 525 w.encodeStringHeader(length) 526 offset := len(w.str) 527 w.str = append(w.str, make([]byte, length)...) 528 w.bufvalue.SetBytes(w.str[offset:]) 529 reflect.Copy(w.bufvalue, val) 530 } 531 532 // writeNamedByteArray encodes byte arrays with named element type. 533 // This exists because reflect.Copy can't be used with such types. 534 func writeNamedByteArray(val reflect.Value, w *encbuf) error { 535 if !val.CanAddr() { 536 // Slice requires the value to be addressable. 537 // Make it addressable by copying. 538 copy := reflect.New(val.Type()).Elem() 539 copy.Set(val) 540 val = copy 541 } 542 size := val.Len() 543 slice := val.Slice(0, size).Bytes() 544 w.encodeString(slice) 545 return nil 546 } 547 548 func writeString(val reflect.Value, w *encbuf) error { 549 s := val.String() 550 if len(s) == 1 && s[0] <= 0x7f { 551 // fits single byte, no string header 552 w.str = append(w.str, s[0]) 553 } else { 554 w.encodeStringHeader(len(s)) 555 w.str = append(w.str, s...) 556 } 557 return nil 558 } 559 560 func writeInterface(val reflect.Value, w *encbuf) error { 561 if val.IsNil() { 562 // Write empty list. This is consistent with the previous RLP 563 // encoder that we had and should therefore avoid any 564 // problems. 565 w.str = append(w.str, EmptyListCode) 566 return nil 567 } 568 eval := val.Elem() 569 wtr, wErr := cachedWriter(eval.Type()) 570 if wErr != nil { 571 return wErr 572 } 573 return wtr(eval, w) 574 } 575 576 func makeSliceWriter(typ reflect.Type, ts tags) (writer, error) { 577 etypeinfo := cachedTypeInfo1(typ.Elem(), tags{}) 578 if etypeinfo.writerErr != nil { 579 return nil, etypeinfo.writerErr 580 } 581 writer := func(val reflect.Value, w *encbuf) error { 582 if !ts.tail { 583 defer w.listEnd(w.list()) 584 } 585 vlen := val.Len() 586 for i := 0; i < vlen; i++ { 587 if err := etypeinfo.writer(val.Index(i), w); err != nil { 588 return err 589 } 590 } 591 return nil 592 } 593 return writer, nil 594 } 595 596 func makeStructWriter(typ reflect.Type) (writer, error) { 597 fields, err := structFields(typ) 598 if err != nil { 599 return nil, err 600 } 601 for _, f := range fields { 602 if f.info.writerErr != nil { 603 return nil, structFieldError{typ, f.index, f.info.writerErr} 604 } 605 } 606 607 var writer writer 608 firstOptionalField := firstOptionalField(fields) 609 if firstOptionalField == len(fields) { 610 // This is the writer function for structs without any optional fields. 611 writer = func(val reflect.Value, w *encbuf) error { 612 lh := w.list() 613 for _, f := range fields { 614 if err := f.info.writer(val.Field(f.index), w); err != nil { 615 return err 616 } 617 } 618 w.listEnd(lh) 619 return nil 620 } 621 } else { 622 // If there are any "optional" fields, the writer needs to perform additional 623 // checks to determine the output list length. 624 writer = func(val reflect.Value, w *encbuf) error { 625 lastField := len(fields) - 1 626 for ; lastField >= firstOptionalField; lastField-- { 627 if !val.Field(fields[lastField].index).IsZero() { 628 break 629 } 630 } 631 lh := w.list() 632 for i := 0; i <= lastField; i++ { 633 if err := fields[i].info.writer(val.Field(fields[i].index), w); err != nil { 634 return err 635 } 636 } 637 w.listEnd(lh) 638 return nil 639 } 640 } 641 return writer, nil 642 } 643 644 func makePtrWriter(typ reflect.Type, ts tags) (writer, error) { 645 etypeinfo := cachedTypeInfo1(typ.Elem(), tags{}) 646 if etypeinfo.writerErr != nil { 647 return nil, etypeinfo.writerErr 648 } 649 // Determine how to encode nil pointers. 650 var nilKind Kind 651 if ts.nilOK { 652 nilKind = ts.nilKind // use struct tag if provided 653 } else { 654 nilKind = defaultNilKind(typ.Elem()) 655 } 656 657 writer := func(val reflect.Value, w *encbuf) error { 658 if val.IsNil() { 659 if nilKind == String { 660 w.str = append(w.str, EmptyStringCode) 661 } else { 662 w.listEnd(w.list()) 663 } 664 return nil 665 } 666 return etypeinfo.writer(val.Elem(), w) 667 } 668 return writer, nil 669 } 670 671 func makeEncoderWriter(typ reflect.Type) writer { 672 if typ.Implements(encoderInterface) { 673 return func(val reflect.Value, w *encbuf) error { 674 return val.Interface().(Encoder).EncodeRLP(w) 675 } 676 } 677 w := func(val reflect.Value, w *encbuf) error { 678 if !val.CanAddr() { 679 // package json simply doesn't call MarshalJSON for this case, but encodes the 680 // value as if it didn't implement the interface. We don't want to handle it that 681 // way. 682 return fmt.Errorf("rlp: unadressable value of type %v, EncodeRLP is pointer method", val.Type()) 683 } 684 return val.Addr().Interface().(Encoder).EncodeRLP(w) 685 } 686 return w 687 } 688 689 // putint writes i to the beginning of b in big endian byte 690 // order, using the least number of bytes needed to represent i. 691 func putint(b []byte, i uint64) (size int) { 692 switch { 693 case i < (1 << 8): 694 b[0] = byte(i) 695 return 1 696 case i < (1 << 16): 697 b[0] = byte(i >> 8) 698 b[1] = byte(i) 699 return 2 700 case i < (1 << 24): 701 b[0] = byte(i >> 16) 702 b[1] = byte(i >> 8) 703 b[2] = byte(i) 704 return 3 705 case i < (1 << 32): 706 b[0] = byte(i >> 24) 707 b[1] = byte(i >> 16) 708 b[2] = byte(i >> 8) 709 b[3] = byte(i) 710 return 4 711 case i < (1 << 40): 712 b[0] = byte(i >> 32) 713 b[1] = byte(i >> 24) 714 b[2] = byte(i >> 16) 715 b[3] = byte(i >> 8) 716 b[4] = byte(i) 717 return 5 718 case i < (1 << 48): 719 b[0] = byte(i >> 40) 720 b[1] = byte(i >> 32) 721 b[2] = byte(i >> 24) 722 b[3] = byte(i >> 16) 723 b[4] = byte(i >> 8) 724 b[5] = byte(i) 725 return 6 726 case i < (1 << 56): 727 b[0] = byte(i >> 48) 728 b[1] = byte(i >> 40) 729 b[2] = byte(i >> 32) 730 b[3] = byte(i >> 24) 731 b[4] = byte(i >> 16) 732 b[5] = byte(i >> 8) 733 b[6] = byte(i) 734 return 7 735 default: 736 b[0] = byte(i >> 56) 737 b[1] = byte(i >> 48) 738 b[2] = byte(i >> 40) 739 b[3] = byte(i >> 32) 740 b[4] = byte(i >> 24) 741 b[5] = byte(i >> 16) 742 b[6] = byte(i >> 8) 743 b[7] = byte(i) 744 return 8 745 } 746 } 747 748 // intsize computes the minimum number of bytes required to store i. 749 func intsize(i uint64) (size int) { 750 return (bits.Len64(i) + 7) / 8 751 } 752 753 func IntLenExcludingHead(i uint64) int { 754 if i < 0x80 { 755 return 0 756 } 757 return intsize(i) 758 } 759 760 func BigIntLenExcludingHead(i *big.Int) int { 761 bitLen := i.BitLen() 762 if bitLen < 8 { 763 return 0 764 } 765 return (bitLen + 7) / 8 766 } 767 768 func Uint256LenExcludingHead(i *uint256.Int) int { 769 bitLen := i.BitLen() 770 if bitLen < 8 { 771 return 0 772 } 773 return (bitLen + 7) / 8 774 } 775 776 // precondition: len(buffer) >= 9 777 func EncodeInt(i uint64, w io.Writer, buffer []byte) error { 778 if 0 < i && i < 0x80 { 779 buffer[0] = byte(i) 780 _, err := w.Write(buffer[:1]) 781 return err 782 } 783 784 binary.BigEndian.PutUint64(buffer[1:], i) 785 size := intsize(i) 786 buffer[8-size] = 0x80 + byte(size) 787 _, err := w.Write(buffer[8-size : 9]) 788 return err 789 } 790 791 func EncodeBigInt(i *big.Int, w io.Writer, buffer []byte) error { 792 bitLen := 0 // treat nil as 0 793 if i != nil { 794 bitLen = i.BitLen() 795 } 796 if bitLen < 8 { 797 if bitLen > 0 { 798 buffer[0] = byte(i.Uint64()) 799 } else { 800 buffer[0] = 0x80 801 } 802 _, err := w.Write(buffer[:1]) 803 return err 804 } 805 806 size := (bitLen + 7) / 8 807 buffer[0] = 0x80 + byte(size) 808 i.FillBytes(buffer[1 : 1+size]) 809 _, err := w.Write(buffer[:1+size]) 810 return err 811 } 812 813 func EncodeString(s []byte, w io.Writer, buffer []byte) error { 814 switch len(s) { 815 case 0: 816 buffer[0] = 128 817 if _, err := w.Write(buffer[:1]); err != nil { 818 return err 819 } 820 case 1: 821 if s[0] >= 128 { 822 buffer[0] = 129 823 if _, err := w.Write(buffer[:1]); err != nil { 824 return err 825 } 826 } 827 if _, err := w.Write(s); err != nil { 828 return err 829 } 830 default: 831 if err := EncodeStringSizePrefix(len(s), w, buffer); err != nil { 832 return err 833 } 834 if _, err := w.Write(s); err != nil { 835 return err 836 } 837 } 838 return nil 839 } 840 841 func EncodeStringSizePrefix(size int, w io.Writer, buffer []byte) error { 842 if size >= 56 { 843 beSize := (bits.Len(uint(size)) + 7) / 8 844 binary.BigEndian.PutUint64(buffer[1:], uint64(size)) 845 buffer[8-beSize] = byte(beSize) + 183 846 if _, err := w.Write(buffer[8-beSize : 9]); err != nil { 847 return err 848 } 849 } else { 850 buffer[0] = byte(size) + 128 851 if _, err := w.Write(buffer[:1]); err != nil { 852 return err 853 } 854 } 855 return nil 856 }