// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "internal/platform/implementation/shared/file.h" #include #include #include #include #include "absl/memory/memory.h" #include "absl/strings/string_view.h" #include "absl/time/clock.h" #include "absl/time/time.h" #include "internal/base/file_path.h" #include "internal/base/files.h" #include "internal/platform/exception.h" namespace nearby { namespace shared { // InputFile std::unique_ptr IOFile::CreateInputFile( const absl::string_view file_path) { auto file = absl::WrapUnique(new IOFile(file_path)); file->OpenForRead(); return file; } void IOFile::OpenForRead() { file_ = std::fstream(path_, std::ios::binary | std::ios::in | std::ios::ate); total_size_ = Files::GetFileSize(FilePath(path_)).value_or(0); file_.seekg(0); } std::unique_ptr IOFile::CreateOutputFile(const absl::string_view path) { auto file = absl::WrapUnique(new IOFile(path)); file->OpenForWrite(); return file; } void IOFile::OpenForWrite() { file_.open(path_, std::ios::binary | std::ios::out); } ExceptionOr IOFile::Read(std::int64_t size) { if (!file_.is_open()) { return ExceptionOr{Exception::kIo}; } if (file_.peek() == EOF) { return ExceptionOr{ByteArray{}}; } if (!file_.good()) { return ExceptionOr{Exception::kIo}; } ByteArray bytes(size); std::unique_ptr read_bytes{new char[size]}; file_.read(read_bytes.get(), static_cast(size)); auto num_bytes_read = file_.gcount(); if (num_bytes_read == 0) { return ExceptionOr{Exception::kIo}; } return ExceptionOr(ByteArray(read_bytes.get(), num_bytes_read)); } Exception IOFile::Close() { if (file_.is_open()) { file_.close(); } return {Exception::kSuccess}; } Exception IOFile::Write(absl::string_view data) { if (!file_.is_open()) { return {Exception::kIo}; } if (!file_.good()) { return {Exception::kIo}; } file_.write(data.data(), data.size()); file_.flush(); return {file_.good() ? Exception::kSuccess : Exception::kIo}; } absl::Time IOFile::GetLastModifiedTime() const { // TODO(ftsui): Implement this method. return absl::Now(); } void IOFile::SetLastModifiedTime(absl::Time last_modified_time) { // TODO(ftsui): Implement this method. } } // namespace shared } // namespace nearby