1 /* 2 * Copyright 2012 Haiku, Inc. All rights reserved. 3 * Distributed under the terms of the MIT License. 4 * 5 * Authors: 6 * Paweł Dziepak, pdziepak@quarnos.org 7 */ 8 #ifndef XDR_H 9 #define XDR_H 10 11 12 #include <SupportDefs.h> 13 14 15 namespace XDR { 16 17 class Stream { 18 public: 19 typedef uint32 Position; 20 21 virtual ~Stream(); 22 23 inline const void* Buffer() const; 24 inline Position Current() const; 25 26 protected: 27 Stream(void* buffer, uint32 size); 28 29 inline uint32 _PositionToSize() const; 30 inline uint32 _RealSize(uint32 size) const; 31 32 uint32* fBuffer; 33 uint32 fSize; 34 Position fPosition; 35 }; 36 37 class ReadStream : public Stream { 38 public: 39 ReadStream(void* buffer, uint32 size); 40 virtual ~ReadStream(); 41 42 inline void SetPosition(Position position); 43 44 inline int Size() const; 45 46 int32 GetInt(); 47 uint32 GetUInt(); 48 int64 GetHyper(); 49 uint64 GetUHyper(); 50 51 inline bool GetBoolean(); 52 53 char* GetString(); 54 55 const void* GetOpaque(uint32* size); 56 57 inline bool IsEOF() const; 58 59 private: 60 bool fEOF; 61 }; 62 63 class WriteStream : public Stream { 64 public: 65 WriteStream(); 66 WriteStream(const WriteStream& x); 67 virtual ~WriteStream(); 68 69 inline int Size() const; 70 void Clear(); 71 72 status_t InsertUInt(Stream::Position pos, uint32 x); 73 74 status_t AddInt(int32 x); 75 status_t AddUInt(uint32 x); 76 status_t AddHyper(int64 x); 77 status_t AddUHyper(uint64 x); 78 79 inline status_t AddBoolean(bool x); 80 81 status_t AddString(const char* str, uint32 maxlen = 0); 82 83 status_t AddOpaque(const void* ptr, uint32 size); 84 status_t AddOpaque(const WriteStream& stream); 85 86 status_t Append(const WriteStream& stream); 87 88 inline status_t Error() const; 89 90 private: 91 status_t _CheckResize(uint32 size); 92 93 status_t fError; 94 95 static const uint32 kInitialSize = 64; 96 }; 97 98 99 inline const void* Buffer()100Stream::Buffer() const 101 { 102 return fBuffer; 103 } 104 105 106 inline Stream::Position Current()107Stream::Current() const 108 { 109 return fPosition; 110 } 111 112 113 inline void SetPosition(Position position)114ReadStream::SetPosition(Position position) 115 { 116 fPosition = position; 117 } 118 119 120 inline int Size()121ReadStream::Size() const 122 { 123 return fSize; 124 } 125 126 127 inline bool IsEOF()128ReadStream::IsEOF() const 129 { 130 return fEOF; 131 } 132 133 134 inline bool GetBoolean()135ReadStream::GetBoolean() 136 { 137 return GetInt() != 0; 138 } 139 140 141 inline int Size()142WriteStream::Size() const 143 { 144 return fPosition * sizeof(uint32); 145 } 146 147 148 inline status_t AddBoolean(bool x)149WriteStream::AddBoolean(bool x) 150 { 151 return AddInt(static_cast<int32>(x)); 152 } 153 154 155 inline status_t Error()156WriteStream::Error() const 157 { 158 return fError; 159 } 160 161 162 } // namespace XDR 163 164 165 #endif // XDR_H 166 167