File: decode_nocgo.go

package info (click to toggle)
golang-github-cznic-zappy 0.0~git20160305.0.4f5e6ef-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 156 kB
  • sloc: makefile: 23; sh: 6
file content (89 lines) | stat: -rw-r--r-- 1,711 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// Copyright 2014 The zappy Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Copyright 2011 The Snappy-Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the SNAPPY-GO-LICENSE file.

// +build !cgo purego

package zappy

import (
	"encoding/binary"
)

func puregoDecode() bool { return true }

// Decode returns the decoded form of src. The returned slice may be a sub-
// slice of buf if buf was large enough to hold the entire decoded block.
// Otherwise, a newly allocated slice will be returned.
// It is valid to pass a nil buf.
func Decode(buf, src []byte) ([]byte, error) {
	dLen, s, err := decodedLen(src)
	if err != nil {
		return nil, err
	}

	if dLen == 0 {
		if len(src) == 1 {
			return nil, nil
		}

		return nil, ErrCorrupt
	}

	if len(buf) < dLen {
		buf = make([]byte, dLen)
	}

	var d, offset, length int
	for s < len(src) {
		n, i := binary.Varint(src[s:])
		if i <= 0 {
			return nil, ErrCorrupt
		}

		s += i
		if n >= 0 {
			length = int(n + 1)
			if length > len(buf)-d || length > len(src)-s {
				return nil, ErrCorrupt
			}

			copy(buf[d:], src[s:s+length])
			d += length
			s += length
			continue
		}

		length = int(-n)
		off64, i := binary.Uvarint(src[s:])
		if i <= 0 {
			return nil, ErrCorrupt
		}

		offset = int(off64)
		s += i
		if s > len(src) {
			return nil, ErrCorrupt
		}

		end := d + length
		if offset > d || end > len(buf) {
			return nil, ErrCorrupt
		}

		for s, v := range buf[d-offset : end-offset] {
			buf[d+s] = v
		}
		d = end

	}
	if d != dLen {
		return nil, ErrCorrupt
	}

	return buf[:d], nil
}