• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright (c) 2021-2024 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 ark::panda_file {
20 
FileWriter(const std::string & fileName)21 FileWriter::FileWriter(const std::string &fileName) : 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(fileName.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     return WriteBytes({data});
42 }
43 
WriteBytes(const std::vector<uint8_t> & bytes)44 bool FileWriter::WriteBytes(const std::vector<uint8_t> &bytes)
45 {
46     if (file_ == nullptr) {
47         return false;
48     }
49 
50     if (bytes.empty()) {
51         return true;
52     }
53 
54     if (countChecksum_) {
55         checksum_ = adler32(checksum_, bytes.data(), bytes.size());
56     }
57 
58     if (fwrite(bytes.data(), sizeof(decltype(bytes.back())), bytes.size(), file_) != bytes.size()) {
59         return false;
60     }
61 
62     offset_ += bytes.size();
63     return true;
64 }
65 
66 }  // namespace ark::panda_file
67