2 CLAW - a C++ Library Absolutely Wonderful
4 CLAW is a free library without any particular aim but being useful to
7 Copyright (C) 2005-2011 Julien Jorge
9 This library is free software; you can redistribute it and/or
10 modify it under the terms of the GNU Lesser General Public
11 License as published by the Free Software Foundation; either
12 version 2.1 of the License, or (at your option) any later version.
14 This library is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 Lesser General Public License for more details.
19 You should have received a copy of the GNU Lesser General Public
20 License along with this library; if not, write to the Free Software
21 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
23 contact: julien.jorge@gamned.org
26 * \file bit_istream.tpp
27 * \brief Implementation of the claw::bit_istream class.
28 * \author Julien Jorge
32 /*----------------------------------------------------------------------------*/
35 * \param f The stream in which we read.
37 template<typename Stream>
38 claw::bit_istream<Stream>::bit_istream( stream_type& f )
39 : m_stream(f), m_pending(0), m_pending_length(0)
42 } // bit_istream::bit_istream()
44 /*----------------------------------------------------------------------------*/
46 * \brief Read some bits.
47 * \param buf A buffer in which we write the bits.
48 * \param n The number of bits to read.
50 template<typename Stream>
51 void claw::bit_istream<Stream>::read( char* buf, unsigned int n )
56 unsigned int cur_size = 0;
58 while ( (n != 0) && !!(*this) )
60 while( (m_pending_length != 0) && (n!=0) && !!(*this) )
62 unsigned int bits = std::min((unsigned int)m_pending_length, n);
64 if ( CHAR_BIT - cur_size < bits )
65 bits = CHAR_BIT - cur_size;
67 unsigned int mask = (1 << bits) - 1;
69 *buf |= (m_pending & mask) << cur_size;
71 m_pending_length -= bits;
75 if ( cur_size == CHAR_BIT )
82 if ( m_pending_length == 0 )
83 if ( m_stream.read( (char*)&m_pending, sizeof(m_pending) ) )
84 m_pending_length = CHAR_BIT;
86 } // bit_istream::read()
88 /*----------------------------------------------------------------------------*/
90 * \brief Tell if the input stream is still valid.
92 template<typename Stream>
93 claw::bit_istream<Stream>::operator bool() const
95 return m_stream || (m_pending_length > 0);
96 } // bit_istream::operator bool()