Fix compilation with old g++ 3.3.5 and debian-sarge.
[wvstreams.git] / utils / wvwordwrap.cc
blob395ae9fb442568ac735375cfcc44fce9c09349e8
1 /*
2 * Worldvisions Weaver Software:
3 * Copyright (C) 1997-2002 Net Integration Technologies, Inc.
5 * A very simple word wrapping encoder.
6 */
7 #include "wvwordwrap.h"
9 WvWordWrapEncoder::WvWordWrapEncoder(int _maxwidth) :
10 maxwidth(_maxwidth)
12 line = new char[maxwidth];
13 _reset();
17 WvWordWrapEncoder::~WvWordWrapEncoder()
19 deletev line;
23 bool WvWordWrapEncoder::_reset()
25 width = 0;
26 curindex = wordindex = 0;
27 inword = false;
28 return true;
32 bool WvWordWrapEncoder::_encode(WvBuf &inbuf, WvBuf &outbuf,
33 bool flush)
35 while (inbuf.used() != 0)
37 int ch = inbuf.getch();
38 switch (ch)
40 case '\n':
41 if (! inword)
42 curindex = 0;
43 flushline(outbuf);
44 width = 0;
45 outbuf.putch('\n');
46 break;
48 case ' ':
49 if (inword)
50 flushline(outbuf);
51 width += 1;
52 if (width <= maxwidth)
53 line[curindex++] = ch;
54 break;
56 case '\t':
57 if (inword)
58 flushline(outbuf);
59 width = (width + 8) & ~7;
60 if (width <= maxwidth)
61 line[curindex++] = ch;
62 break;
64 default:
65 if (width >= maxwidth)
67 if (! inword)
69 // discard trailing whitespace
70 curindex = wordindex = 0;
71 width = 0;
73 else if (wordindex == 0)
75 // insert hard line break
76 flushline(outbuf);
77 width = 0;
79 else
81 // insert soft line break
82 curindex -= wordindex;
83 memmove(line, line + wordindex, curindex);
84 wordindex = 0;
85 width = curindex;
87 outbuf.putch('\n');
89 if (! inword)
91 inword = true;
92 wordindex = curindex;
94 width += 1;
95 line[curindex++] = ch;
96 break;
100 if (flush)
101 flushline(outbuf);
102 return true;
106 void WvWordWrapEncoder::flushline(WvBuf &outbuf)
108 outbuf.put(line, curindex);
109 curindex = wordindex = 0;
110 inword = false;