Claw  1.7.3
bit_istream.tpp
1 /*
2  CLAW - a C++ Library Absolutely Wonderful
3 
4  CLAW is a free library without any particular aim but being useful to
5  anyone.
6 
7  Copyright (C) 2005-2011 Julien Jorge
8 
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.
13 
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.
18 
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
22 
23  contact: julien.jorge@gamned.org
24 */
25 /**
26  * \file bit_istream.tpp
27  * \brief Implementation of the claw::bit_istream class.
28  * \author Julien Jorge
29  */
30 #include <climits>
31 
32 /*----------------------------------------------------------------------------*/
33 /**
34  * \brief Constructor.
35  * \param f The stream in which we read.
36  */
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)
40 {
41 
42 } // bit_istream::bit_istream()
43 
44 /*----------------------------------------------------------------------------*/
45 /**
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.
49  */
50 template<typename Stream>
51 void claw::bit_istream<Stream>::read( char* buf, unsigned int n )
52 {
53  if ( n == 0 )
54  return;
55 
56  unsigned int cur_size = 0;
57 
58  while ( (n != 0) && !!(*this) )
59  {
60  while( (m_pending_length != 0) && (n!=0) && !!(*this) )
61  {
62  unsigned int bits = std::min((unsigned int)m_pending_length, n);
63 
64  if ( CHAR_BIT - cur_size < bits )
65  bits = CHAR_BIT - cur_size;
66 
67  unsigned int mask = (1 << bits) - 1;
68 
69  *buf |= (m_pending & mask) << cur_size;
70  cur_size += bits;
71  m_pending_length -= bits;
72  m_pending >>= bits;
73  n -= bits;
74 
75  if ( cur_size == CHAR_BIT )
76  {
77  ++buf;
78  cur_size = 0;
79  }
80  }
81 
82  if ( m_pending_length == 0 )
83  if ( m_stream.read( (char*)&m_pending, sizeof(m_pending) ) )
84  m_pending_length = CHAR_BIT;
85  }
86 } // bit_istream::read()
87 
88 /*----------------------------------------------------------------------------*/
89 /**
90  * \brief Tell if the input stream is still valid.
91  */
92 template<typename Stream>
93 claw::bit_istream<Stream>::operator bool() const
94 {
95  return m_stream || (m_pending_length > 0);
96 } // bit_istream::operator bool()