Turi Create  4.0
union_fstream.hpp
1 /* Copyright © 2017 Apple Inc. All rights reserved.
2  *
3  * Use of this source code is governed by a BSD-3-clause license that can
4  * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
5  */
6 #ifndef FILEIO_UNION_FSTREAM_HPP
7 #define FILEIO_UNION_FSTREAM_HPP
8 #include <iostream>
9 #include <fstream>
10 #include <memory>
11 
12 namespace turi {
13 
14 /**
15  * \ingroup fileio
16  * A simple union of std::fstream and turi::hdfs::fstream.
17  * Also performs S3 downloading, uploading, and Curl downloading automatically.
18  */
20 
21  public:
22  enum stream_type {HDFS, STD, CACHE};
23  /**
24  * Constructs a union fstream from a filename. Based on the filename
25  * (whether it begins with hdfs://, or cache://)
26  * an appropriate stream type (HDFS, STD, or CACHE) is created.
27  *
28  * Throws an std::io_base_failure exception if fail to construct the stream.
29  */
30  union_fstream(std::string url,
31  std::ios_base::openmode mode = std::ios_base::in | std::ios_base::out,
32  std::string proxy="");
33 
34  /// Destructor
36 
37  /// Returns the current stream type. Whether it is a HDFS, STD, or cache stream
38  stream_type get_type() const;
39 
40  std::shared_ptr<std::istream> get_istream();
41 
42  std::shared_ptr<std::ostream> get_ostream();
43 
44  /**
45  * Returns the filename used to construct the union_fstream
46  */
47  std::string get_name() const;
48 
49  /**
50  * Returns the file size of the opened file.
51  * Returns (size_t)(-1) if there is no file opened, or if there is an
52  * error obtaining the file size.
53  */
54  size_t file_size();
55 
56  private:
57  union_fstream(const union_fstream& other) = delete;
58 
59  private:
60 
61  stream_type type;
62  std::string url;
63  size_t m_file_size = (size_t)(-1);
64 
65  std::shared_ptr<std::istream> input_stream;
66  std::shared_ptr<std::ostream> output_stream;
67 
68  // Hold the input stream from cache or s3 stream.
69  std::shared_ptr<std::istream> original_input_stream_handle;
70 };
71 
72 } // namespace turi
73 #endif
std::string get_name() const
stream_type get_type() const
Returns the current stream type. Whether it is a HDFS, STD, or cache stream.
union_fstream(std::string url, std::ios_base::openmode mode=std::ios_base::in|std::ios_base::out, std::string proxy="")
~union_fstream()
Destructor.