blob: c506c01f3b97297107714fbd33bfd8bed7f9922c [file] [log] [blame]
rspangler@google.com49fdf182009-10-10 00:57:34 +00001// Copyright (c) 2009 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
adlr@google.comc98a7ed2009-12-04 18:54:03 +00005#ifndef CHROMEOS_PLATFORM_UPDATE_ENGINE_FILE_WRITER_H__
6#define CHROMEOS_PLATFORM_UPDATE_ENGINE_FILE_WRITER_H__
rspangler@google.com49fdf182009-10-10 00:57:34 +00007
8#include <sys/types.h>
9#include <sys/stat.h>
10#include <fcntl.h>
11#include <unistd.h>
adlr@google.comc98a7ed2009-12-04 18:54:03 +000012#include "chromeos/obsolete_logging.h"
13#include "update_engine/utils.h"
rspangler@google.com49fdf182009-10-10 00:57:34 +000014
15// FileWriter is a class that is used to (synchronously, for now) write to
16// a file. This file is a thin wrapper around open/write/close system calls,
17// but provides and interface that can be customized by subclasses that wish
18// to filter the data.
19
20namespace chromeos_update_engine {
21
22class FileWriter {
23 public:
24 virtual ~FileWriter() {}
25
26 // Wrapper around open. Returns 0 on success or -errno on error.
27 virtual int Open(const char* path, int flags, mode_t mode) = 0;
28
29 // Wrapper around write. Returns bytes written on success or
30 // -errno on error.
31 virtual int Write(const void* bytes, size_t count) = 0;
32
33 // Wrapper around close. Returns 0 on success or -errno on error.
34 virtual int Close() = 0;
35};
36
37// Direct file writer is probably the simplest FileWriter implementation.
38// It calls the system calls directly.
39
40class DirectFileWriter : public FileWriter {
41 public:
42 DirectFileWriter() : fd_(-1) {}
43 virtual ~DirectFileWriter() {}
44
adlr@google.comc98a7ed2009-12-04 18:54:03 +000045 virtual int Open(const char* path, int flags, mode_t mode);
46 virtual int Write(const void* bytes, size_t count);
47 virtual int Close();
rspangler@google.com49fdf182009-10-10 00:57:34 +000048
adlr@google.comc98a7ed2009-12-04 18:54:03 +000049 int fd() const { return fd_; }
rspangler@google.com49fdf182009-10-10 00:57:34 +000050
51 private:
52 int fd_;
53};
54
adlr@google.comc98a7ed2009-12-04 18:54:03 +000055class ScopedFileWriterCloser {
56 public:
57 explicit ScopedFileWriterCloser(FileWriter* writer) : writer_(writer) {}
58 ~ScopedFileWriterCloser() {
59 int err = writer_->Close();
60 if (err)
61 LOG(ERROR) << "FileWriter::Close failed: "
62 << utils::ErrnoNumberAsString(-err);
63 }
64 private:
65 FileWriter* writer_;
66};
67
rspangler@google.com49fdf182009-10-10 00:57:34 +000068} // namespace chromeos_update_engine
69
adlr@google.comc98a7ed2009-12-04 18:54:03 +000070#endif // CHROMEOS_PLATFORM_UPDATE_ENGINE_FILE_WRITER_H__