IBR-DTNSuite  0.10
HashStream.cpp
Go to the documentation of this file.
1 /*
2  * HashStream.cpp
3  *
4  * Copyright (C) 2011 IBR, TU Braunschweig
5  *
6  * Written-by: Johannes Morgenroth <morgenroth@ibr.cs.tu-bs.de>
7  *
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *
20  */
21 
22 #include "HashStream.h"
23 #include <sstream>
24 
25 namespace ibrcommon
26 {
27  HashStream::HashStream(const unsigned int hash, const size_t buffer)
28  : iostream(this), data_buf_(buffer), data_size_(buffer), hash_buf_(hash), hash_size_(hash), final_(false)
29  {
30  // Initialize get pointer. This should be zero so that underflow is called upon first read.
31  setg(0, 0, 0);
32  setp(&data_buf_[0], &data_buf_[0] + data_size_ - 1);
33  }
34 
36  {
37  }
38 
39  std::string HashStream::extract(std::istream &stream)
40  {
41  std::stringstream buf;
42  buf << stream.rdbuf();
43  return buf.str();
44  }
45 
47  {
48  int ret = std::char_traits<char>::eq_int_type(this->overflow(
49  std::char_traits<char>::eof()), std::char_traits<char>::eof()) ? -1
50  : 0;
51 
52  return ret;
53  }
54 
55  std::char_traits<char>::int_type HashStream::overflow(std::char_traits<char>::int_type c)
56  {
57  char *ibegin = &data_buf_[0];
58  char *iend = pptr();
59 
60  // mark the buffer as free
61  setp(&data_buf_[0], &data_buf_[0] + data_size_ - 1);
62 
63  if (!std::char_traits<char>::eq_int_type(c, std::char_traits<char>::eof()))
64  {
65  *iend++ = std::char_traits<char>::to_char_type(c);
66  }
67 
68  // if there is nothing to send, just return
69  if ((iend - ibegin) == 0)
70  {
71  return std::char_traits<char>::not_eof(c);
72  }
73 
74  // hashing
75  update(&data_buf_[0], (iend - ibegin));
76 
77  return std::char_traits<char>::not_eof(c);
78  }
79 
80  std::char_traits<char>::int_type HashStream::underflow()
81  {
82  // TODO: add seek mechanisms to reset the istream
83 
84  if (!final_)
85  {
86  finalize(&hash_buf_[0], hash_size_);
87  final_ = true;
88 
89  // Since the input buffer content is now valid (or is new)
90  // the get pointer should be initialized (or reset).
91  setg(&hash_buf_[0], &hash_buf_[0], &hash_buf_[0] + hash_size_);
92 
93  return std::char_traits<char>::not_eof(hash_buf_[0]);
94  }
95 
96  return std::char_traits<char>::eof();
97  }
98 }