00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019 #ifndef OST_IO_BINARY_DATA_SINK_HH
00020 #define OST_IO_BINARY_DATA_SINK_HH
00021
00022
00023
00024
00025
00026
00027 #include <iostream>
00028
00029 #include <ost/io/module_config.hh>
00030
00031 namespace ost { namespace io {
00032
00033 class BinaryDataSink {
00034 public:
00035 BinaryDataSink(std::ostream& stream)
00036 : stream_(stream) {
00037 }
00038 template <typename SERIALIZABLE>
00039 BinaryDataSink& operator << (SERIALIZABLE object) {
00040 Serialize(*this, object);
00041 return *this;
00042 }
00043 template <typename SERIALIZABLE>
00044 BinaryDataSink& operator & (SERIALIZABLE object) {
00045 return this->operator<<(object);
00046 }
00047 std::ostream& Stream() {
00048 return stream_;
00049 }
00050
00051 bool IsSource() { return false; }
00052 private:
00053 std::ostream& stream_;
00054 };
00055
00056 namespace detail {
00057
00058 template <bool B, typename T>
00059 struct SerializeWriteHelper;
00060
00061 template <typename T>
00062 struct SerializeWriteHelper<false, T> {
00063 SerializeWriteHelper(BinaryDataSink& sink, T& value)
00064 {
00065 value.Serialize(sink);
00066 }
00067 };
00068
00069 template <typename T>
00070 struct SerializeWriteHelper<true, T> {
00071 SerializeWriteHelper(BinaryDataSink& sink, T& value)
00072 {
00073 sink.Stream().write(reinterpret_cast<char*>(&value), sizeof(T));
00074 }
00075 };
00076 }
00077
00078 template <typename T>
00079 void Serialize(BinaryDataSink& sink, const T& value)
00080 {
00081 detail::SerializeWriteHelper<boost::is_integral<T>::value ||
00082 boost::is_floating_point<T>::value,
00083 T>(sink, const_cast<T&>(value));
00084 }
00085
00086
00087 inline void RawSerialize(BinaryDataSink& sink, char* value, size_t size)
00088 {
00089 sink.Stream().write(reinterpret_cast<char*>(value), size);
00090 }
00091
00092 inline void Serialize(BinaryDataSink& sink, const String& str) {
00093 size_t str_len=str.length();
00094 sink.Stream().write(reinterpret_cast<char*>(&str_len), sizeof(size_t));
00095 sink.Stream().write(str.c_str(), str.length());
00096 }
00097 }}
00098
00099 #endif