Boost logo

Boost :

From: Jonathan Turkanis (technews_at_[hidden])
Date: 2005-03-04 13:16:40


Peter Dimov wrote:
> Peter Dimov wrote:
>
>> Time for a contest. "Write the best non-blocking comment skipping
>> filter". :-)
>
> Here's my entry.
>
> struct filter
> {
> char comment_char_;
> bool in_comment_;
>
> filter(): comment_char_( '#' ), in_comment_( false )
> {
> }
>
> template< class Source > int get( Source & src )
> {
> int c;
>
> for( ;; )
> {
> if( in_comment_ )
> {
> for( ;; )
> {
> c = src.get();
>
> if( c == eof || c == eagain ) return c;
> if( c == '\n' ) break;
> }
>
> in_comment_ = false;
> }
>
> c = src.get();
>
> if( c != comment_char_ ) return c;
>
> in_comment_ = true;
> }
> }
> };

This one is simple enough to put in the tutorial.

> struct filter2
> {
> char comment_char_;
> bool in_comment_;
>
> filter2(): comment_char_( '#' ), in_comment_( false )
> {
> }
>
> template< class Source > int read( Source & src, char * s, int n )
> {
> int m = src.read( s, n );
>
> if( m <= 0 ) return m;
>
> int r = 0; // dest: [s, s + r)
>
> char const * p = s; // src: [p, p + m)
>
> for( ;; )
> {
> if( in_comment_ )
> {
> char const * q = static_cast<char const *>( memchr(
> p, '\n', m ) );
>
> if( q == 0 )
> {
> return r;
> }
>
> m -= q - p + 1;
> p = q + 1;
> in_comment_ = false;
> }
>
> char const * q = static_cast<char const *>( memchr( p,
> comment_char_, m ) );
>
> if( q == 0 )
> {
> memmove( s + r, p, m );
> return r + m;
> }
>
> memmove( s + r, p, q - p );
> r += q - p;
> m -= q - p + 1;
> p = q + 1;
> in_comment_ = true;
> }
> }
> };

Pretty sneaky! Try that with a tab-expanding filter ;-)

Jonathan


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk