Debian Codegraph @

encode_nocgo.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 import (
14 "encoding/binary"
15 "fmt"
16 "math"
17 )
18
19 func puregoEncode() bool { return true }
20
21 // Encode returns the encoded form of src. The returned slice may be a sub-
22 // slice of buf if buf was large enough to hold the entire encoded block.
23 // Otherwise, a newly allocated slice will be returned.
24 // It is valid to pass a nil buf.
25 func Encode(buf, src []byte) ([]byte, error) {
26 if n := MaxEncodedLen(len(src)); len(buf) < n {
27 buf = make([]byte, n)
28 }
29
30 if len(src) > math.MaxInt32 {
31 return nil, fmt.Errorf("zappy.Encode: too long data: %d bytes", len(src))
32 }
33
34 // The block starts with the varint-encoded length of the decompressed bytes.
35 d := binary.PutUvarint(buf, uint64(len(src)))
36
37 // Return early if src is short.
38 if len(src) <= 4 {
39 if len(src) != 0 {
40 d += emitLiteral(buf[d:], src)
41 }
42 return buf[:d], nil
43 }
44
45 // Iterate over the source bytes.
46 var (
47 table [1 << 12]int // Hash table
48 s int // The iterator position.
49 t int // The last position with the same hash as s.
50 lit int // The start position of any pending literal bytes.
51 )
52 for lim := len(src) - 3; s < lim; {
53 // Update the hash table.
54 b0, b1, b2, b3 := src[s], src[s+1], src[s+2], src[s+3]
55 h := uint32(b0) | uint32(b1)<<8 | uint32(b2)<<16 | uint32(b3)<<24
56 more:
57 p := &table[(h*0x1e35a7bd)>>20]
58 t, *p = *p, s
59 // If t is invalid or src[s:s+4] differs from src[t:t+4], accumulate a literal byte.
60 if t == 0 || s-t >= maxOffset || b0 != src[t] || b1 != src[t+1] || b2 != src[t+2] || b3 != src[t+3] {
61 s++
62 if s >= lim {
63 break
64 }
65
66 b0, b1, b2, b3 = b1, b2, b3, src[s+3]
67 h = h>>8 | uint32(b3)<<24
68 goto more
69 }
70
71 // Otherwise, we have a match. First, emit any pending literal bytes.
72 if lit != s {
73 d += emitLiteral(buf[d:], src[lit:s])
74 }
75 // Extend the match to be as long as possible.
76 s0 := s
77 s, t = s+4, t+4
78 for s < len(src) && src[s] == src[t] {
79 s++
80 t++
81 }
82 // Emit the copied bytes.
83 d += emitCopy(buf[d:], s-t, s-s0)
84 lit = s
85 }
86
87 // Emit any final pending literal bytes and return.
88 if lit != len(src) {
89 d += emitLiteral(buf[d:], src[lit:])
90 }
91 return buf[:d], nil
92 }