read_write.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. // Copyright 2014 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum 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. // go-ethereum 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 go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. package rle
  17. import (
  18. "bytes"
  19. "errors"
  20. "github.com/ethereum/go-ethereum/crypto"
  21. )
  22. const (
  23. token byte = 0xfe
  24. emptyShaToken = 0xfd
  25. emptyListShaToken = 0xfe
  26. tokenToken = 0xff
  27. )
  28. var empty = crypto.Sha3([]byte(""))
  29. var emptyList = crypto.Sha3([]byte{0x80})
  30. func Decompress(dat []byte) ([]byte, error) {
  31. buf := new(bytes.Buffer)
  32. for i := 0; i < len(dat); i++ {
  33. if dat[i] == token {
  34. if i+1 < len(dat) {
  35. switch dat[i+1] {
  36. case emptyShaToken:
  37. buf.Write(empty)
  38. case emptyListShaToken:
  39. buf.Write(emptyList)
  40. case tokenToken:
  41. buf.WriteByte(token)
  42. default:
  43. buf.Write(make([]byte, int(dat[i+1]-2)))
  44. }
  45. i++
  46. } else {
  47. return nil, errors.New("error reading bytes. token encountered without proceeding bytes")
  48. }
  49. } else {
  50. buf.WriteByte(dat[i])
  51. }
  52. }
  53. return buf.Bytes(), nil
  54. }
  55. func compressChunk(dat []byte) (ret []byte, n int) {
  56. switch {
  57. case dat[0] == token:
  58. return []byte{token, tokenToken}, 1
  59. case len(dat) > 1 && dat[0] == 0x0 && dat[1] == 0x0:
  60. j := 0
  61. for j <= 254 && j < len(dat) {
  62. if dat[j] != 0 {
  63. break
  64. }
  65. j++
  66. }
  67. return []byte{token, byte(j + 2)}, j
  68. case len(dat) >= 32:
  69. if dat[0] == empty[0] && bytes.Compare(dat[:32], empty) == 0 {
  70. return []byte{token, emptyShaToken}, 32
  71. } else if dat[0] == emptyList[0] && bytes.Compare(dat[:32], emptyList) == 0 {
  72. return []byte{token, emptyListShaToken}, 32
  73. }
  74. fallthrough
  75. default:
  76. return dat[:1], 1
  77. }
  78. }
  79. func Compress(dat []byte) []byte {
  80. buf := new(bytes.Buffer)
  81. i := 0
  82. for i < len(dat) {
  83. b, n := compressChunk(dat[i:])
  84. buf.Write(b)
  85. i += n
  86. }
  87. return buf.Bytes()
  88. }