blob: 2dbf8beea52b450b423ea5a5ab0aadc64b259547 [file] [log] [blame]
Alex Deymoa28e0192017-09-08 14:21:05 +02001// Copyright 2017 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef _BSDIFF_PATCH_WRITER_H_
6#define _BSDIFF_PATCH_WRITER_H_
7
8#include <stdio.h>
9
10#include <string>
11#include <vector>
12
13#include "bsdiff/common.h"
14#include "bz2_compressor.h"
15
16namespace bsdiff {
17
18struct ControlEntry {
19 ControlEntry(uint64_t diff_size,
20 uint64_t extra_size,
21 int64_t offset_increment)
22 : diff_size(diff_size),
23 extra_size(extra_size),
24 offset_increment(offset_increment) {}
25
26 // The number of bytes to copy from the source and diff stream.
27 uint64_t diff_size;
28
29 // The number of bytes to copy from the extra stream.
30 uint64_t extra_size;
31
32 // The value to add to the source pointer after patching from the diff stream.
33 int64_t offset_increment;
34};
35
36class BsdiffPatchWriter {
37 public:
38 BsdiffPatchWriter(const uint8_t* old_buf,
39 uint64_t old_size,
40 const uint8_t* new_buf,
41 uint64_t new_size)
42 : old_buf_(old_buf),
43 old_size_(old_size),
44 new_buf_(new_buf),
45 new_size_(new_size) {}
46
47 // Create the file |patch_filename| where the patch will be written to.
48 bool Open(const std::string& patch_filename);
49
50 // Add a new control triplet entry to the patch. The |entry.diff_size| bytes
51 // for the diff stream and the |entry.extra_size| bytes for the extra stream
52 // will be computed and added to the corresponding streams in the patch.
53 // Returns whether the operation succeeded. The operation can fail if either
54 // the old or new files are referenced out of bounds.
55 bool AddControlEntry(const ControlEntry& entry);
56
57 bool Close();
58
59 private:
60 // Write the BSDIFF patch header to the |fp_| given the size of the compressed
61 // control block and the compressed diff block.
62 bool WriteHeader(uint64_t ctrl_size, uint64_t diff_size);
63
64
65 const uint8_t* old_buf_;
66 uint64_t old_size_;
67 const uint8_t* new_buf_;
68 uint64_t new_size_;
69
70 // Bytes of the new_buf_ already written.
71 uint64_t written_output_{0};
72
73 // The current position in the old buf.
74 int64_t old_pos_{0};
75
76 // The current file we are writing to.
77 FILE* fp_{nullptr};
78
79 // The three internal compressed streams.
80 BZ2Compressor ctrl_stream_;
81 BZ2Compressor diff_stream_;
82 BZ2Compressor extra_stream_;
83};
84
85} // namespace bsdiff
86
87#endif // _BSDIFF_PATCH_WRITER_H_