| 1 |
// Copyright 2014 The zappy Authors. All rights reserved. |
| 2 |
// Use of this source code is governed by a BSD-style |
| 3 |
// license that can be found in the LICENSE file. |
| 4 |
|
| 5 |
// Copyright 2011 The Snappy-Go Authors. All rights reserved. |
| 6 |
// Use of this source code is governed by a BSD-style |
| 7 |
// license that can be found in the SNAPPY-GO-LICENSE file. |
| 8 |
|
| 9 |
// +build !cgo purego |
| 10 |
|
| 11 |
package zappy |
| 12 |
|
| 13 |
import ( |
| 14 |
"encoding/binary" |
| 15 |
) |
| 16 |
|
| 17 |
func puregoDecode() bool { return true } |
| 18 |
|
| 19 |
// Decode returns the decoded form of src. The returned slice may be a sub- |
| 20 |
// slice of buf if buf was large enough to hold the entire decoded block. |
| 21 |
// Otherwise, a newly allocated slice will be returned. |
| 22 |
// It is valid to pass a nil buf. |
| 23 |
func Decode(buf, src []byte) ([]byte, error) { |
| 24 |
dLen, s, err := decodedLen(src) |
| 25 |
if err != nil { |
| 26 |
return nil, err |
| 27 |
} |
| 28 |
|
| 29 |
if dLen == 0 { |
| 30 |
if len(src) == 1 { |
| 31 |
return nil, nil |
| 32 |
} |
| 33 |
|
| 34 |
return nil, ErrCorrupt |
| 35 |
} |
| 36 |
|
| 37 |
if len(buf) < dLen { |
| 38 |
buf = make([]byte, dLen) |
| 39 |
} |
| 40 |
|
| 41 |
var d, offset, length int |
| 42 |
for s < len(src) { |
| 43 |
n, i := binary.Varint(src[s:]) |
| 44 |
if i <= 0 { |
| 45 |
return nil, ErrCorrupt |
| 46 |
} |
| 47 |
|
| 48 |
s += i |
| 49 |
if n >= 0 { |
| 50 |
length = int(n + 1) |
| 51 |
if length > len(buf)-d || length > len(src)-s { |
| 52 |
return nil, ErrCorrupt |
| 53 |
} |
| 54 |
|
| 55 |
copy(buf[d:], src[s:s+length]) |
| 56 |
d += length |
| 57 |
s += length |
| 58 |
continue |
| 59 |
} |
| 60 |
|
| 61 |
length = int(-n) |
| 62 |
off64, i := binary.Uvarint(src[s:]) |
| 63 |
if i <= 0 { |
| 64 |
return nil, ErrCorrupt |
| 65 |
} |
| 66 |
|
| 67 |
offset = int(off64) |
| 68 |
s += i |
| 69 |
if s > len(src) { |
| 70 |
return nil, ErrCorrupt |
| 71 |
} |
| 72 |
|
| 73 |
end := d + length |
| 74 |
if offset > d || end > len(buf) { |
| 75 |
return nil, ErrCorrupt |
| 76 |
} |
| 77 |
|
| 78 |
for s, v := range buf[d-offset : end-offset] { |
| 79 |
buf[d+s] = v |
| 80 |
} |
| 81 |
d = end |
| 82 |
|
| 83 |
} |
| 84 |
if d != dLen { |
| 85 |
return nil, ErrCorrupt |
| 86 |
} |
| 87 |
|
| 88 |
return buf[:d], nil |
| 89 |
} |