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_ostream.tpp
27 * \brief Implementation of the claw::bit_ostream class.
28 * \author Julien Jorge
32 /*----------------------------------------------------------------------------*/
35 * \param f The stream in which we write.
37 template<typename Stream>
38 claw::bit_ostream<Stream>::bit_ostream( stream_type& f )
39 : m_stream(f), m_pending(0), m_pending_length(0)
42 } // bit_ostream::bit_ostream()
44 /*----------------------------------------------------------------------------*/
48 template<typename Stream>
49 claw::bit_ostream<Stream>::~bit_ostream()
51 if (m_pending_length != 0)
52 m_stream.write( (char*)&m_pending, sizeof(m_pending) );
53 } // bit_ostream::~bit_ostream()
55 /*----------------------------------------------------------------------------*/
57 * \brief Write some bits.
58 * \param buf A buffer from which we read the bits.
59 * \param n The number of bits to write.
61 template<typename Stream>
62 void claw::bit_ostream<Stream>::write( const char* buf, unsigned int n )
67 unsigned int cur_size = 0;
68 unsigned char data = *buf;
72 while( (m_pending_length != CHAR_BIT) && (n!=0) )
75 std::min(CHAR_BIT - (unsigned int)m_pending_length, n);
77 if ( CHAR_BIT - cur_size < bits )
78 bits = CHAR_BIT - cur_size;
80 unsigned int mask = (1 << bits) - 1;
82 m_pending |= (data & mask) << m_pending_length;
84 m_pending_length += bits;
88 if ( (cur_size == CHAR_BIT) && (n!=0) )
96 if ( m_pending_length == CHAR_BIT )
98 m_stream.write( (char*)&m_pending, sizeof(m_pending) );
100 m_pending_length = 0;
103 } // bit_ostream::write()