WvStreams
wvwordwrap.cc
1/*
2 * Worldvisions Weaver Software:
3 * Copyright (C) 1997-2002 Net Integration Technologies, Inc.
4 *
5 * A very simple word wrapping encoder.
6 */
7#include "wvwordwrap.h"
8
9WvWordWrapEncoder::WvWordWrapEncoder(int _maxwidth) :
10 maxwidth(_maxwidth)
11{
12 line = new char[maxwidth];
13 _reset();
14}
15
16
17WvWordWrapEncoder::~WvWordWrapEncoder()
18{
19 deletev line;
20}
21
22
24{
25 width = 0;
26 curindex = wordindex = 0;
27 inword = false;
28 return true;
29}
30
31
32bool WvWordWrapEncoder::_encode(WvBuf &inbuf, WvBuf &outbuf,
33 bool flush)
34{
35 while (inbuf.used() != 0)
36 {
37 int ch = inbuf.getch();
38 switch (ch)
39 {
40 case '\n':
41 if (! inword)
42 curindex = 0;
43 flushline(outbuf);
44 width = 0;
45 outbuf.putch('\n');
46 break;
47
48 case ' ':
49 if (inword)
50 flushline(outbuf);
51 width += 1;
52 if (width <= maxwidth)
53 line[curindex++] = ch;
54 break;
55
56 case '\t':
57 if (inword)
58 flushline(outbuf);
59 width = (width + 8) & ~7;
60 if (width <= maxwidth)
61 line[curindex++] = ch;
62 break;
63
64 default:
65 if (width >= maxwidth)
66 {
67 if (! inword)
68 {
69 // discard trailing whitespace
70 curindex = wordindex = 0;
71 width = 0;
72 }
73 else if (wordindex == 0)
74 {
75 // insert hard line break
76 flushline(outbuf);
77 width = 0;
78 }
79 else
80 {
81 // insert soft line break
82 curindex -= wordindex;
83 memmove(line, line + wordindex, curindex);
84 wordindex = 0;
85 width = curindex;
86 }
87 outbuf.putch('\n');
88 }
89 if (! inword)
90 {
91 inword = true;
92 wordindex = curindex;
93 }
94 width += 1;
95 line[curindex++] = ch;
96 break;
97
98 }
99 }
100 if (flush)
101 flushline(outbuf);
102 return true;
103}
104
105
106void WvWordWrapEncoder::flushline(WvBuf &outbuf)
107{
108 outbuf.put(line, curindex);
109 curindex = wordindex = 0;
110 inword = false;
111}
bool flush(WvBuf &inbuf, WvBuf &outbuf, bool finish=false)
Flushes the encoder and optionally finishes it.
virtual bool _reset()
Template method implementation of reset().
Definition wvwordwrap.cc:23
virtual bool _encode(WvBuf &inbuf, WvBuf &outbuf, bool flush)
Template method implementation of encode().
Definition wvwordwrap.cc:32