52076c9ee496658d12f8ab31b9b9094d11bec7df
[nit.git] / lib / filter_stream.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2006 Floréal Morandat <morandat@lirmm.fr>
4 #
5 # This file is free software, which comes along with NIT. This software is
6 # distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
7 # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
8 # PARTICULAR PURPOSE. You can modify it is you want, provided this header
9 # is kept unaltered, and a notification of the changes is added.
10 # You are allowed to redistribute it and sell it, alone or is a part of
11 # another product.
12
13 class FilterIStream
14 special IStream
15 # Filter readed elements
16 readable attr _stream: IStream
17
18 redef meth eof: Bool
19 do
20 assert stream != null
21 return stream.eof
22 end
23
24 private meth stream=(i: IStream)
25 do
26 _stream = i
27 end
28 end
29
30 class FilterOStream
31 special OStream
32 # Filter outputed elements
33 readable attr _stream: OStream
34
35 # Can the stream be used to write
36 redef meth is_writable: Bool
37 do
38 assert stream != null
39 return stream.is_writable
40 end
41
42 private meth stream=(i: OStream)
43 do
44 _stream = i
45 end
46 end
47
48 class StreamCat
49 special FilterIStream
50 attr _streams: Iterator[IStream]
51
52 redef meth eof: Bool
53 do
54 if stream == null then
55 return true
56 else if stream.eof then
57 stream.close
58 stream = null
59 return eof
60 else
61 return false
62 end
63 end
64
65 redef meth stream: IStream
66 do
67 if _stream == null and _streams.is_ok then
68 stream = _streams.item
69 assert _stream != null
70 _streams.next
71 end
72 return _stream
73 end
74
75 redef meth read_char: Int
76 do
77 assert not eof
78 return stream.read_char
79 end
80
81 redef meth close
82 do
83 while stream != null do
84 stream.close
85 stream = null
86 end
87 end
88
89 init with_streams(streams: Array[IStream])
90 do
91 _streams = streams.iterator
92 end
93 init(streams: IStream ...)
94 do
95 _streams = streams.iterator
96 end
97 end
98
99 class StreamDemux
100 special FilterOStream
101 attr _streams: Array[OStream]
102
103 redef meth is_writable: Bool
104 do
105 if stream.is_writable then
106 return true
107 else
108 for i in _streams
109 do
110 if i.is_writable then
111 return true
112 end
113 end
114 return false
115 end
116 end
117
118 redef meth write(s: String)
119 do
120 for i in _streams
121 do
122 stream = i
123 if stream.is_writable then
124 stream.write(s)
125 end
126 end
127 end
128
129 init with_streams(streams: Array[OStream])
130 do
131 _streams = streams
132 end
133
134 init(streams: OStream ...)
135 do
136 _streams = streams
137 end
138 end