1 // Copyright 2015 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_TEST_UTILS_H_ 6 #define _BSDIFF_TEST_UTILS_H_ 7 8 #include <string> 9 #include <vector> 10 11 #define TEST_AND_RETURN_FALSE(_x) \ 12 do { \ 13 if (!static_cast<bool>(_x)) { \ 14 fprintf(stderr, "%s failed.", #_x); \ 15 return false; \ 16 } \ 17 } while (0) 18 19 namespace test_utils { 20 21 // Reads all the contents of the file |path| into |out|. Returns whether it 22 // read up to the end of file. 23 bool ReadFile(const std::string& path, std::vector<uint8_t>* out); 24 25 // Overrides the file |path| with the contents passed in |out|. Returns whether 26 // the operation succeeded. 27 bool WriteFile(const std::string& path, std::vector<uint8_t> contents); 28 29 // Utility class to create and delete a temp file. 30 class ScopedTempFile { 31 public: 32 // Creates a temp file with the passed |pattern|. The pattern should end with 33 // "XXXXXX", that will be replaced with a random string. The file will be 34 // removed when this instance is destroyed. 35 explicit ScopedTempFile(const std::string& pattern); 36 ~ScopedTempFile(); 37 38 std::string filename() const { return filename_; } 39 const char* c_str() const { return filename_.c_str(); } 40 41 // Releases the temporary file. It will not be deleted when this instance is 42 // destroyed. 43 void release() { filename_.clear(); } 44 45 private: 46 std::string filename_; 47 }; 48 49 // This struct representes a parsed BSDIFF40 file. 50 struct BsdiffPatchFile { 51 static const size_t kHeaderSize = 32; 52 53 // Parses a BSDIFF40 file and stores the contents in the local methods. 54 bool LoadFromFile(const std::string& filename); 55 56 // Returns wheter the patch file is valid. 57 bool IsValid() const; 58 59 // The magic string in the header file. Normally "BSDIFF40". 60 std::string magic; 61 62 // The length of the first (ctrl) bzip2 stream. Negative values are invalid. 63 int64_t ctrl_len = -1; 64 65 // The length of the first (diff) bzip2 stream. Negative values are invalid. 66 int64_t diff_len = -1; 67 68 // The length of the first (diff) bzip2 stream. This value is not stored in 69 // the file, but generated based on the |file_size|. 70 uint64_t extra_len = 0; 71 72 // The length of the new file after applying the patch. Negative values are 73 // invalid. 74 int64_t new_file_len = -1; 75 76 // The three compressed streams. 77 std::vector<uint8_t> bz2_ctrl; 78 std::vector<uint8_t> bz2_diff; 79 std::vector<uint8_t> bz2_extra; 80 81 uint64_t file_size = 0; 82 }; 83 84 85 } // namespace test_utils 86 87 88 #endif // _BSDIFF_TEST_UTILS_H_ 89