Merge: Graphics related features, fixes and doc
[nit.git] / lib / csv.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # CSV output facilities
16 module csv
17
18 # A CSV document representation
19 class CSVDocument
20 super Streamable
21
22 var header: Array[String] = new Array[String] is writable
23 var lines: Array[Array[String]] = new Array[Array[String]]
24
25 fun set_header(values: Object...) do
26 header.clear
27 for value in values do
28 header.add(value.to_s)
29 end
30 end
31
32 fun add_line(values: Object...) do
33 if values.length != header.length then
34 print "CSV error: header declares {header.length} columns, line contains {values.length} values"
35 abort
36 end
37 var line = new Array[String]
38 for value in values do
39 line.add(value.to_s)
40 end
41 lines.add(line)
42 end
43
44 private fun write_line_to(line: Collection[String], stream: OStream)
45 do
46 var i = line.iterator
47 if i.is_ok then
48 stream.write(i.item)
49 i.next
50 while i.is_ok do
51 stream.write(";")
52 stream.write(i.item)
53 i.next
54 end
55 end
56 stream.write("\n")
57 end
58
59 redef fun write_to(stream)
60 do
61 write_line_to(header, stream)
62 for line in lines do write_line_to(line, stream)
63 end
64
65 # deprecated alias for `write_to_file`
66 fun save(file: String) do write_to_file(file)
67 end