Debian Codegraph @

src/dmlc-core/include/dmlc/io.h

raw symbols SCIP
1 /*!
2 * Copyright (c) 2015 by Contributors
3 * \file io.h
4 * \brief defines serializable interface of dmlc
5 */
6 #ifndef DMLC_IO_H_
7 #define DMLC_IO_H_
8 #include <cstdio>
9 #include <cstring>
10 #include <istream>
11 #include <ostream>
12 #include <streambuf>
13 #include <string>
14 #include <vector>
15
16 #include "./logging.h"
17
18 // include uint64_t only to make io standalone
19 #ifdef _MSC_VER
20 /*! \brief uint64 */
21 typedef unsigned __int64 uint64_t;
22 #else
23 #include <inttypes.h>
24 #endif
25
26 /*! \brief namespace for dmlc */
27 namespace dmlc {
28 /*!
29 * \brief interface of stream I/O for serialization
30 */
31 class Stream { // NOLINT(*)
32 public:
33 /*!
34 * \brief reads data from a stream
35 * \param ptr pointer to a memory buffer
36 * \param size The maximum number of bytes to read
37 * \return The number of bytes read from the stream
38 */
39 virtual size_t Read(void *ptr, size_t size) = 0;
40 /*!
41 * \brief writes data to a stream
42 * \param ptr pointer to a memory buffer
43 * \param size The maximum number of bytes to write
44 * \return The number of bytes written
45 */
46 virtual size_t Write(const void *ptr, size_t size) = 0;
47 /*! \brief virtual destructor */
48 virtual ~Stream(void) {}
49 /*!
50 * \brief generic factory function
51 * create an stream, the stream will close the underlying files upon deletion
52 *
53 * \param uri the uri of the input currently we support
54 * hdfs://, s3://, and file:// by default file:// will be used
55 * \param flag can be "w", "r", "a"
56 * \param allow_null whether NULL can be returned, or directly report error
57 * \return the created stream, can be NULL when allow_null == true and file do not exist
58 */
59 static Stream *Create(const char *uri, const char *const flag, bool allow_null = false);
60 // helper functions to write/read different data structures
61 /*!
62 * \brief writes a data to stream.
63 *
64 * dmlc::Stream support Write/Read of most STL composites and base types.
65 * If the data type is not supported, a compile time error will be issued.
66 *
67 * This function is endian-aware,
68 * the output endian defined by DMLC_IO_USE_LITTLE_ENDIAN
69 *
70 * \param data data to be written
71 * \tparam T the data type to be written
72 */
73 template <typename T>
74 inline void Write(const T &data);
75 /*!
76 * \brief loads a data from stream.
77 *
78 * dmlc::Stream support Write/Read of most STL composites and base types.
79 * If the data type is not supported, a compile time error will be issued.
80 *
81 * This function is endian-aware,
82 * the input endian defined by DMLC_IO_USE_LITTLE_ENDIAN
83 *
84 * \param out_data place holder of data to be deserialized
85 * \return whether the load was successful
86 */
87 template <typename T>
88 inline bool Read(T *out_data);
89 /*!
90 * \brief Endian aware write array of data.
91 * \param data The data pointer
92 * \param num_elems Number of elements
93 * \tparam T the data type.
94 */
95 template <typename T>
96 inline void WriteArray(const T *data, size_t num_elems);
97 /*!
98 * \brief Endian aware read array of data.
99 * \param data The data pointer
100 * \param num_elems Number of elements
101 * \tparam T the data type.
102 * \return whether the load was successful
103 */
104 template <typename T>
105 inline bool ReadArray(T *data, size_t num_elems);
106 };
107
108 /*! \brief interface of i/o stream that support seek */
109 class SeekStream : public Stream {
110 public:
111 // virtual destructor
112 virtual ~SeekStream(void) {}
113 /*! \brief seek to certain position of the file */
114 virtual void Seek(size_t pos) = 0;
115 /*! \brief tell the position of the stream */
116 virtual size_t Tell(void) = 0;
117 /*!
118 * \brief generic factory function
119 * create an SeekStream for read only,
120 * the stream will close the underlying files upon deletion
121 * error will be reported and the system will exit when create failed
122 * \param uri the uri of the input currently we support
123 * hdfs://, s3://, and file:// by default file:// will be used
124 * \param allow_null whether NULL can be returned, or directly report error
125 * \return the created stream, can be NULL when allow_null == true and file do not exist
126 */
127 static SeekStream *CreateForRead(const char *uri, bool allow_null = false);
128 };
129
130 /*! \brief interface for serializable objects */
131 class Serializable {
132 public:
133 /*! \brief virtual destructor */
134 virtual ~Serializable() {}
135 /*!
136 * \brief load the model from a stream
137 * \param fi stream where to load the model from
138 */
139 virtual void Load(Stream *fi) = 0;
140 /*!
141 * \brief saves the model to a stream
142 * \param fo stream where to save the model to
143 */
144 virtual void Save(Stream *fo) const = 0;
145 };
146
147 /*!
148 * \brief input split creates that allows reading
149 * of records from split of data,
150 * independent part that covers all the dataset
151 *
152 * see InputSplit::Create for definition of record
153 */
154 class InputSplit {
155 public:
156 /*! \brief a blob of memory region */
157 struct Blob {
158 /*! \brief points to start of the memory region */
159 void *dptr;
160 /*! \brief size of the memory region */
161 size_t size;
162 };
163 /*!
164 * \brief hint the inputsplit how large the chunk size
165 * it should return when implementing NextChunk
166 * this is a hint so may not be enforced,
167 * but InputSplit will try adjust its internal buffer
168 * size to the hinted value
169 */
170 virtual void HintChunkSize(size_t /*chunk_size*/) {}
171 /*! \brief get the total size of the InputSplit */
172 virtual size_t GetTotalSize(void) = 0;
173 /*! \brief reset the position of InputSplit to beginning */
174 virtual void BeforeFirst(void) = 0;
175 /*!
176 * \brief get the next record, the returning value
177 * is valid until next call to NextRecord, NextChunk or NextBatch
178 * caller can modify the memory content of out_rec
179 *
180 * For text, out_rec contains a single line
181 * For recordio, out_rec contains one record content(with header striped)
182 *
183 * \param out_rec used to store the result
184 * \return true if we can successfully get next record
185 * false if we reached end of split
186 * \sa InputSplit::Create for definition of record
187 */
188 virtual bool NextRecord(Blob *out_rec) = 0;
189 /*!
190 * \brief get a chunk of memory that can contain multiple records,
191 * the caller needs to parse the content of the resulting chunk,
192 * for text file, out_chunk can contain data of multiple lines
193 * for recordio, out_chunk can contain multiple records(including headers)
194 *
195 * This function ensures there won't be partial record in the chunk
196 * caller can modify the memory content of out_chunk,
197 * the memory is valid until next call to NextRecord, NextChunk or NextBatch
198 *
199 * Usually NextRecord is sufficient, NextChunk can be used by some
200 * multi-threaded parsers to parse the input content
201 *
202 * \param out_chunk used to store the result
203 * \return true if we can successfully get next record
204 * false if we reached end of split
205 * \sa InputSplit::Create for definition of record
206 * \sa RecordIOChunkReader to parse recordio content from out_chunk
207 */
208 virtual bool NextChunk(Blob *out_chunk) = 0;
209 /*!
210 * \brief get a chunk of memory that can contain multiple records,
211 * with hint for how many records is needed,
212 * the caller needs to parse the content of the resulting chunk,
213 * for text file, out_chunk can contain data of multiple lines
214 * for recordio, out_chunk can contain multiple records(including headers)
215 *
216 * This function ensures there won't be partial record in the chunk
217 * caller can modify the memory content of out_chunk,
218 * the memory is valid until next call to NextRecord, NextChunk or NextBatch
219 *
220 *
221 * \param out_chunk used to store the result
222 * \return true if we can successfully get next record
223 * false if we reached end of split
224 * \sa InputSplit::Create for definition of record
225 * \sa RecordIOChunkReader to parse recordio content from out_chunk
226 */
227 virtual bool NextBatch(Blob *out_chunk, size_t /*n_records*/) {
228 return NextChunk(out_chunk);
229 }
230 /*! \brief destructor*/
231 virtual ~InputSplit(void) DMLC_THROW_EXCEPTION {}
232 /*!
233 * \brief reset the Input split to a certain part id,
234 * The InputSplit will be pointed to the head of the new specified segment.
235 * This feature may not be supported by every implementation of InputSplit.
236 * \param part_index The part id of the new input.
237 * \param num_parts The total number of parts.
238 */
239 virtual void ResetPartition(unsigned part_index, unsigned num_parts) = 0;
240 /*!
241 * \brief factory function:
242 * create input split given a uri
243 * \param uri the uri of the input, can contain hdfs prefix
244 * \param part_index the part id of current input
245 * \param num_parts total number of splits
246 * \param type type of record
247 * List of possible types: "text", "recordio", "indexed_recordio"
248 * - "text":
249 * text file, each line is treated as a record
250 * input split will split on '\\n' or '\\r'
251 * - "recordio":
252 * binary recordio file, see recordio.h
253 * - "indexed_recordio":
254 * binary recordio file with index, see recordio.h
255 * \return a new input split
256 * \sa InputSplit::Type
257 */
258 static InputSplit *Create(
259 const char *uri, unsigned part_index, unsigned num_parts, const char *type);
260 /*!
261 * \brief factory function:
262 * create input split given a uri for input and index
263 * \param uri the uri of the input, can contain hdfs prefix
264 * \param index_uri the uri of the index, can contain hdfs prefix
265 * \param part_index the part id of current input
266 * \param num_parts total number of splits
267 * \param type type of record
268 * List of possible types: "text", "recordio", "indexed_recordio"
269 * - "text":
270 * text file, each line is treated as a record
271 * input split will split on '\\n' or '\\r'
272 * - "recordio":
273 * binary recordio file, see recordio.h
274 * - "indexed_recordio":
275 * binary recordio file with index, see recordio.h
276 * \param shuffle whether to shuffle the output from the InputSplit,
277 * supported only by "indexed_recordio" type.
278 * Defaults to "false"
279 * \param seed random seed to use in conjunction with the "shuffle"
280 * option. Defaults to 0
281 * \param batch_size a hint to InputSplit what is the intended number
282 * of examples return per batch. Used only by
283 * "indexed_recordio" type
284 * \param recurse_directories whether to recursively traverse directories
285 * \return a new input split
286 * \sa InputSplit::Type
287 */
288 static InputSplit *Create(const char *uri, const char *index_uri, unsigned part_index,
289 unsigned num_parts, const char *type, const bool shuffle = false, const int seed = 0,
290 const size_t batch_size = 256, const bool recurse_directories = false);
291 };
292
293 #ifndef _LIBCPP_SGX_NO_IOSTREAMS
294 /*!
295 * \brief a std::ostream class that can can wrap Stream objects,
296 * can use ostream with that output to underlying Stream
297 *
298 * Usage example:
299 * \code
300 *
301 * Stream *fs = Stream::Create("hdfs:///test.txt", "w");
302 * dmlc::ostream os(fs);
303 * os << "hello world" << std::endl;
304 * delete fs;
305 * \endcode
306 */
307 class ostream : public std::basic_ostream<char> {
308 public:
309 /*!
310 * \brief construct std::ostream type
311 * \param stream the Stream output to be used
312 * \param buffer_size internal streambuf size
313 */
314 explicit ostream(Stream *stream, size_t buffer_size = (1 << 10))
315 : std::basic_ostream<char>(NULL), buf_(buffer_size) {
316 this->set_stream(stream);
317 }
318 // explictly synchronize the buffer
319 virtual ~ostream() DMLC_NO_EXCEPTION {
320 buf_.pubsync();
321 }
322 /*!
323 * \brief set internal stream to be stream, reset states
324 * \param stream new stream as output
325 */
326 inline void set_stream(Stream *stream) {
327 buf_.set_stream(stream);
328 this->rdbuf(&buf_);
329 }
330
331 /*! \return how many bytes we written so far */
332 inline size_t bytes_written(void) const {
333 return buf_.bytes_out();
334 }
335
336 private:
337 // internal streambuf
338 class OutBuf : public std::streambuf {
339 public:
340 explicit OutBuf(size_t buffer_size) : stream_(NULL), buffer_(buffer_size), bytes_out_(0) {
341 if (buffer_size == 0) {
342 buffer_.resize(2);
343 }
344 }
345 // set stream to the buffer
346 inline void set_stream(Stream *stream);
347
348 inline size_t bytes_out() const {
349 return bytes_out_;
350 }
351
352 private:
353 /*! \brief internal stream by StreamBuf */
354 Stream *stream_;
355 /*! \brief internal buffer */
356 std::vector<char> buffer_;
357 /*! \brief number of bytes written so far */
358 size_t bytes_out_;
359 // override sync
360 inline int_type sync(void);
361 // override overflow
362 inline int_type overflow(int c);
363 };
364 /*! \brief buffer of the stream */
365 OutBuf buf_;
366 };
367
368 /*!
369 * \brief a std::istream class that can can wrap Stream objects,
370 * can use istream with that output to underlying Stream
371 *
372 * Usage example:
373 * \code
374 *
375 * Stream *fs = Stream::Create("hdfs:///test.txt", "r");
376 * dmlc::istream is(fs);
377 * is >> mydata;
378 * delete fs;
379 * \endcode
380 */
381 class istream : public std::basic_istream<char> {
382 public:
383 /*!
384 * \brief construct std::ostream type
385 * \param stream the Stream output to be used
386 * \param buffer_size internal buffer size
387 */
388 explicit istream(Stream *stream, size_t buffer_size = (1 << 10))
389 : std::basic_istream<char>(NULL), buf_(buffer_size) {
390 this->set_stream(stream);
391 }
392 virtual ~istream() DMLC_NO_EXCEPTION {}
393 /*!
394 * \brief set internal stream to be stream, reset states
395 * \param stream new stream as output
396 */
397 inline void set_stream(Stream *stream) {
398 buf_.set_stream(stream);
399 this->rdbuf(&buf_);
400 }
401 /*! \return how many bytes we read so far */
402 inline size_t bytes_read(void) const {
403 return buf_.bytes_read();
404 }
405
406 private:
407 // internal streambuf
408 class InBuf : public std::streambuf {
409 public:
410 explicit InBuf(size_t buffer_size) : stream_(NULL), bytes_read_(0), buffer_(buffer_size) {
411 if (buffer_size == 0) {
412 buffer_.resize(2);
413 }
414 }
415 // set stream to the buffer
416 inline void set_stream(Stream *stream);
417 // return how many bytes read so far
418 inline size_t bytes_read(void) const {
419 return bytes_read_;
420 }
421
422 private:
423 /*! \brief internal stream by StreamBuf */
424 Stream *stream_;
425 /*! \brief how many bytes we read so far */
426 size_t bytes_read_;
427 /*! \brief internal buffer */
428 std::vector<char> buffer_;
429 // override underflow
430 inline int_type underflow();
431 };
432 /*! \brief input buffer */
433 InBuf buf_;
434 };
435 #endif
436 } // namespace dmlc
437
438 #include "./serializer.h"
439
440 namespace dmlc {
441 // implementations of inline functions
442 template <typename T>
443 inline void Stream::Write(const T &data) {
444 serializer::Handler<T>::Write(this, data);
445 }
446 template <typename T>
447 inline bool Stream::Read(T *out_data) {
448 return serializer::Handler<T>::Read(this, out_data);
449 }
450
451 template <typename T>
452 inline void Stream::WriteArray(const T *data, size_t num_elems) {
453 for (size_t i = 0; i < num_elems; ++i) {
454 this->Write<T>(data[i]);
455 }
456 }
457
458 template <typename T>
459 inline bool Stream::ReadArray(T *data, size_t num_elems) {
460 for (size_t i = 0; i < num_elems; ++i) {
461 if (!this->Read<T>(data + i)) {
462 return false;
463 }
464 }
465 return true;
466 }
467
468 #ifndef _LIBCPP_SGX_NO_IOSTREAMS
469 // implementations for ostream
470 inline void ostream::OutBuf::set_stream(Stream *stream) {
471 if (stream_ != NULL) {
472 this->pubsync();
473 }
474 this->stream_ = stream;
475 this->setp(&buffer_[0], &buffer_[0] + buffer_.size() - 1);
476 }
477 inline int ostream::OutBuf::sync(void) {
478 if (stream_ == NULL) {
479 return -1;
480 }
481 std::ptrdiff_t n = pptr() - pbase();
482 stream_->Write(pbase(), n);
483 this->pbump(-static_cast<int>(n));
484 bytes_out_ += n;
485 return 0;
486 }
487 inline int ostream::OutBuf::overflow(int c) {
488 *(this->pptr()) = c;
489 std::ptrdiff_t n = pptr() - pbase();
490 this->pbump(-static_cast<int>(n));
491 if (c == EOF) {
492 stream_->Write(pbase(), n);
493 bytes_out_ += n;
494 } else {
495 stream_->Write(pbase(), n + 1);
496 bytes_out_ += n + 1;
497 }
498 return c;
499 }
500
501 // implementations for istream
502 inline void istream::InBuf::set_stream(Stream *stream) {
503 stream_ = stream;
504 this->setg(&buffer_[0], &buffer_[0], &buffer_[0]);
505 }
506 inline int istream::InBuf::underflow() {
507 char *bhead = &buffer_[0];
508 if (this->gptr() == this->egptr()) {
509 size_t sz = stream_->Read(bhead, buffer_.size());
510 this->setg(bhead, bhead, bhead + sz);
511 bytes_read_ += sz;
512 }
513 if (this->gptr() == this->egptr()) {
514 return traits_type::eof();
515 } else {
516 return traits_type::to_int_type(*gptr());
517 }
518 }
519 #endif
520
521 namespace io {
522 /*! \brief common data structure for URI */
523 struct URI {
524 /*! \brief protocol */
525 std::string protocol;
526 /*!
527 * \brief host name, namenode for HDFS, bucket name for s3
528 */
529 std::string host;
530 /*! \brief name of the path */
531 std::string name;
532 /*! \brief enable default constructor */
533 URI(void) {}
534 /*!
535 * \brief construct from URI string
536 */
537 explicit URI(const char *uri) {
538 const char *p = std::strstr(uri, "://");
539 if (p == NULL) {
540 name = uri;
541 } else {
542 protocol = std::string(uri, p - uri + 3);
543 uri = p + 3;
544 p = std::strchr(uri, '/');
545 if (p == NULL) {
546 host = uri;
547 name = '/';
548 } else {
549 host = std::string(uri, p - uri);
550 name = p;
551 }
552 }
553 }
554 /*! \brief string representation */
555 inline std::string str(void) const {
556 return protocol + host + name;
557 }
558 };
559
560 /*! \brief type of file */
561 enum FileType {
562 /*! \brief the file is file */
563 kFile,
564 /*! \brief the file is directory */
565 kDirectory
566 };
567
568 /*! \brief use to store file information */
569 struct FileInfo {
570 /*! \brief full path to the file */
571 URI path;
572 /*! \brief the size of the file */
573 size_t size;
574 /*! \brief the type of the file */
575 FileType type;
576 /*! \brief default constructor */
577 FileInfo() : size(0), type(kFile) {}
578 };
579
580 /*! \brief file system system interface */
581 class FileSystem {
582 public:
583 /*!
584 * \brief get singleton of filesystem instance according to URI
585 * \param path can be s3://..., hdfs://..., file://...,
586 * empty string(will return local)
587 * \return a corresponding filesystem, report error if
588 * we cannot find a matching system
589 */
590 static FileSystem *GetInstance(const URI &path);
591 /*! \brief virtual destructor */
592 virtual ~FileSystem() {}
593 /*!
594 * \brief get information about a path
595 * \param path the path to the file
596 * \return the information about the file
597 */
598 virtual FileInfo GetPathInfo(const URI &path) = 0;
599 /*!
600 * \brief list files in a directory
601 * \param path to the file
602 * \param out_list the output information about the files
603 */
604 virtual void ListDirectory(const URI &path, std::vector<FileInfo> *out_list) = 0;
605 /*!
606 * \brief list files in a directory recursively using ListDirectory
607 * \param path to the file
608 * \param out_list the output information about the files
609 */
610 virtual void ListDirectoryRecursive(const URI &path, std::vector<FileInfo> *out_list);
611 /*!
612 * \brief open a stream
613 * \param path path to file
614 * \param flag can be "w", "r", "a
615 * \param allow_null whether NULL can be returned, or directly report error
616 * \return the created stream, can be NULL when allow_null == true and file do not exist
617 */
618 virtual Stream *Open(const URI &path, const char *const flag, bool allow_null = false) = 0;
619 /*!
620 * \brief open a seekable stream for read
621 * \param path the path to the file
622 * \param allow_null whether NULL can be returned, or directly report error
623 * \return the created stream, can be NULL when allow_null == true and file do not exist
624 */
625 virtual SeekStream *OpenForRead(const URI &path, bool allow_null = false) = 0;
626 };
627
628 } // namespace io
629 } // namespace dmlc
630 #endif // DMLC_IO_H_