blob: 0647b65ec1c737ce5af052cb32407f0f49675d1a [file] [log] [blame]
Patrick Venture22e38752018-11-21 08:52:49 -08001/*
2 * Copyright 2018 Google Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Patrick Venture64919ec2018-11-15 11:52:07 -080017#include "file_handler.hpp"
18
19#include <cstdint>
20#include <memory>
21#include <string>
22#include <vector>
23
24namespace blobs
25{
26
27bool FileHandler::open(const std::string& path)
28{
29 this->path = path;
30
31 if (file.is_open())
32 {
33 /* This wasn't properly closed somehow.
34 * TODO: Throw an error or just reset the state?
35 */
36 return false;
37 }
38
39 /* using ofstream no need to set out */
40 file.open(filename, std::ios::binary);
41 if (file.bad())
42 {
43 /* TODO: Oh no! Care about this. */
44 return false;
45 }
46
47 /* We were able to open the file for staging.
48 * TODO: We'll need to do other stuff to eventually.
49 */
50 return true;
51}
52
53void FileHandler::close()
54{
55 if (file.is_open())
56 {
57 file.close();
58 }
59 return;
60}
61
62bool FileHandler::write(std::uint32_t offset,
63 const std::vector<std::uint8_t>& data)
64{
65 if (!file.is_open())
66 {
67 return false;
68 }
69
70 /* We could track this, but if they write in a scattered method, this is
71 * easier.
72 */
73 file.seekp(offset, std::ios_base::beg);
74 if (!file.good())
75 {
76 /* the documentation wasn't super clear on fail vs bad in these cases,
77 * so let's only be happy with goodness.
78 */
79 return false;
80 }
81
82 file.write(reinterpret_cast<const char*>(data.data()), data.size());
83 if (!file.good())
84 {
85 return false;
86 }
87
88 return true;
89}
90
91} // namespace blobs