Debian Codegraph @

decode_cgo.go

raw
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 /*
14
15 #include <stdint.h>
16 #include <string.h>
17
18 // supports only uint32 encoded values
19 int uvarint(unsigned int* n, uint8_t* src, int len) {
20 int r = 0;
21 unsigned int v = 0;
22 unsigned int s = 0;
23 while ((len-- != 0) && (++r <= 5)) {
24 uint8_t b = *src++;
25 v = v | ((b&0x7f)<<s);
26 if (b < 0x80) {
27 *n = v;
28 return r;
29 }
30
31 s += 7;
32 }
33 return -1;
34 }
35
36 int varint(int* n, uint8_t* src, int len) {
37 unsigned int u;
38 int i = uvarint(&u, src, len);
39 int x = u>>1;
40 if ((u&1) != 0)
41 x = ~x;
42 *n = x;
43 return i;
44 }
45
46 int decode(int s, int len_src, uint8_t* src, int len_dst, uint8_t* dst) {
47 int d = 0;
48 int length;
49 while (s < len_src) {
50 int n, i = varint(&n, src+s, len_src-s);
51 if (i <= 0) {
52 return -1;
53 }
54
55 s += i;
56 if (n >= 0) {
57 length = n+1;
58 if ((length > len_dst-d) || (length > len_src-s))
59 return -1;
60
61 memcpy(dst+d, src+s, length);
62 d += length;
63 s += length;
64 continue;
65 }
66
67
68 length = -n;
69 int offset;
70 i = uvarint((unsigned int*)(&offset), src+s, len_src-s);
71 if (i <= 0)
72 return -1;
73
74 s += i;
75 if (s > len_src)
76 return -1;
77
78 int end = d+length;
79 if ((offset > d) || (end > len_dst))
80 return -1;
81
82 for( ; d < end; d++)
83 *(dst+d) = *(dst+d-offset);
84 }
85 return d;
86 }
87
88 */
89 import "C"
90
91 func puregoDecode() bool { return false }
92
93 // Decode returns the decoded form of src. The returned slice may be a sub-
94 // slice of buf if buf was large enough to hold the entire decoded block.
95 // Otherwise, a newly allocated slice will be returned.
96 // It is valid to pass a nil buf.
97 func Decode(buf, src []byte) ([]byte, error) {
98 dLen, s, err := decodedLen(src)
99 if err != nil {
100 return nil, err
101 }
102
103 if dLen == 0 {
104 if len(src) == 1 {
105 return nil, nil
106 }
107
108 return nil, ErrCorrupt
109 }
110
111 if len(buf) < dLen {
112 buf = make([]byte, dLen)
113 }
114
115 d := int(C.decode(C.int(s), C.int(len(src)), (*C.uint8_t)(&src[0]), C.int(len(buf)), (*C.uint8_t)(&buf[0])))
116 if d != dLen {
117 return nil, ErrCorrupt
118 }
119
120 return buf[:d], nil
121 }