1 // Copyright 2022 Google LLC
2 //
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 // https://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 #include "contrib/brotli/utils/utils_brotli.h"
16
GetStreamSize(std::ifstream & stream)17 std::streamsize GetStreamSize(std::ifstream& stream) {
18 stream.seekg(0, std::ios_base::end);
19 std::streamsize ssize = stream.tellg();
20 stream.seekg(0, std::ios_base::beg);
21
22 return ssize;
23 }
24
ReadFile(const std::string & in_file_s)25 absl::StatusOr<std::vector<uint8_t>> ReadFile(const std::string& in_file_s) {
26 std::ifstream in_file(in_file_s);
27 if (!in_file.is_open()) {
28 return absl::UnavailableError("File could not be opened");
29 }
30
31 std::streamsize ssize = GetStreamSize(in_file);
32 if (ssize >= kFileMaxSize) {
33 return absl::UnavailableError("Incorrect size of file");
34 }
35
36 std::vector<uint8_t> out_buf(ssize);
37 in_file.read(reinterpret_cast<char*>(out_buf.data()), ssize);
38 if (ssize != in_file.gcount()) {
39 return absl::UnavailableError("Premature end of file");
40 }
41 if (in_file.fail() || in_file.eof()) {
42 return absl::UnavailableError("Error reading file");
43 }
44
45 return out_buf;
46 }
47
WriteFile(const std::string & out_file_s,const std::vector<uint8_t> & out_buf)48 absl::Status WriteFile(const std::string& out_file_s,
49 const std::vector<uint8_t>& out_buf) {
50 std::ofstream out_file(out_file_s);
51 if (!out_file.is_open()) {
52 return absl::UnavailableError("File could not be opened");
53 }
54
55 out_file.write(reinterpret_cast<const char*>(out_buf.data()), out_buf.size());
56 if (!out_file.good()) {
57 return absl::UnavailableError("Error writting file");
58 }
59
60 return absl::OkStatus();
61 }
62