IBR-DTNSuite
0.8
|
00001 /* 00002 * HashStream.cpp 00003 * 00004 * Created on: 12.07.2010 00005 * Author: morgenro 00006 */ 00007 00008 #include "HashStream.h" 00009 #include <sstream> 00010 00011 namespace ibrcommon 00012 { 00013 HashStream::HashStream(const size_t hash, const size_t buffer) 00014 : iostream(this), data_buf_(new char[buffer]), data_size_(buffer), hash_buf_(new char[hash]), hash_size_(hash), final_(false) 00015 { 00016 // Initialize get pointer. This should be zero so that underflow is called upon first read. 00017 setg(0, 0, 0); 00018 setp(data_buf_, data_buf_ + data_size_ - 1); 00019 } 00020 00021 HashStream::~HashStream() 00022 { 00023 delete[] data_buf_; 00024 delete[] hash_buf_; 00025 } 00026 00027 std::string HashStream::extract(std::istream &stream) 00028 { 00029 std::stringstream buf; 00030 buf << stream.rdbuf(); 00031 return buf.str(); 00032 } 00033 00034 int HashStream::sync() 00035 { 00036 int ret = std::char_traits<char>::eq_int_type(this->overflow( 00037 std::char_traits<char>::eof()), std::char_traits<char>::eof()) ? -1 00038 : 0; 00039 00040 return ret; 00041 } 00042 00043 std::char_traits<char>::int_type HashStream::overflow(std::char_traits<char>::int_type c) 00044 { 00045 char *ibegin = data_buf_; 00046 char *iend = pptr(); 00047 00048 // mark the buffer as free 00049 setp(data_buf_, data_buf_ + data_size_ - 1); 00050 00051 if (!std::char_traits<char>::eq_int_type(c, std::char_traits<char>::eof())) 00052 { 00053 *iend++ = std::char_traits<char>::to_char_type(c); 00054 } 00055 00056 // if there is nothing to send, just return 00057 if ((iend - ibegin) == 0) 00058 { 00059 return std::char_traits<char>::not_eof(c); 00060 } 00061 00062 // hashing 00063 update(data_buf_, (iend - ibegin)); 00064 00065 return std::char_traits<char>::not_eof(c); 00066 } 00067 00068 std::char_traits<char>::int_type HashStream::underflow() 00069 { 00070 // TODO: add seek mechanisms to reset the istream 00071 00072 if (!final_) 00073 { 00074 finalize(hash_buf_, hash_size_); 00075 final_ = true; 00076 00077 // Since the input buffer content is now valid (or is new) 00078 // the get pointer should be initialized (or reset). 00079 setg(hash_buf_, hash_buf_, hash_buf_ + hash_size_); 00080 00081 return std::char_traits<char>::not_eof((unsigned char) hash_buf_[0]); 00082 } 00083 00084 return std::char_traits<char>::eof(); 00085 } 00086 }