github.com/bir3/gocompiler@v0.9.2202/extra/compress/internal/snapref/encode_other.go (about)

     1  // Copyright 2016 The Snappy-Go 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  package snapref
     6  
     7  func load32(b []byte, i int) uint32 {
     8  	b = b[i : i+4 : len(b)] // Help the compiler eliminate bounds checks on the next line.
     9  	return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
    10  }
    11  
    12  func load64(b []byte, i int) uint64 {
    13  	b = b[i : i+8 : len(b)] // Help the compiler eliminate bounds checks on the next line.
    14  	return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 |
    15  		uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56
    16  }
    17  
    18  // emitLiteral writes a literal chunk and returns the number of bytes written.
    19  //
    20  // It assumes that:
    21  //
    22  //	dst is long enough to hold the encoded bytes
    23  //	1 <= len(lit) && len(lit) <= 65536
    24  func emitLiteral(dst, lit []byte) int {
    25  	i, n := 0, uint(len(lit)-1)
    26  	switch {
    27  	case n < 60:
    28  		dst[0] = uint8(n)<<2 | tagLiteral
    29  		i = 1
    30  	case n < 1<<8:
    31  		dst[0] = 60<<2 | tagLiteral
    32  		dst[1] = uint8(n)
    33  		i = 2
    34  	default:
    35  		dst[0] = 61<<2 | tagLiteral
    36  		dst[1] = uint8(n)
    37  		dst[2] = uint8(n >> 8)
    38  		i = 3
    39  	}
    40  	return i + copy(dst[i:], lit)
    41  }
    42  
    43  // emitCopy writes a copy chunk and returns the number of bytes written.
    44  //
    45  // It assumes that:
    46  //
    47  //	dst is long enough to hold the encoded bytes
    48  //	1 <= offset && offset <= 65535
    49  //	4 <= length && length <= 65535
    50  func emitCopy(dst []byte, offset, length int) int {
    51  	i := 0
    52  	// The maximum length for a single tagCopy1 or tagCopy2 op is 64 bytes. The
    53  	// threshold for this loop is a little higher (at 68 = 64 + 4), and the
    54  	// length emitted down below is is a little lower (at 60 = 64 - 4), because
    55  	// it's shorter to encode a length 67 copy as a length 60 tagCopy2 followed
    56  	// by a length 7 tagCopy1 (which encodes as 3+2 bytes) than to encode it as
    57  	// a length 64 tagCopy2 followed by a length 3 tagCopy2 (which encodes as
    58  	// 3+3 bytes). The magic 4 in the 64±4 is because the minimum length for a
    59  	// tagCopy1 op is 4 bytes, which is why a length 3 copy has to be an
    60  	// encodes-as-3-bytes tagCopy2 instead of an encodes-as-2-bytes tagCopy1.
    61  	for length >= 68 {
    62  		// Emit a length 64 copy, encoded as 3 bytes.
    63  		dst[i+0] = 63<<2 | tagCopy2
    64  		dst[i+1] = uint8(offset)
    65  		dst[i+2] = uint8(offset >> 8)
    66  		i += 3
    67  		length -= 64
    68  	}
    69  	if length > 64 {
    70  		// Emit a length 60 copy, encoded as 3 bytes.
    71  		dst[i+0] = 59<<2 | tagCopy2
    72  		dst[i+1] = uint8(offset)
    73  		dst[i+2] = uint8(offset >> 8)
    74  		i += 3
    75  		length -= 60
    76  	}
    77  	if length >= 12 || offset >= 2048 {
    78  		// Emit the remaining copy, encoded as 3 bytes.
    79  		dst[i+0] = uint8(length-1)<<2 | tagCopy2
    80  		dst[i+1] = uint8(offset)
    81  		dst[i+2] = uint8(offset >> 8)
    82  		return i + 3
    83  	}
    84  	// Emit the remaining copy, encoded as 2 bytes.
    85  	dst[i+0] = uint8(offset>>8)<<5 | uint8(length-4)<<2 | tagCopy1
    86  	dst[i+1] = uint8(offset)
    87  	return i + 2
    88  }
    89  
    90  // extendMatch returns the largest k such that k <= len(src) and that
    91  // src[i:i+k-j] and src[j:k] have the same contents.
    92  //
    93  // It assumes that:
    94  //
    95  //	0 <= i && i < j && j <= len(src)
    96  func extendMatch(src []byte, i, j int) int {
    97  	for ; j < len(src) && src[i] == src[j]; i, j = i+1, j+1 {
    98  	}
    99  	return j
   100  }
   101  
   102  func hash(u, shift uint32) uint32 {
   103  	return (u * 0x1e35a7bd) >> shift
   104  }
   105  
   106  // EncodeBlockInto exposes encodeBlock but checks dst size.
   107  func EncodeBlockInto(dst, src []byte) (d int) {
   108  	if MaxEncodedLen(len(src)) > len(dst) {
   109  		return 0
   110  	}
   111  
   112  	// encodeBlock breaks on too big blocks, so split.
   113  	for len(src) > 0 {
   114  		p := src
   115  		src = nil
   116  		if len(p) > maxBlockSize {
   117  			p, src = p[:maxBlockSize], p[maxBlockSize:]
   118  		}
   119  		if len(p) < minNonLiteralBlockSize {
   120  			d += emitLiteral(dst[d:], p)
   121  		} else {
   122  			d += encodeBlock(dst[d:], p)
   123  		}
   124  	}
   125  	return d
   126  }
   127  
   128  // encodeBlock encodes a non-empty src to a guaranteed-large-enough dst. It
   129  // assumes that the varint-encoded length of the decompressed bytes has already
   130  // been written.
   131  //
   132  // It also assumes that:
   133  //
   134  //	len(dst) >= MaxEncodedLen(len(src)) &&
   135  //	minNonLiteralBlockSize <= len(src) && len(src) <= maxBlockSize
   136  func encodeBlock(dst, src []byte) (d int) {
   137  	// Initialize the hash table. Its size ranges from 1<<8 to 1<<14 inclusive.
   138  	// The table element type is uint16, as s < sLimit and sLimit < len(src)
   139  	// and len(src) <= maxBlockSize and maxBlockSize == 65536.
   140  	const (
   141  		maxTableSize = 1 << 14
   142  		// tableMask is redundant, but helps the compiler eliminate bounds
   143  		// checks.
   144  		tableMask = maxTableSize - 1
   145  	)
   146  	shift := uint32(32 - 8)
   147  	for tableSize := 1 << 8; tableSize < maxTableSize && tableSize < len(src); tableSize *= 2 {
   148  		shift--
   149  	}
   150  	// In Go, all array elements are zero-initialized, so there is no advantage
   151  	// to a smaller tableSize per se. However, it matches the C++ algorithm,
   152  	// and in the asm versions of this code, we can get away with zeroing only
   153  	// the first tableSize elements.
   154  	var table [maxTableSize]uint16
   155  
   156  	// sLimit is when to stop looking for offset/length copies. The inputMargin
   157  	// lets us use a fast path for emitLiteral in the main loop, while we are
   158  	// looking for copies.
   159  	sLimit := len(src) - inputMargin
   160  
   161  	// nextEmit is where in src the next emitLiteral should start from.
   162  	nextEmit := 0
   163  
   164  	// The encoded form must start with a literal, as there are no previous
   165  	// bytes to copy, so we start looking for hash matches at s == 1.
   166  	s := 1
   167  	nextHash := hash(load32(src, s), shift)
   168  
   169  	for {
   170  		// Copied from the C++ snappy implementation:
   171  		//
   172  		// Heuristic match skipping: If 32 bytes are scanned with no matches
   173  		// found, start looking only at every other byte. If 32 more bytes are
   174  		// scanned (or skipped), look at every third byte, etc.. When a match
   175  		// is found, immediately go back to looking at every byte. This is a
   176  		// small loss (~5% performance, ~0.1% density) for compressible data
   177  		// due to more bookkeeping, but for non-compressible data (such as
   178  		// JPEG) it's a huge win since the compressor quickly "realizes" the
   179  		// data is incompressible and doesn't bother looking for matches
   180  		// everywhere.
   181  		//
   182  		// The "skip" variable keeps track of how many bytes there are since
   183  		// the last match; dividing it by 32 (ie. right-shifting by five) gives
   184  		// the number of bytes to move ahead for each iteration.
   185  		skip := 32
   186  
   187  		nextS := s
   188  		candidate := 0
   189  		for {
   190  			s = nextS
   191  			bytesBetweenHashLookups := skip >> 5
   192  			nextS = s + bytesBetweenHashLookups
   193  			skip += bytesBetweenHashLookups
   194  			if nextS > sLimit {
   195  				goto emitRemainder
   196  			}
   197  			candidate = int(table[nextHash&tableMask])
   198  			table[nextHash&tableMask] = uint16(s)
   199  			nextHash = hash(load32(src, nextS), shift)
   200  			if load32(src, s) == load32(src, candidate) {
   201  				break
   202  			}
   203  		}
   204  
   205  		// A 4-byte match has been found. We'll later see if more than 4 bytes
   206  		// match. But, prior to the match, src[nextEmit:s] are unmatched. Emit
   207  		// them as literal bytes.
   208  		d += emitLiteral(dst[d:], src[nextEmit:s])
   209  
   210  		// Call emitCopy, and then see if another emitCopy could be our next
   211  		// move. Repeat until we find no match for the input immediately after
   212  		// what was consumed by the last emitCopy call.
   213  		//
   214  		// If we exit this loop normally then we need to call emitLiteral next,
   215  		// though we don't yet know how big the literal will be. We handle that
   216  		// by proceeding to the next iteration of the main loop. We also can
   217  		// exit this loop via goto if we get close to exhausting the input.
   218  		for {
   219  			// Invariant: we have a 4-byte match at s, and no need to emit any
   220  			// literal bytes prior to s.
   221  			base := s
   222  
   223  			// Extend the 4-byte match as long as possible.
   224  			//
   225  			// This is an inlined version of:
   226  			//	s = extendMatch(src, candidate+4, s+4)
   227  			s += 4
   228  			for i := candidate + 4; s < len(src) && src[i] == src[s]; i, s = i+1, s+1 {
   229  			}
   230  
   231  			d += emitCopy(dst[d:], base-candidate, s-base)
   232  			nextEmit = s
   233  			if s >= sLimit {
   234  				goto emitRemainder
   235  			}
   236  
   237  			// We could immediately start working at s now, but to improve
   238  			// compression we first update the hash table at s-1 and at s. If
   239  			// another emitCopy is not our next move, also calculate nextHash
   240  			// at s+1. At least on GOARCH=amd64, these three hash calculations
   241  			// are faster as one load64 call (with some shifts) instead of
   242  			// three load32 calls.
   243  			x := load64(src, s-1)
   244  			prevHash := hash(uint32(x>>0), shift)
   245  			table[prevHash&tableMask] = uint16(s - 1)
   246  			currHash := hash(uint32(x>>8), shift)
   247  			candidate = int(table[currHash&tableMask])
   248  			table[currHash&tableMask] = uint16(s)
   249  			if uint32(x>>8) != load32(src, candidate) {
   250  				nextHash = hash(uint32(x>>16), shift)
   251  				s++
   252  				break
   253  			}
   254  		}
   255  	}
   256  
   257  emitRemainder:
   258  	if nextEmit < len(src) {
   259  		d += emitLiteral(dst[d:], src[nextEmit:])
   260  	}
   261  	return d
   262  }