Yingdi Yu | 3168c30 | 2015-07-04 16:45:40 -0700 | [diff] [blame^] | 1 | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ |
| 2 | /** |
| 3 | * Copyright (c) 2013-2016 Regents of the University of California. |
| 4 | * |
| 5 | * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions). |
| 6 | * |
| 7 | * ndn-cxx library is free software: you can redistribute it and/or modify it under the |
| 8 | * terms of the GNU Lesser General Public License as published by the Free Software |
| 9 | * Foundation, either version 3 of the License, or (at your option) any later version. |
| 10 | * |
| 11 | * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY |
| 12 | * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A |
| 13 | * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. |
| 14 | * |
| 15 | * You should have received copies of the GNU General Public License and GNU Lesser |
| 16 | * General Public License along with ndn-cxx, e.g., in COPYING.md file. If not, see |
| 17 | * <http://www.gnu.org/licenses/>. |
| 18 | * |
| 19 | * See AUTHORS.md for complete list of ndn-cxx authors and contributors. |
| 20 | */ |
| 21 | |
| 22 | #include "stream-source.hpp" |
| 23 | #include <vector> |
| 24 | |
| 25 | namespace ndn { |
| 26 | namespace security { |
| 27 | namespace transform { |
| 28 | |
| 29 | const std::size_t StreamSource::DEFAULT_BUFFER_LEN = 1024; |
| 30 | |
| 31 | StreamSource::StreamSource(std::istream& is, size_t bufferSize) |
| 32 | : Source() |
| 33 | , m_is(is) |
| 34 | , m_bufferSize(bufferSize) |
| 35 | { |
| 36 | BOOST_ASSERT(bufferSize > 0); |
| 37 | } |
| 38 | |
| 39 | void |
| 40 | StreamSource::doPump() |
| 41 | { |
| 42 | BOOST_ASSERT(m_next != nullptr); |
| 43 | |
| 44 | std::vector<uint8_t> buffer(m_bufferSize); |
| 45 | size_t dataOffset = 0; |
| 46 | size_t dataLen = 0; |
| 47 | |
| 48 | while (dataLen > 0 || !m_is.eof()) { |
| 49 | if (dataLen > 0) { |
| 50 | // we have some leftover, handle them first |
| 51 | size_t nBytesWritten = m_next->write(&buffer[dataOffset], dataLen); |
| 52 | |
| 53 | dataOffset += nBytesWritten; |
| 54 | dataLen -= nBytesWritten; |
| 55 | } |
| 56 | else if (m_is.bad()) { |
| 57 | BOOST_THROW_EXCEPTION(Error(getIndex(), "Input stream in bad state")); |
| 58 | } |
| 59 | else if (m_is.good()) { |
| 60 | m_is.read(reinterpret_cast<char*>(&buffer.front()), buffer.size()); |
| 61 | dataOffset = 0; |
| 62 | dataLen = m_is.gcount(); |
| 63 | } |
| 64 | } |
| 65 | m_next->end(); |
| 66 | } |
| 67 | |
| 68 | } // namespace transform |
| 69 | } // namespace security |
| 70 | } // namespace ndn |