Panda3D
|
00001 // Filename: fakestringstream.h 00002 // Created by: cary (04Feb99) 00003 // 00004 //////////////////////////////////////////////////////////////////// 00005 // 00006 // PANDA 3D SOFTWARE 00007 // Copyright (c) Carnegie Mellon University. All rights reserved. 00008 // 00009 // All use of this software is subject to the terms of the revised BSD 00010 // license. You should have received a copy of this license along 00011 // with this source code in a file named "LICENSE." 00012 // 00013 //////////////////////////////////////////////////////////////////// 00014 00015 #ifndef FAKESTRINGSTREAM_H 00016 #define FAKESTRINGSTREAM_H 00017 00018 #include <strstream.h> 00019 #include <string.h> 00020 #include <string> 00021 00022 #ifdef HAVE_NAMESPACE 00023 using namespace std; 00024 #endif 00025 00026 class fake_istream_buffer { 00027 public: 00028 fake_istream_buffer() { 00029 _len = 0; 00030 _str = ""; 00031 } 00032 fake_istream_buffer(const string &source) { 00033 _len = source.length(); 00034 if (_len == 0) { 00035 _str = ""; 00036 } else { 00037 _str = new char[_len]; 00038 memcpy(_str, source.data(), _len); 00039 } 00040 } 00041 ~fake_istream_buffer() { 00042 if (_len != 0) { 00043 delete[] _str; 00044 } 00045 } 00046 00047 int _len; 00048 char *_str; 00049 }; 00050 00051 class istringstream : public fake_istream_buffer, public istrstream { 00052 public: 00053 istringstream(const string &input) : 00054 fake_istream_buffer(input), 00055 istrstream(_str, _len) { } 00056 }; 00057 00058 class ostringstream : public ostrstream { 00059 public: 00060 string str() { 00061 // We must capture the length before we take the str(). 00062 int length = pcount(); 00063 char *s = ostrstream::str(); 00064 string result(s, length); 00065 delete[] s; 00066 return result; 00067 } 00068 }; 00069 00070 class stringstream : public fake_istream_buffer, public strstream { 00071 public: 00072 stringstream() : strstream() { 00073 _owns_str = true; 00074 } 00075 stringstream(const string &input) : 00076 fake_istream_buffer(input), 00077 strstream(_str, _len, ios::in) 00078 { 00079 _owns_str = false; 00080 } 00081 00082 // str() doesn't seem to compile cross-platform too reliably--Irix 00083 // doesn't define pcount() for some reason. On the other hand, why 00084 // are you calling str() on a stringstream? Just use an 00085 // ostringstream. 00086 00087 /* 00088 string str() { 00089 int length = pcount(); 00090 char *s = strstream::str(); 00091 string result(s, length); 00092 if (_owns_str) { 00093 delete[] s; 00094 } 00095 return result; 00096 } 00097 */ 00098 00099 private: 00100 bool _owns_str; 00101 }; 00102 00103 #endif