strigi/src/streams
stringstream.h
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020 #ifndef STRIGI_STRINGSTREAM_H
00021 #define STRIGI_STRINGSTREAM_H
00022
00023
00024
00025
00026
00027
00028 #include "streambase.h"
00029
00030 #include <string.h>
00031
00032 namespace Strigi {
00033
00037 template <class T>
00038 class StringStream : public StreamBase<T> {
00039 private:
00040 int64_t markpt;
00041 T* data;
00042 bool dataowner;
00043 StringStream(const StringStream<T>&);
00044 void operator=(const StringStream<T>&);
00045 public:
00066 StringStream(const T* value, int32_t length = -1, bool copy = true);
00067 ~StringStream();
00068 int32_t read(const T*& start, int32_t min, int32_t max);
00069 int64_t skip(int64_t ntoskip);
00070 int64_t reset(int64_t pos);
00071 };
00072
00074 typedef StringStream<char> StringInputStream;
00075
00077 typedef StringStream<wchar_t> StringReader;
00078
00079 template <class T>
00080 StringStream<T>::StringStream(const T* value, int32_t length, bool copy)
00081 : markpt(0), dataowner(copy) {
00082 if (length < 0) {
00083 length = 0;
00084 while (value[length] != '\0') {
00085 length++;
00086 }
00087 }
00088 StreamBase<T>::m_size = length;
00089 if (copy) {
00090 data = new T[length+1];
00091 size_t s = (size_t)(length*sizeof(T));
00092 memcpy(data, value, s);
00093 data[length] = 0;
00094 } else {
00095
00096 data = (T*)value;
00097 }
00098 }
00099 template <class T>
00100 StringStream<T>::~StringStream() {
00101 if (dataowner) {
00102 delete [] data;
00103 }
00104 }
00105 template <class T>
00106 int32_t
00107 StringStream<T>::read(const T*& start, int32_t min, int32_t max) {
00108 int64_t left = StreamBase<T>::m_size - StreamBase<T>::m_position;
00109 if (left == 0) {
00110 StreamBase<T>::m_status = Eof;
00111 return -1;
00112 }
00113 if (min < 0) min = 0;
00114 int32_t nread = (int32_t)(max > left || max < 1) ?left :max;
00115 start = data + StreamBase<T>::m_position;
00116 StreamBase<T>::m_position += nread;
00117 if (StreamBase<T>::m_position == StreamBase<T>::m_size) {
00118 StreamBase<T>::m_status = Eof;
00119 }
00120 return nread;
00121 }
00122 template <class T>
00123 int64_t
00124 StringStream<T>::skip(int64_t ntoskip) {
00125 if (ntoskip == 0) return 0;
00126 const T* start;
00127 return read(start, ntoskip, ntoskip);
00128 }
00129 template <class T>
00130 int64_t
00131 StringStream<T>::reset(int64_t newpos) {
00132 if (newpos < 0) {
00133 StreamBase<T>::m_status = Ok;
00134 StreamBase<T>::m_position = 0;
00135 } else if (newpos < StreamBase<T>::m_size) {
00136 StreamBase<T>::m_status = Ok;
00137 StreamBase<T>::m_position = newpos;
00138 } else {
00139 StreamBase<T>::m_position = StreamBase<T>::m_size;
00140 StreamBase<T>::m_status = Eof;
00141 }
00142 return StreamBase<T>::m_position;
00143 }
00144
00145 }
00146
00147 #endif