1 /*
2 *
3 * C++ Portable Types Library (PTypes)
4 * Version 2.1.1 Released 27-Jun-2007
5 *
6 * Copyright (C) 2001-2007 Hovik Melikyan
7 *
8 * http://www.melikyan.com/ptypes/
9 *
10 */
11
12 #include <string.h>
13
14 #include "pstreams.h"
15
16
17 PTYPES_BEGIN
18
19
get_errstmname()20 string infilter::get_errstmname()
21 {
22 if (stm == nil)
23 return get_streamname();
24 else
25 return get_streamname() + ": " + stm->get_errstmname();
26 }
27
28
copytobuf(string & s)29 void infilter::copytobuf(string& s)
30 {
31 int n = imin(savecount, length(s));
32 if (n > 0)
33 {
34 memcpy(savebuf, pconst(s), n);
35 savebuf += n;
36 savecount -= n;
37 if (n == savecount)
38 clear(s);
39 else
40 del(s, 0, n);
41 }
42 }
43
44
copytobuf(pconst & buf,int & count)45 void infilter::copytobuf(pconst& buf, int& count)
46 {
47 int n = imin(savecount, count);
48 if (n > 0)
49 {
50 memcpy(savebuf, buf, n);
51 savebuf += n;
52 savecount -= n;
53 buf += n;
54 count -= n;
55 }
56 }
57
58
copytobuf(char c)59 bool infilter::copytobuf(char c)
60 {
61 if (savecount > 0) {
62 *savebuf = c;
63 savebuf++;
64 savecount--;
65 return true;
66 }
67 else
68 return false;
69 }
70
71
infilter(instm * istm,int ibufsize)72 infilter::infilter(instm* istm, int ibufsize)
73 : instm(ibufsize), stm(istm), savebuf(nil), savecount(0)
74 {
75 if (stm != nil)
76 stm->addnotification(this);
77 }
78
79
~infilter()80 infilter::~infilter()
81 {
82 if (stm != nil)
83 stm->delnotification(this);
84 }
85
86
freenotify(component * sender)87 void infilter::freenotify(component* sender)
88 {
89 if (sender == stm)
90 {
91 stm = nil;
92 close();
93 }
94 }
95
96
doopen()97 void infilter::doopen()
98 {
99 if (stm != nil && !stm->get_active())
100 stm->open();
101 }
102
103
doclose()104 void infilter::doclose()
105 {
106 savebuf = nil;
107 savecount = 0;
108 clear(postponed);
109 }
110
111
set_stm(instm * istm)112 void infilter::set_stm(instm* istm)
113 {
114 close();
115 if (stm != nil)
116 stm->delnotification(this);
117 stm = istm;
118 if (stm != nil)
119 stm->addnotification(this);
120 }
121
122
dorawread(char * buf,int count)123 int infilter::dorawread(char* buf, int count)
124 {
125 savebuf = buf;
126 savecount = count;
127 if (!isempty(postponed))
128 copytobuf(postponed);
129 if (savecount > 0 && stm != nil)
130 dofilter();
131 return count - savecount;
132 }
133
134
post(const char * buf,int count)135 void infilter::post(const char* buf, int count)
136 {
137 if (count > 0)
138 {
139 copytobuf(buf, count);
140 if (count > 0)
141 concat(postponed, buf, count);
142 }
143 }
144
145
post(string s)146 void infilter::post(string s)
147 {
148 if (!isempty(s))
149 {
150 copytobuf(s);
151 if (!isempty(s))
152 concat(postponed, s);
153 }
154 }
155
156
post(const char * s)157 void infilter::post(const char* s)
158 {
159 post(s, strlen(s));
160 }
161
162
post(char c)163 void infilter::post(char c)
164 {
165 if (!copytobuf(c))
166 concat(postponed, c);
167 }
168
169
170 PTYPES_END
171