Alf P. Steinbach
unread,Nov 9, 2015, 9:59:38 AM11/9/15You do not have permission to delete messages in this group
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message
to
#include "cppx.hpp"
// using std::move; Found via ADL anyway.
using std::wcout;
using cppx::Boxed;
using cppx::n_items;
using cppx::Pipe;
using cppx::String;
#include <functional>
using std::function;
#include <sstream>
using std::wistringstream;
#include <string>
using std::stoi;
#include <thread>
using std::thread;
using Input_func = auto() -> Boxed<String>;
using Output_func = void( Boxed<String> );
auto boxed_line_input()
-> Boxed<String>
{ return cppx::input_line(); }
void boxed_line_output( Boxed<String> const& box )
{ if( not box.is_empty() ) { wcout << box.item() << "\n"; } }
void lines_to_words(
function<Input_func> const& receive_line,
function<Output_func> const& send_word
)
{
for( ;; )
{
Boxed<String> const line = receive_line();
if( line.is_empty() )
{
send_word( Boxed<String>::empty() );
return;
}
else
{
wistringstream stream( line.item() );
String w;
while( stream >> w ) { send_word( Boxed<String>( w ) ); }
}
}
}
void words_to_lines(
int const max_line_length,
function<Input_func> const& receive_word,
function<Output_func> const& send_line
)
{
String line;
for( ;; )
{
Boxed<String> word_box = receive_word();
if( word_box.is_empty() )
{
break;
}
String& word = word_box.item();
int const previous_length = n_items( line );
if( previous_length == 0 )
{
line = move( word );
}
else if( previous_length + 1 + n_items( word ) > max_line_length )
{
send_line( Boxed<String>( move( line ) ) );
line = move( word );
}
else
{
line += L' ';
line += word;
}
}
if( n_items( line ) > 0 )
{
send_line( Boxed<String>( move( line ) ) );
}
send_line( Boxed<String>::empty() );
}
auto main( int, char** args )
-> int
{
int const w = stoi( args[1] );
Pipe<Boxed<String>> pipe;
thread t1(
lines_to_words,
boxed_line_input,
[&]( Boxed<String> s )-> void { pipe.put( move( s ) ); }
);
thread t2(
words_to_lines,
w,
[&]()->Boxed<String> { return pipe.get(); },
boxed_line_output
);
t1.join(); t2.join();
}