1 /*
2  *  Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #ifndef SYSTEM_WRAPPERS_INCLUDE_FILE_WRAPPER_H_
12 #define SYSTEM_WRAPPERS_INCLUDE_FILE_WRAPPER_H_
13 
14 #include <stddef.h>
15 #include <stdio.h>
16 
17 #include "common_types.h"  // NOLINT(build/include)
18 #include "rtc_base/criticalsection.h"
19 #include "typedefs.h"  // NOLINT(build/include)
20 
21 // Implementation of an InStream and OutStream that can read (exclusive) or
22 // write from/to a file.
23 
24 namespace webrtc {
25 
26 // TODO(tommi): Remove the base classes, rename to rtc::File and move to base.
27 class FileWrapper : public InStream, public OutStream {
28  public:
29   static const size_t kMaxFileNameSize = 1024;
30 
31   // Factory methods.
32   // TODO(tommi): Remove Create().
33   static FileWrapper* Create();
34   static FileWrapper Open(const char* file_name_utf8, bool read_only);
35 
36   FileWrapper(FILE* file, size_t max_size);
37   ~FileWrapper() override;
38 
39   // Support for move semantics.
40   FileWrapper(FileWrapper&& other);
41   FileWrapper& operator=(FileWrapper&& other);
42 
43   // Returns true if a file has been opened.
is_open()44   bool is_open() const { return file_ != nullptr; }
45 
46   // Opens a file in read or write mode, decided by the read_only parameter.
47   bool OpenFile(const char* file_name_utf8, bool read_only);
48 
49   // Initializes the wrapper from an existing handle.  The wrapper
50   // takes ownership of |handle| and closes it in CloseFile().
51   bool OpenFromFileHandle(FILE* handle);
52 
53   void CloseFile();
54 
55   // Limits the file size to |bytes|. Writing will fail after the cap
56   // is hit. Pass zero to use an unlimited size.
57   // TODO(tommi): Could we move this out into a separate class?
58   void SetMaxFileSize(size_t bytes);
59 
60   // Flush any pending writes.  Note: Flushing when closing, is not required.
61   int Flush();
62 
63   // Rewinds the file to the start.
64   int Rewind() override;
65   int Read(void* buf, size_t length) override;
66   bool Write(const void* buf, size_t length) override;
67 
68  private:
69   FileWrapper();
70 
71   void CloseFileImpl();
72   int FlushImpl();
73 
74   // TODO(tommi): Remove the lock.
75   rtc::CriticalSection lock_;
76 
77   FILE* file_ = nullptr;
78   size_t position_ = 0;
79   size_t max_size_in_bytes_ = 0;
80 
81   // Copying is not supported.
82   FileWrapper(const FileWrapper&) = delete;
83   FileWrapper& operator=(const FileWrapper&) = delete;
84 };
85 
86 }  // namespace webrtc
87 
88 #endif  // SYSTEM_WRAPPERS_INCLUDE_FILE_WRAPPER_H_
89