diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6350f0f --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +test-data/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md index c409364..be7282e 100644 --- a/README.md +++ b/README.md @@ -1 +1,8 @@ A Golang implementation of the rsync algorithm. + +# Running the tests +When you want to run the tests, make sure to extract the test-data.xz file first. + +If you made any modifications to the test data, you can update it using: + + tar c test-data | xz > test-data.xz diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..ecb3faf --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module github.com/juli4n/rsync + +go 1.12 diff --git a/rsync.go b/rsync.go index 9be54d2..763f960 100644 --- a/rsync.go +++ b/rsync.go @@ -1,36 +1,51 @@ -// Copyright 2016 Julian Gutierrez Oschmann (github.com/juli4n). -// All rights reserved. -// Use of this source code is governed by a BSD-style license that can be found -// in the LICENSE file. +/* +Copyright 2016 Julian Gutierrez Oschmann (github.com/juli4n). +Copyright 2019 Dolf 'Freeaqingme' Schimmel. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ // Package rsync contains an implementation of the rsync algorithm. package rsync import ( "bytes" + "context" "crypto/md5" "fmt" + "hash" "io" - "io/ioutil" ) const ( - BlockSize = 1024 * 64 - M = 1 << 16 + defaultBlockSize = 1024 * 64 + m = 1 << 16 + defaultMaxDataSize = 2 << 20 // 2 MiB ) // BlockHash holds both strong and weak hash of a block. type BlockHash struct { - index int - strongHash []byte - weakHash uint32 + Index uint32 + StrongHash []byte + WeakHash uint32 } // There are two kind of operations: BLOCK and DATA. // If a block match is found on the server, a BLOCK operation is sent over the channel along with the block index. // Modified data between two block matches is sent like a DATA operation. const ( - BLOCK = iota + INVALID = iota + BLOCK DATA ) @@ -39,17 +54,31 @@ const ( type Operation struct { // Kind of operation: BLOCK | DATA. OpCode int - // The raw modificated (or misaligned) data. Iff opCode == DATA, nil otherwise. + // The raw modified (or misaligned) data. If opCode == DATA, nil otherwise. Data []byte - // The index of found block. Iff opCode == BLOCK. nil otherwise. - BlockIndex int + // The index of found block. If opCode == BLOCK. 0 otherwise. + BlockIndex uint32 +} + +type Rsync struct { + StrongHashAlgo func() hash.Hash + BlockSize int64 + MaxDataSize int64 +} + +func New() *Rsync { + return &Rsync{ + StrongHashAlgo: md5.New, + BlockSize: defaultBlockSize, + MaxDataSize: defaultMaxDataSize, // Must be larger than block size + } } // CalculateBlockHashes returns a list of block hashes for a given byte stream. -func CalculateBlockHashes(content io.Reader) ([]BlockHash, error) { - b := make([]byte, BlockSize) +func (rsync *Rsync) CalculateBlockHashes(content io.Reader) ([]BlockHash, error) { + b := make([]byte, rsync.BlockSize) var blockHashes []BlockHash - i := 0 + i := uint32(1) for { n, err := content.Read(b) if err == io.EOF { @@ -58,8 +87,8 @@ func CalculateBlockHashes(content io.Reader) ([]BlockHash, error) { return nil, err } weak, _, _ := weakHash(b[0:n]) - strong := strongHash(b[0:n]) - blockHashes = append(blockHashes, BlockHash{index: i, strongHash: strong, weakHash: weak}) + strong := rsync.strongHash(b[0:n]) + blockHashes = append(blockHashes, BlockHash{Index: i, StrongHash: strong, WeakHash: weak}) i++ } return blockHashes, nil @@ -67,36 +96,28 @@ func CalculateBlockHashes(content io.Reader) ([]BlockHash, error) { // ApplyOps applies operations from a given channel to the original content // and returns a reader with the modified content. -func ApplyOps(original io.Reader, ops chan Operation) (io.Reader, error) { - if s, ok := original.(io.ReadSeeker); ok { - return applyOpsSeeker(s, ops), nil - } - b, err := ioutil.ReadAll(original) - if err != nil { - return nil, err - } - return applyOpsSeeker(bytes.NewReader(b), ops), nil -} - -func applyOpsSeeker(original io.ReadSeeker, ops chan Operation) io.Reader { +func (rsync *Rsync) ApplyOps(original io.ReadSeeker, ops chan Operation) io.ReadCloser { r, w := io.Pipe() go func() { for op := range ops { switch op.OpCode { case BLOCK: + offset := int64(op.BlockIndex-1) * rsync.BlockSize // There is a block match, set the reader offset to the right position // and do the copy. If something goes wrong, just close the writer with an error. - if _, err := original.Seek(int64(op.BlockIndex*BlockSize), io.SeekStart); err != nil { + if _, err := original.Seek(offset, io.SeekStart); err != nil { w.CloseWithError(err) } - if n, err := io.CopyN(w, original, BlockSize); err != nil { + if n, err := io.CopyN(w, original, rsync.BlockSize); err != nil { w.CloseWithError(err) - } else if n != BlockSize { - w.CloseWithError(fmt.Errorf("Cannot read block at offset %d", op.BlockIndex*BlockSize)) + } else if n != rsync.BlockSize { + w.CloseWithError(fmt.Errorf("Cannot read block at offset %d", offset)) } case DATA: // There is no block match. Copy the raw data. w.Write(op.Data) + case INVALID: + panic("Invalid OP") } } w.Close() @@ -104,59 +125,116 @@ func applyOpsSeeker(original io.ReadSeeker, ops chan Operation) io.Reader { return r } -// CalculateDifferences computes all the operations needed to recreate content. -// All these operations are sent through a channel of RSyncOp. -func CalculateDifferences(content []byte, hashes []BlockHash, opsChannel chan Operation) { +func (rsync *Rsync) BuildHashMap(hashes []BlockHash) map[uint32][]BlockHash { hashesMap := make(map[uint32][]BlockHash) - defer close(opsChannel) for _, h := range hashes { - key := h.weakHash + key := h.WeakHash hashesMap[key] = append(hashesMap[key], h) } - var offset, previousMatch int + return hashesMap +} + +// CalculateDifferences computes all the operations needed to recreate content. +// All these operations are sent through a channel of RSyncOp. +func (rsync *Rsync) CalculateDifferences(ctx context.Context, + source io.Reader, + hashesMap map[uint32][]BlockHash, + opsChannel chan Operation, +) { + + defer close(opsChannel) + content, err := newSlidingWindowBuf(source, rsync.MaxDataSize) + if err != nil { + // now what? + } + + var offset, previousMatch, size, endingByte int64 var aweak, bweak, weak uint32 var dirty, isRolling bool + var prevLastByte, lastByte byte + var block []byte + + dirtyContent := make([]byte, rsync.MaxDataSize) + + for true { + block, size, _ = content.ReadAt(offset, rsync.BlockSize) + endingByte = offset + size + if len(block) == 0 { + break + } - for offset < len(content) { - endingByte := min(offset+BlockSize, len(content)-1) - block := content[offset:endingByte] if !isRolling { weak, aweak, bweak = weakHash(block) isRolling = true } else { - aweak = (aweak - uint32(content[offset-1]) + uint32(content[endingByte-1])) % M - bweak = (bweak - (uint32(endingByte-offset) * uint32(content[offset-1])) + aweak) % M + prevLastByte, _ = content.ReadByteAt(offset - 1) + lastByte, _ = content.ReadByteAt(endingByte - 1) + + aweak = (aweak - uint32(prevLastByte) + uint32(lastByte)) % m + bweak = (bweak - (uint32(endingByte-offset) * uint32(prevLastByte)) + aweak) % m weak = aweak + (1 << 16 * bweak) } + if l := hashesMap[weak]; l != nil { - blockFound, blockHash := searchStrongHash(l, strongHash(block)) + blockFound, blockHash := rsync.searchStrongHash(l, rsync.strongHash(block)) if blockFound { if dirty { - opsChannel <- Operation{OpCode: DATA, Data: content[previousMatch:offset]} + dirtyContent, _, _ = content.ReadAt(previousMatch, offset-previousMatch) + + select { + case opsChannel <- Operation{OpCode: DATA, Data: dirtyContent}: + case <-ctx.Done(): + return + } dirty = false } - opsChannel <- Operation{OpCode: BLOCK, BlockIndex: blockHash.index} + select { + case opsChannel <- Operation{OpCode: BLOCK, BlockIndex: blockHash.Index}: + case <-ctx.Done(): + return + } + previousMatch = endingByte isRolling = false - offset += BlockSize + offset += rsync.BlockSize continue } } + + if (offset - previousMatch) >= rsync.MaxDataSize { + dirtyContent, _, _ = content.ReadAt(previousMatch, rsync.MaxDataSize) + + select { + case opsChannel <- Operation{OpCode: DATA, Data: dirtyContent}: + case <-ctx.Done(): + return + } + previousMatch = offset + isRolling = false + } + dirty = true offset++ } if dirty { - opsChannel <- Operation{OpCode: DATA, Data: content[previousMatch:]} + dirtyContent, _, _ = content.ReadAt(previousMatch, offset-previousMatch) + + select { + case opsChannel <- Operation{OpCode: DATA, Data: dirtyContent}: + case <-ctx.Done(): + return + } } + } // Searches for a given strong hash among all strong hashes in this bucket. -func searchStrongHash(l []BlockHash, hashValue []byte) (bool, *BlockHash) { +func (rsync *Rsync) searchStrongHash(l []BlockHash, hashValue []byte) (bool, *BlockHash) { for _, blockHash := range l { - if bytes.Compare(blockHash.strongHash, hashValue) == 0 { + if bytes.Compare(blockHash.StrongHash, hashValue) == 0 { return true, &blockHash } } @@ -164,8 +242,8 @@ func searchStrongHash(l []BlockHash, hashValue []byte) (bool, *BlockHash) { } // Returns a strong hash for a given block of data -func strongHash(v []byte) []byte { - h := md5.New() +func (rsync *Rsync) strongHash(v []byte) []byte { + h := rsync.StrongHashAlgo() h.Write(v) return h.Sum(nil) } @@ -177,13 +255,5 @@ func weakHash(v []byte) (uint32, uint32, uint32) { a += uint32(v[i]) b += (uint32(len(v)-1) - uint32(i) + 1) * uint32(v[i]) } - return (a % M) + (1 << 16 * (b % M)), a % M, b % M -} - -// Returns the smaller of a or b. -func min(a, b int) int { - if a < b { - return a - } - return b + return (a % m) + (1 << 16 * (b % m)), a % m, b % m } diff --git a/rsync_test.go b/rsync_test.go index 67ec53a..c4ca6fe 100644 --- a/rsync_test.go +++ b/rsync_test.go @@ -1,13 +1,27 @@ -// Copyright 2012 Julian Gutierrez Oschmann (github.com/julian-gutierrez-o). -// All rights reserved. -// Use of this source code is governed by a BSD-style license that can be found -// in the LICENSE file. +/* +Copyright 2016 Julian Gutierrez Oschmann (github.com/juli4n). +Copyright 2019 Dolf 'Freeaqingme' Schimmel. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ // Unit tests for core package package rsync import ( "bytes" + "context" + "fmt" "io/ioutil" "os" "testing" @@ -16,34 +30,96 @@ import ( type filePair struct { original string modified string + + totalOps uint64 + hashBlocks uint64 + dataBlocks uint64 + dataBytes uint64 +} + +func (p *filePair) String() string { + return fmt.Sprintf("%s %s", p.original, p.modified) } func Test_SyncModifiedContent(t *testing.T) { + files := []filePair{ - filePair{"golang-original.bmp", "golang-modified.bmp"}, - filePair{"text-original.txt", "text-modified.txt"}} + {"golang-original.bmp", "golang-modified.bmp", + 48, 46, 2, 196608}, + {"text-original.txt", "text-modified.txt", + 1, 0, 1, 16}, + {"text-original-empty.txt", "text-modified-empty-not.txt", + 2, 0, 2, 175577}, + {"text-original-empty.txt", "text-original-empty.txt", + 0, 0, 0, 0}, + {"text-modified-empty-not.txt", "text-modified-empty-not-rev.txt", + 2, 0, 2, 175577}, + {"text-modified-empty-not-5mb.txt", "text-modified-empty-not-rev-5mb.txt", + 45, 0, 45, 5794041}, + {"text-modified-empty-not-5mb.txt", "text-modified-empty-not-5mb.txt", + 89, 89, 0, 0}, + } for _, filePair := range files { - original, _ := os.Open("test-data/" + filePair.original) - modified, _ := ioutil.ReadFile("test-data/" + filePair.modified) + original, err := os.Open("test-data/" + filePair.original) + if err != nil { + panic(err) + } + modified, err := os.Open("test-data/" + filePair.modified) + if err != nil { + panic(err) + } + modifiedBytes, _ := ioutil.ReadFile("test-data/" + filePair.modified) - hashes, _ := CalculateBlockHashes(original) + rsync := New() + rsync.MaxDataSize = 2 << 16 // 128 KiB + hashes, _ := rsync.CalculateBlockHashes(original) opsChannel := make(chan Operation) - go CalculateDifferences(modified, hashes, opsChannel) + opsChannel2 := make(chan Operation) + go rsync.CalculateDifferences(context.Background(), modified, rsync.BuildHashMap(hashes), opsChannel) - result, err := ApplyOps(original, opsChannel) - if err != nil { - t.Error(err) - } + var totalOps, dataBlocks, hashBlocks, dataBytes uint64 + go func(chan1, chan2 chan Operation) { + for op := range chan1 { + totalOps += 1 + if length := uint64(len(op.Data)); length > 1 { + dataBlocks += 1 + dataBytes += length + } else { + hashBlocks += 1 + } + chan2 <- op + } + close(chan2) + }(opsChannel, opsChannel2) + + result := rsync.ApplyOps(original, opsChannel2) resultBytes, err := ioutil.ReadAll(result) if err != nil { t.Error(err) } - if bytes.Compare(resultBytes, modified) != 0 { - t.Errorf("rsync did not work as expected for %v", filePair) + fmt.Printf("%v:\n\ttotalOps %d /hashBlocks %d / dataBlocks %d / dataBytes %d\n\n", filePair, totalOps, hashBlocks, dataBlocks, dataBytes) + if bytes.Compare(resultBytes, modifiedBytes) != 0 { + t.Errorf("rsync did not work as expected for %v", filePair.String()) + } + + if filePair.totalOps != totalOps { + t.Errorf("Expected %d ops, but encountered %d, for: %v", filePair.totalOps, totalOps, filePair) + } + + if filePair.hashBlocks != hashBlocks { + t.Errorf("Expected %d hash blocks, but encountered %d, for: %v", filePair.hashBlocks, hashBlocks, filePair) + } + + if filePair.dataBlocks != dataBlocks { + t.Errorf("Expected %d data blocks, but encountered %d, for: %v", filePair.dataBlocks, dataBlocks, filePair) + } + + if filePair.dataBytes != dataBytes { + t.Errorf("Expected %d data bytes, but encountered %d, for: %v", filePair.dataBytes, dataBytes, filePair) } } } diff --git a/slidingWindowBuf.go b/slidingWindowBuf.go new file mode 100644 index 0000000..c6ef98f --- /dev/null +++ b/slidingWindowBuf.go @@ -0,0 +1,109 @@ +package rsync + +import ( + "errors" + "io" + "sync" +) + +type slidingWindowBuf struct { + source io.Reader + chunkSize int64 + + s []byte + slider int64 + + lastOffset int64 + size int64 + eof bool + + byteSlicePool *sync.Pool +} + +func newSlidingWindowBuf(source io.Reader, chunkSize int64) (*slidingWindowBuf, error) { + r := &slidingWindowBuf{ + source: source, + chunkSize: chunkSize, + byteSlicePool: &sync.Pool{ + New: func() interface{} { + return make([]byte, 3*chunkSize) + }, + }, + } + + err := r.grow(0) + return r, err +} + +func (r *slidingWindowBuf) grow(requestedOffset int64) error { + if r.eof || requestedOffset+(2*r.chunkSize) <= r.size { + return nil + } + chunk := r.byteSlicePool.Get().([]byte) + n, err := r.source.Read(chunk) + if err != nil { + if err != io.EOF { + return err + } + r.eof = true + return nil + } + + if r.lastOffset-r.slider < (3 * r.chunkSize) { + r.s = append(r.s, chunk[:n]...) + r.size += int64(n) + } else { + r.byteSlicePool.Put(r.s[0 : r.chunkSize*3]) + r.s = append(r.s[r.chunkSize*3:], chunk[:n]...) + r.slider += r.chunkSize * 3 + r.size += int64(n) + } + //fmt.Printf("readseakerbuf is now %d bytes\n", len(r.s)) + + if int64(n) < r.chunkSize { + return nil + } + + // allow for tail recursion optimization + return r.grow(requestedOffset) +} + +// ReadAt() without copy() +func (r *slidingWindowBuf) ReadAt(off int64, n int64) ([]byte, int64, error) { + if off < 0 { + return []byte{}, 0, errors.New("bytes.Reader.ReadAt: negative offset") + } + + if err := r.grow(off); err != nil { + return []byte{}, 0, err + } + + if (off - r.slider) >= int64(len(r.s)) { + return []byte{}, 0, io.EOF + } + + if (off-r.slider)+n > int64(len(r.s)) { + n = int64(len(r.s)) - (off - r.slider) + } + + r.lastOffset = off + return r.s[(off - r.slider) : (off-r.slider)+n], n, nil +} + +func (r *slidingWindowBuf) ReadByteAt(off int64) (content byte, err error) { + if off < 0 { + return 0, errors.New("bytes.Reader.ReadAt: negative offset") + } + + if (off-r.slider)+1 >= int64(len(r.s)) { + return 0, io.EOF + } + + r.lastOffset = off + + //if err := r.grow(off); err != nil { + // return 0, err + //} + + return r.s[(off - r.slider) : (off-r.slider)+1][0], nil +} diff --git a/test-data.xz b/test-data.xz new file mode 100644 index 0000000..f839554 Binary files /dev/null and b/test-data.xz differ diff --git a/test-data/golang-modified.bmp b/test-data/golang-modified.bmp deleted file mode 100644 index d8e6b82..0000000 Binary files a/test-data/golang-modified.bmp and /dev/null differ diff --git a/test-data/golang-original.bmp b/test-data/golang-original.bmp deleted file mode 100644 index 984562d..0000000 Binary files a/test-data/golang-original.bmp and /dev/null differ diff --git a/test-data/text-modified.txt b/test-data/text-modified.txt deleted file mode 100644 index 289cd47..0000000 --- a/test-data/text-modified.txt +++ /dev/null @@ -1 +0,0 @@ -some extra text diff --git a/test-data/text-original.txt b/test-data/text-original.txt deleted file mode 100644 index 7b57bd2..0000000 --- a/test-data/text-original.txt +++ /dev/null @@ -1 +0,0 @@ -some text