go4.org@v0.0.0-20230225012048-214862532bf5/rollsum/rollsum.go (about)

     1  /*
     2  Copyright 2011 The Perkeep Authors
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8       http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  // Package rollsum implements rolling checksums similar to apenwarr's bup, which
    18  // is similar to librsync.
    19  //
    20  // The bup project is at https://github.com/apenwarr/bup and its splitting in
    21  // particular is at https://github.com/apenwarr/bup/blob/master/lib/bup/bupsplit.c
    22  package rollsum // import "go4.org/rollsum"
    23  
    24  import (
    25  	"math/bits"
    26  )
    27  
    28  const windowSize = 64 // Roll assumes windowSize is a power of 2
    29  const charOffset = 31
    30  
    31  const blobBits = 13
    32  const blobSize = 1 << blobBits // 8k
    33  
    34  type RollSum struct {
    35  	s1, s2 uint32
    36  	window [windowSize]uint8
    37  	wofs   int
    38  }
    39  
    40  func New() *RollSum {
    41  	return &RollSum{
    42  		s1: windowSize * charOffset,
    43  		s2: windowSize * (windowSize - 1) * charOffset,
    44  	}
    45  }
    46  
    47  func (rs *RollSum) add(drop, add uint32) {
    48  	s1 := rs.s1 + add - drop
    49  	rs.s1 = s1
    50  	rs.s2 += s1 - uint32(windowSize)*(drop+charOffset)
    51  }
    52  
    53  // Roll adds ch to the rolling sum.
    54  func (rs *RollSum) Roll(ch byte) {
    55  	wp := &rs.window[rs.wofs]
    56  	rs.add(uint32(*wp), uint32(ch))
    57  	*wp = ch
    58  	rs.wofs = (rs.wofs + 1) & (windowSize - 1)
    59  }
    60  
    61  // OnSplit reports whether at least 13 consecutive trailing bits of
    62  // the current checksum are set the same way.
    63  func (rs *RollSum) OnSplit() bool {
    64  	return (rs.s2 & (blobSize - 1)) == ((^0) & (blobSize - 1))
    65  }
    66  
    67  // OnSplitWithBits reports whether at least n consecutive trailing bits
    68  // of the current checksum are set the same way.
    69  func (rs *RollSum) OnSplitWithBits(n uint32) bool {
    70  	mask := (uint32(1) << n) - 1
    71  	return rs.s2&mask == (^uint32(0))&mask
    72  }
    73  
    74  func (rs *RollSum) Bits() int {
    75  	rsum := rs.Digest() >> (blobBits + 1)
    76  	return blobBits + bits.TrailingZeros32(^rsum)
    77  }
    78  
    79  func (rs *RollSum) Digest() uint32 {
    80  	return (rs.s1 << 16) | (rs.s2 & 0xffff)
    81  }