• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "file_writer.h"
17 #include "zlib.h"
18 
19 namespace panda::panda_file {
20 
FileWriter(const std::string & file_name)21 FileWriter::FileWriter(const std::string &file_name) : checksum_(adler32(0, nullptr, 0))
22 {
23 #ifdef PANDA_TARGET_WINDOWS
24     constexpr char const *mode = "wb";
25 #else
26     constexpr char const *mode = "wbe";
27 #endif
28 
29     file_ = fopen(file_name.c_str(), mode);
30 }
31 
~FileWriter()32 FileWriter::~FileWriter()
33 {
34     if (file_ != nullptr) {
35         fclose(file_);
36     }
37 }
38 
WriteByte(uint8_t data)39 bool FileWriter::WriteByte(uint8_t data)
40 {
41     if (LIKELY(count_checksum_)) {
42         checksum_ = adler32(checksum_, &data, 1u);
43     }
44     buffer_.push_back(data);
45     return true;
46 }
47 
WriteBytes(const std::vector<uint8_t> & bytes)48 bool FileWriter::WriteBytes(const std::vector<uint8_t> &bytes)
49 {
50     if (UNLIKELY(bytes.empty())) {
51         return true;
52     }
53 
54     if (LIKELY(count_checksum_)) {
55         checksum_ = adler32(checksum_, bytes.data(), bytes.size());
56     }
57 
58     buffer_.insert(buffer_.end(), bytes.begin(), bytes.end());
59     return true;
60 }
61 
FinishWrite()62 bool FileWriter::FinishWrite()
63 {
64     if (file_ == nullptr) {
65         return false;
66     }
67     const auto &buf = GetBuffer();
68     auto length = buf.size();
69     bool ret = fwrite(buf.data(), sizeof(decltype(buf.back())), length, file_) == length;
70     fclose(file_);
71     file_ = nullptr;
72     return ret;
73 }
74 
75 }  // namespace panda::panda_file
76