00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023 #ifndef SHEEP_MISC_BINARYSTREAM_H
00024 #define SHEEP_MISC_BINARYSTREAM_H
00025
00026 #include "config.h"
00027
00028 #include <algorithm>
00029 #include <cassert>
00030 #include <cstddef>
00031 #include <cstdio>
00032 #include <string>
00033
00034 namespace sheep {
00035
00036 class BinaryStream {
00037 public:
00038 struct BaseException {};
00039 struct ReadException : public BaseException {};
00040 struct WriteException : public BaseException {};
00041 struct SeekException : public BaseException {};
00042
00043 enum StreamMode {
00044 InputStream,
00045 OutputStream
00046 };
00047
00048 enum Endianness {
00049 NativeEndian,
00050 LittleEndian,
00051 BigEndian
00052 };
00053
00054 BinaryStream();
00055 BinaryStream(
00056 const std::string &filename,
00057 StreamMode mode,
00058 Endianness endianness = NativeEndian
00059 );
00060
00061 ~BinaryStream();
00062
00063 void Open(
00064 const std::string &filename,
00065 StreamMode mode,
00066 Endianness endianness = NativeEndian
00067 );
00068
00069 void Close()
00070 throw(WriteException);
00071
00072 bool IsOpen() const;
00073
00074
00075
00076
00077 void SetBufferSize(int size);
00078
00079 void SetEndianness(Endianness endianness);
00080
00081 enum SeekOrigin {
00082 SeekFromBeginning,
00083 SeekFromCurrent,
00084 SeekFromEnd
00085 };
00086
00087 void Seek(long offset, SeekOrigin origin)
00088 throw(SeekException);
00089
00090 long Tell() const
00091 throw(SeekException);
00092
00093
00094
00095 void Write(const void *data, size_t size)
00096 throw(WriteException);
00097
00098
00099
00100 void Read(void *data, size_t size)
00101 throw(ReadException);
00102
00103 template<typename T>
00104 void Write(T t)
00105 throw(WriteException);
00106
00107 template<typename T>
00108 void Read(T *t)
00109 throw(ReadException);
00110
00111 private:
00112 FILE *m_file;
00113 StreamMode m_mode;
00114 bool m_swap;
00115 char *m_buffer_base;
00116 char *m_buffer_end;
00117 char *m_buffer_ptr;
00118 int m_buffer_size;
00119
00120 Endianness get_host_endianness() const;
00121
00122 void initialize();
00123
00124 void flush_output_buffer()
00125 throw(WriteException);
00126
00127 size_t fill_input_buffer()
00128 throw(ReadException);
00129
00130 void invalidate_input_buffer();
00131
00132
00133 template<typename T>
00134 void swap_bytes(T *t) const;
00135 };
00136
00137 #include "binarystream.inl"
00138
00139 }
00140
00141 #endif // !SHEEP_MISC_BINARYSTREAM_H