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