rspangler@google.com | 49fdf18 | 2009-10-10 00:57:34 +0000 | [diff] [blame] | 1 | // Copyright (c) 2009 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 | #include <sys/stat.h> |
| 6 | #include <sys/types.h> |
| 7 | #include <stdio.h> |
| 8 | #include <stdlib.h> |
| 9 | #include <unistd.h> |
| 10 | #include <string> |
| 11 | #include <vector> |
| 12 | #include "update_engine/test_utils.h" |
seanparent@google.com | d2e4ccc | 2009-11-05 22:56:33 +0000 | [diff] [blame^] | 13 | #include "base/logging.h" |
rspangler@google.com | 49fdf18 | 2009-10-10 00:57:34 +0000 | [diff] [blame] | 14 | |
| 15 | #include "update_engine/file_writer.h" |
| 16 | |
| 17 | using std::string; |
| 18 | using std::vector; |
| 19 | |
| 20 | namespace chromeos_update_engine { |
| 21 | |
| 22 | vector<char> ReadFile(const string& path) { |
| 23 | vector<char> ret; |
| 24 | FILE* fp = fopen(path.c_str(), "r"); |
| 25 | if (!fp) |
| 26 | return ret; |
| 27 | const size_t kChunkSize(1024); |
| 28 | size_t read_size; |
| 29 | do { |
| 30 | char buf[kChunkSize]; |
| 31 | read_size = fread(buf, 1, kChunkSize, fp); |
| 32 | ret.insert(ret.end(), buf, buf + read_size); |
| 33 | } while (read_size == kChunkSize); |
| 34 | fclose(fp); |
| 35 | return ret; |
| 36 | } |
| 37 | |
| 38 | bool WriteFile(const std::string& path, const std::vector<char>& data) { |
| 39 | DirectFileWriter writer; |
| 40 | if (0 != writer.Open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644)) { |
| 41 | return false; |
| 42 | } |
| 43 | if (static_cast<int>(data.size()) != writer.Write(&data[0], data.size())) { |
| 44 | writer.Close(); |
| 45 | return false; |
| 46 | } |
| 47 | writer.Close(); |
| 48 | return true; |
| 49 | } |
| 50 | |
| 51 | off_t FileSize(const string& path) { |
| 52 | struct stat stbuf; |
| 53 | int rc = stat(path.c_str(), &stbuf); |
| 54 | CHECK_EQ(0, rc); |
| 55 | if (rc < 0) |
| 56 | return rc; |
| 57 | return stbuf.st_size; |
| 58 | } |
| 59 | |
| 60 | std::vector<char> GzipCompressData(const std::vector<char>& data) { |
| 61 | const char fname[] = "/tmp/GzipCompressDataTemp"; |
| 62 | if (!WriteFile(fname, data)) { |
| 63 | system((string("rm ") + fname).c_str()); |
| 64 | return vector<char>(); |
| 65 | } |
| 66 | system((string("cat ") + fname + "|gzip>" + fname + ".gz").c_str()); |
| 67 | system((string("rm ") + fname).c_str()); |
| 68 | vector<char> ret = ReadFile(string(fname) + ".gz"); |
| 69 | system((string("rm ") + fname + ".gz").c_str()); |
| 70 | return ret; |
| 71 | } |
| 72 | |
| 73 | } // namespace chromeos_update_engine |