1 /* 2 * Copyright (C) 2007-2020 by the Widelands Development Team 3 * 4 * This program is free software; you can redistribute it and/or 5 * modify it under the terms of the GNU General Public License 6 * as published by the Free Software Foundation; either version 2 7 * of the License, or (at your option) any later version. 8 * 9 * This program is distributed in the hope that it will be useful, 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 * GNU General Public License for more details. 13 * 14 * You should have received a copy of the GNU General Public License 15 * along with this program; if not, write to the Free Software 16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. 17 * 18 */ 19 20 #ifndef WL_IO_STREAMREAD_H 21 #define WL_IO_STREAMREAD_H 22 23 #include "base/macros.h" 24 #include "base/wexception.h" 25 26 /** 27 * Abstract base class for stream-like data sources. 28 * It is intended for deserializing network packets and for reading log-type 29 * data from disk. 30 * 31 * This is not intended for pipes or pipe-like operations, and all reads 32 * are "blocking". Once \ref data returns 0, or any number less than the 33 * requested number of bytes, the stream is at its end. 34 * 35 * All implementations need to implement \ref data and \ref end_of_file . 36 * 37 * Convenience functions are provided for many data types. 38 */ 39 class StreamRead { 40 public: StreamRead()41 explicit StreamRead() { 42 } 43 virtual ~StreamRead(); 44 45 /** 46 * Read a number of bytes from the stream. 47 * 48 * \return the number of bytes that were actually read. Will return 0 at 49 * end of stream. 50 */ 51 virtual size_t data(void* read_data, size_t bufsize) = 0; 52 53 /** 54 * \return \c true if the end of file / end of stream has been reached. 55 */ 56 virtual bool end_of_file() const = 0; 57 58 void data_complete(void* data, size_t size); 59 60 int8_t signed_8(); 61 uint8_t unsigned_8(); 62 int16_t signed_16(); 63 uint16_t unsigned_16(); 64 int32_t signed_32(); 65 uint32_t unsigned_32(); 66 float float_32(); 67 std::string string(); c_string()68 virtual char const* c_string() { 69 throw; 70 } 71 72 /// Base of all exceptions that are caused by errors in the data that is 73 /// read. 74 class DataError : public WException { 75 public: 76 DataError(char const* const fmt, ...) PRINTF_FORMAT(2, 3); 77 }; 78 #define data_error(...) DataError(__VA_ARGS__) 79 80 private: 81 DISALLOW_COPY_AND_ASSIGN(StreamRead); 82 }; 83 84 #endif // end of include guard: WL_IO_STREAMREAD_H 85