;]
[askyou.git] / lib / faster_csv.rb
blob9c3a4066694058586840d4393139111081529e2a
1 #!/usr/local/bin/ruby -w
3 # = faster_csv.rb -- Faster CSV Reading and Writing
5 #  Created by James Edward Gray II on 2005-10-31.
6 #  Copyright 2005 Gray Productions. All rights reserved.
7
8 # See FasterCSV for documentation.
10 if RUBY_VERSION >= "1.9"
11   abort <<-VERSION_WARNING.gsub(/^\s+/, "")
12   Please switch to Ruby 1.9's standard CSV library.  It's FasterCSV plus
13   support for Ruby 1.9's m17n encoding engine.
14   VERSION_WARNING
15 end
17 require "forwardable"
18 require "English"
19 require "enumerator"
20 require "date"
21 require "stringio"
23
24 # This class provides a complete interface to CSV files and data.  It offers
25 # tools to enable you to read and write to and from Strings or IO objects, as
26 # needed.
27
28 # == Reading
29
30 # === From a File
31
32 # ==== A Line at a Time
33
34 #   FasterCSV.foreach("path/to/file.csv") do |row|
35 #     # use row here...
36 #   end
37
38 # ==== All at Once
39
40 #   arr_of_arrs = FasterCSV.read("path/to/file.csv")
41
42 # === From a String
43
44 # ==== A Line at a Time
45
46 #   FasterCSV.parse("CSV,data,String") do |row|
47 #     # use row here...
48 #   end
49
50 # ==== All at Once
51
52 #   arr_of_arrs = FasterCSV.parse("CSV,data,String")
53
54 # == Writing
55
56 # === To a File
57
58 #   FasterCSV.open("path/to/file.csv", "w") do |csv|
59 #     csv << ["row", "of", "CSV", "data"]
60 #     csv << ["another", "row"]
61 #     # ...
62 #   end
63
64 # === To a String
65
66 #   csv_string = FasterCSV.generate do |csv|
67 #     csv << ["row", "of", "CSV", "data"]
68 #     csv << ["another", "row"]
69 #     # ...
70 #   end
71
72 # == Convert a Single Line
73
74 #   csv_string = ["CSV", "data"].to_csv   # to CSV
75 #   csv_array  = "CSV,String".parse_csv   # from CSV
76
77 # == Shortcut Interface
78
79 #   FCSV             { |csv_out| csv_out << %w{my data here} }  # to $stdout
80 #   FCSV(csv = "")   { |csv_str| csv_str << %w{my data here} }  # to a String
81 #   FCSV($stderr)    { |csv_err| csv_err << %w{my data here} }  # to $stderr
82
83 class FasterCSV
84   # The version of the installed library.
85   VERSION = "1.5.0".freeze
86   
87   # 
88   # A FasterCSV::Row is part Array and part Hash.  It retains an order for the
89   # fields and allows duplicates just as an Array would, but also allows you to
90   # access fields by name just as you could if they were in a Hash.
91   # 
92   # All rows returned by FasterCSV will be constructed from this class, if
93   # header row processing is activated.
94   # 
95   class Row
96     # 
97     # Construct a new FasterCSV::Row from +headers+ and +fields+, which are
98     # expected to be Arrays.  If one Array is shorter than the other, it will be
99     # padded with +nil+ objects.
100     # 
101     # The optional +header_row+ parameter can be set to +true+ to indicate, via
102     # FasterCSV::Row.header_row?() and FasterCSV::Row.field_row?(), that this is
103     # a header row.  Otherwise, the row is assumes to be a field row.
104     # 
105     # A FasterCSV::Row object supports the following Array methods through
106     # delegation:
107     # 
108     # * empty?()
109     # * length()
110     # * size()
111     # 
112     def initialize(headers, fields, header_row = false)
113       @header_row = header_row
114       
115       # handle extra headers or fields
116       @row = if headers.size > fields.size
117         headers.zip(fields)
118       else
119         fields.zip(headers).map { |pair| pair.reverse }
120       end
121     end
122     
123     # Internal data format used to compare equality.
124     attr_reader :row
125     protected   :row
127     ### Array Delegation ###
129     extend Forwardable
130     def_delegators :@row, :empty?, :length, :size
131     
132     # Returns +true+ if this is a header row.
133     def header_row?
134       @header_row
135     end
136     
137     # Returns +true+ if this is a field row.
138     def field_row?
139       not header_row?
140     end
141     
142     # Returns the headers of this row.
143     def headers
144       @row.map { |pair| pair.first }
145     end
146     
147     # 
148     # :call-seq:
149     #   field( header )
150     #   field( header, offset )
151     #   field( index )
152     # 
153     # This method will fetch the field value by +header+ or +index+.  If a field
154     # is not found, +nil+ is returned.
155     # 
156     # When provided, +offset+ ensures that a header match occurrs on or later
157     # than the +offset+ index.  You can use this to find duplicate headers, 
158     # without resorting to hard-coding exact indices.
159     # 
160     def field(header_or_index, minimum_index = 0)
161       # locate the pair
162       finder = header_or_index.is_a?(Integer) ? :[] : :assoc
163       pair   = @row[minimum_index..-1].send(finder, header_or_index)
165       # return the field if we have a pair
166       pair.nil? ? nil : pair.last
167     end
168     alias_method :[], :field
169     
170     # 
171     # :call-seq:
172     #   []=( header, value )
173     #   []=( header, offset, value )
174     #   []=( index, value )
175     # 
176     # Looks up the field by the semantics described in FasterCSV::Row.field()
177     # and assigns the +value+.
178     # 
179     # Assigning past the end of the row with an index will set all pairs between
180     # to <tt>[nil, nil]</tt>.  Assigning to an unused header appends the new
181     # pair.
182     # 
183     def []=(*args)
184       value = args.pop
185       
186       if args.first.is_a? Integer
187         if @row[args.first].nil?  # extending past the end with index
188           @row[args.first] = [nil, value]
189           @row.map! { |pair| pair.nil? ? [nil, nil] : pair }
190         else                      # normal index assignment
191           @row[args.first][1] = value
192         end
193       else
194         index = index(*args)
195         if index.nil?             # appending a field
196           self << [args.first, value]
197         else                      # normal header assignment
198           @row[index][1] = value
199         end
200       end
201     end
202     
203     # 
204     # :call-seq:
205     #   <<( field )
206     #   <<( header_and_field_array )
207     #   <<( header_and_field_hash )
208     # 
209     # If a two-element Array is provided, it is assumed to be a header and field
210     # and the pair is appended.  A Hash works the same way with the key being
211     # the header and the value being the field.  Anything else is assumed to be
212     # a lone field which is appended with a +nil+ header.
213     # 
214     # This method returns the row for chaining.
215     # 
216     def <<(arg)
217       if arg.is_a?(Array) and arg.size == 2  # appending a header and name
218         @row << arg
219       elsif arg.is_a?(Hash)                  # append header and name pairs
220         arg.each { |pair| @row << pair }
221       else                                   # append field value
222         @row << [nil, arg]
223       end
224       
225       self  # for chaining
226     end
227     
228     # 
229     # A shortcut for appending multiple fields.  Equivalent to:
230     # 
231     #   args.each { |arg| faster_csv_row << arg }
232     # 
233     # This method returns the row for chaining.
234     # 
235     def push(*args)
236       args.each { |arg| self << arg }
237       
238       self  # for chaining
239     end
240     
241     # 
242     # :call-seq:
243     #   delete( header )
244     #   delete( header, offset )
245     #   delete( index )
246     # 
247     # Used to remove a pair from the row by +header+ or +index+.  The pair is
248     # located as described in FasterCSV::Row.field().  The deleted pair is 
249     # returned, or +nil+ if a pair could not be found.
250     # 
251     def delete(header_or_index, minimum_index = 0)
252       if header_or_index.is_a? Integer  # by index
253         @row.delete_at(header_or_index)
254       else                              # by header
255         @row.delete_at(index(header_or_index, minimum_index))
256       end
257     end
258     
259     # 
260     # The provided +block+ is passed a header and field for each pair in the row
261     # and expected to return +true+ or +false+, depending on whether the pair
262     # should be deleted.
263     # 
264     # This method returns the row for chaining.
265     # 
266     def delete_if(&block)
267       @row.delete_if(&block)
268       
269       self  # for chaining
270     end
271     
272     # 
273     # This method accepts any number of arguments which can be headers, indices,
274     # Ranges of either, or two-element Arrays containing a header and offset.  
275     # Each argument will be replaced with a field lookup as described in
276     # FasterCSV::Row.field().
277     # 
278     # If called with no arguments, all fields are returned.
279     # 
280     def fields(*headers_and_or_indices)
281       if headers_and_or_indices.empty?  # return all fields--no arguments
282         @row.map { |pair| pair.last }
283       else                              # or work like values_at()
284         headers_and_or_indices.inject(Array.new) do |all, h_or_i|
285           all + if h_or_i.is_a? Range
286             index_begin = h_or_i.begin.is_a?(Integer) ? h_or_i.begin :
287                                                         index(h_or_i.begin)
288             index_end   = h_or_i.end.is_a?(Integer)   ? h_or_i.end :
289                                                         index(h_or_i.end)
290             new_range   = h_or_i.exclude_end? ? (index_begin...index_end) :
291                                                 (index_begin..index_end)
292             fields.values_at(new_range)
293           else
294             [field(*Array(h_or_i))]
295           end
296         end
297       end
298     end
299     alias_method :values_at, :fields
300     
301     # 
302     # :call-seq:
303     #   index( header )
304     #   index( header, offset )
305     # 
306     # This method will return the index of a field with the provided +header+.
307     # The +offset+ can be used to locate duplicate header names, as described in
308     # FasterCSV::Row.field().
309     # 
310     def index(header, minimum_index = 0)
311       # find the pair
312       index = headers[minimum_index..-1].index(header)
313       # return the index at the right offset, if we found one
314       index.nil? ? nil : index + minimum_index
315     end
316     
317     # Returns +true+ if +name+ is a header for this row, and +false+ otherwise.
318     def header?(name)
319       headers.include? name
320     end
321     alias_method :include?, :header?
322     
323     # 
324     # Returns +true+ if +data+ matches a field in this row, and +false+
325     # otherwise.
326     # 
327     def field?(data)
328       fields.include? data
329     end
331     include Enumerable
332     
333     # 
334     # Yields each pair of the row as header and field tuples (much like
335     # iterating over a Hash).
336     # 
337     # Support for Enumerable.
338     # 
339     # This method returns the row for chaining.
340     # 
341     def each(&block)
342       @row.each(&block)
343       
344       self  # for chaining
345     end
346     
347     # 
348     # Returns +true+ if this row contains the same headers and fields in the 
349     # same order as +other+.
350     # 
351     def ==(other)
352       @row == other.row
353     end
354     
355     # 
356     # Collapses the row into a simple Hash.  Be warning that this discards field
357     # order and clobbers duplicate fields.
358     # 
359     def to_hash
360       # flatten just one level of the internal Array
361       Hash[*@row.inject(Array.new) { |ary, pair| ary.push(*pair) }]
362     end
363     
364     # 
365     # Returns the row as a CSV String.  Headers are not used.  Equivalent to:
366     # 
367     #   faster_csv_row.fields.to_csv( options )
368     # 
369     def to_csv(options = Hash.new)
370       fields.to_csv(options)
371     end
372     alias_method :to_s, :to_csv
373     
374     # A summary of fields, by header.
375     def inspect
376       str = "#<#{self.class}"
377       each do |header, field|
378         str << " #{header.is_a?(Symbol) ? header.to_s : header.inspect}:" <<
379                field.inspect
380       end
381       str << ">"
382     end
383   end
384   
385   # 
386   # A FasterCSV::Table is a two-dimensional data structure for representing CSV
387   # documents.  Tables allow you to work with the data by row or column, 
388   # manipulate the data, and even convert the results back to CSV, if needed.
389   # 
390   # All tables returned by FasterCSV will be constructed from this class, if
391   # header row processing is activated.
392   # 
393   class Table
394     # 
395     # Construct a new FasterCSV::Table from +array_of_rows+, which are expected
396     # to be FasterCSV::Row objects.  All rows are assumed to have the same 
397     # headers.
398     # 
399     # A FasterCSV::Table object supports the following Array methods through
400     # delegation:
401     # 
402     # * empty?()
403     # * length()
404     # * size()
405     # 
406     def initialize(array_of_rows)
407       @table = array_of_rows
408       @mode  = :col_or_row
409     end
410     
411     # The current access mode for indexing and iteration.
412     attr_reader :mode
413     
414     # Internal data format used to compare equality.
415     attr_reader :table
416     protected   :table
418     ### Array Delegation ###
420     extend Forwardable
421     def_delegators :@table, :empty?, :length, :size
422     
423     # 
424     # Returns a duplicate table object, in column mode.  This is handy for 
425     # chaining in a single call without changing the table mode, but be aware 
426     # that this method can consume a fair amount of memory for bigger data sets.
427     # 
428     # This method returns the duplicate table for chaining.  Don't chain
429     # destructive methods (like []=()) this way though, since you are working
430     # with a duplicate.
431     # 
432     def by_col
433       self.class.new(@table.dup).by_col!
434     end
435     
436     # 
437     # Switches the mode of this table to column mode.  All calls to indexing and
438     # iteration methods will work with columns until the mode is changed again.
439     # 
440     # This method returns the table and is safe to chain.
441     # 
442     def by_col!
443       @mode = :col
444       
445       self
446     end
447     
448     # 
449     # Returns a duplicate table object, in mixed mode.  This is handy for 
450     # chaining in a single call without changing the table mode, but be aware 
451     # that this method can consume a fair amount of memory for bigger data sets.
452     # 
453     # This method returns the duplicate table for chaining.  Don't chain
454     # destructive methods (like []=()) this way though, since you are working
455     # with a duplicate.
456     # 
457     def by_col_or_row
458       self.class.new(@table.dup).by_col_or_row!
459     end
460     
461     # 
462     # Switches the mode of this table to mixed mode.  All calls to indexing and
463     # iteration methods will use the default intelligent indexing system until
464     # the mode is changed again.  In mixed mode an index is assumed to be a row
465     # reference while anything else is assumed to be column access by headers.
466     # 
467     # This method returns the table and is safe to chain.
468     # 
469     def by_col_or_row!
470       @mode = :col_or_row
471       
472       self
473     end
474     
475     # 
476     # Returns a duplicate table object, in row mode.  This is handy for chaining
477     # in a single call without changing the table mode, but be aware that this
478     # method can consume a fair amount of memory for bigger data sets.
479     # 
480     # This method returns the duplicate table for chaining.  Don't chain
481     # destructive methods (like []=()) this way though, since you are working
482     # with a duplicate.
483     # 
484     def by_row
485       self.class.new(@table.dup).by_row!
486     end
487     
488     # 
489     # Switches the mode of this table to row mode.  All calls to indexing and
490     # iteration methods will work with rows until the mode is changed again.
491     # 
492     # This method returns the table and is safe to chain.
493     # 
494     def by_row!
495       @mode = :row
496       
497       self
498     end
499     
500     # 
501     # Returns the headers for the first row of this table (assumed to match all
502     # other rows).  An empty Array is returned for empty tables.
503     # 
504     def headers
505       if @table.empty?
506         Array.new
507       else
508         @table.first.headers
509       end
510     end
511     
512     # 
513     # In the default mixed mode, this method returns rows for index access and
514     # columns for header access.  You can force the index association by first
515     # calling by_col!() or by_row!().
516     # 
517     # Columns are returned as an Array of values.  Altering that Array has no
518     # effect on the table.
519     # 
520     def [](index_or_header)
521       if @mode == :row or  # by index
522          (@mode == :col_or_row and index_or_header.is_a? Integer)
523         @table[index_or_header]
524       else                 # by header
525         @table.map { |row| row[index_or_header] }
526       end
527     end
528     
529     # 
530     # In the default mixed mode, this method assigns rows for index access and
531     # columns for header access.  You can force the index association by first
532     # calling by_col!() or by_row!().
533     # 
534     # Rows may be set to an Array of values (which will inherit the table's
535     # headers()) or a FasterCSV::Row.
536     # 
537     # Columns may be set to a single value, which is copied to each row of the 
538     # column, or an Array of values.  Arrays of values are assigned to rows top
539     # to bottom in row major order.  Excess values are ignored and if the Array
540     # does not have a value for each row the extra rows will receive a +nil+.
541     # 
542     # Assigning to an existing column or row clobbers the data.  Assigning to
543     # new columns creates them at the right end of the table.
544     # 
545     def []=(index_or_header, value)
546       if @mode == :row or  # by index
547          (@mode == :col_or_row and index_or_header.is_a? Integer)
548         if value.is_a? Array
549           @table[index_or_header] = Row.new(headers, value)
550         else
551           @table[index_or_header] = value
552         end
553       else                 # set column
554         if value.is_a? Array  # multiple values
555           @table.each_with_index do |row, i|
556             if row.header_row?
557               row[index_or_header] = index_or_header
558             else
559               row[index_or_header] = value[i]
560             end
561           end
562         else                  # repeated value
563           @table.each do |row|
564             if row.header_row?
565               row[index_or_header] = index_or_header
566             else
567               row[index_or_header] = value
568             end
569           end
570         end
571       end
572     end
573     
574     # 
575     # The mixed mode default is to treat a list of indices as row access,
576     # returning the rows indicated.  Anything else is considered columnar
577     # access.  For columnar access, the return set has an Array for each row
578     # with the values indicated by the headers in each Array.  You can force
579     # column or row mode using by_col!() or by_row!().
580     # 
581     # You cannot mix column and row access.
582     # 
583     def values_at(*indices_or_headers)
584       if @mode == :row or  # by indices
585          ( @mode == :col_or_row and indices_or_headers.all? do |index|
586                                       index.is_a?(Integer)         or
587                                       ( index.is_a?(Range)         and
588                                         index.first.is_a?(Integer) and
589                                         index.last.is_a?(Integer) )
590                                     end )
591         @table.values_at(*indices_or_headers)
592       else                 # by headers
593         @table.map { |row| row.values_at(*indices_or_headers) }
594       end
595     end
597     # 
598     # Adds a new row to the bottom end of this table.  You can provide an Array,
599     # which will be converted to a FasterCSV::Row (inheriting the table's
600     # headers()), or a FasterCSV::Row.
601     # 
602     # This method returns the table for chaining.
603     # 
604     def <<(row_or_array)
605       if row_or_array.is_a? Array  # append Array
606         @table << Row.new(headers, row_or_array)
607       else                         # append Row
608         @table << row_or_array
609       end
610       
611       self  # for chaining
612     end
613     
614     # 
615     # A shortcut for appending multiple rows.  Equivalent to:
616     # 
617     #   rows.each { |row| self << row }
618     # 
619     # This method returns the table for chaining.
620     # 
621     def push(*rows)
622       rows.each { |row| self << row }
623       
624       self  # for chaining
625     end
627     # 
628     # Removes and returns the indicated column or row.  In the default mixed
629     # mode indices refer to rows and everything else is assumed to be a column
630     # header.  Use by_col!() or by_row!() to force the lookup.
631     # 
632     def delete(index_or_header)
633       if @mode == :row or  # by index
634          (@mode == :col_or_row and index_or_header.is_a? Integer)
635         @table.delete_at(index_or_header)
636       else                 # by header
637         @table.map { |row| row.delete(index_or_header).last }
638       end
639     end
640     
641     # 
642     # Removes any column or row for which the block returns +true+.  In the
643     # default mixed mode or row mode, iteration is the standard row major
644     # walking of rows.  In column mode, interation will +yield+ two element
645     # tuples containing the column name and an Array of values for that column.
646     # 
647     # This method returns the table for chaining.
648     # 
649     def delete_if(&block)
650       if @mode == :row or @mode == :col_or_row  # by index
651         @table.delete_if(&block)
652       else                                      # by header
653         to_delete = Array.new
654         headers.each_with_index do |header, i|
655           to_delete << header if block[[header, self[header]]]
656         end
657         to_delete.map { |header| delete(header) }
658       end
659       
660       self  # for chaining
661     end
662     
663     include Enumerable
664     
665     # 
666     # In the default mixed mode or row mode, iteration is the standard row major
667     # walking of rows.  In column mode, interation will +yield+ two element
668     # tuples containing the column name and an Array of values for that column.
669     # 
670     # This method returns the table for chaining.
671     # 
672     def each(&block)
673       if @mode == :col
674         headers.each { |header| block[[header, self[header]]] }
675       else
676         @table.each(&block)
677       end
678       
679       self  # for chaining
680     end
681     
682     # Returns +true+ if all rows of this table ==() +other+'s rows.
683     def ==(other)
684       @table == other.table
685     end
686     
687     # 
688     # Returns the table as an Array of Arrays.  Headers will be the first row,
689     # then all of the field rows will follow.
690     # 
691     def to_a
692       @table.inject([headers]) do |array, row|
693         if row.header_row?
694           array
695         else
696           array + [row.fields]
697         end
698       end
699     end
700     
701     # 
702     # Returns the table as a complete CSV String.  Headers will be listed first,
703     # then all of the field rows.
704     # 
705     def to_csv(options = Hash.new)
706       @table.inject([headers.to_csv(options)]) do |rows, row|
707         if row.header_row?
708           rows
709         else
710           rows + [row.fields.to_csv(options)]
711         end
712       end.join
713     end
714     alias_method :to_s, :to_csv
715     
716     def inspect
717       "#<#{self.class} mode:#{@mode} row_count:#{to_a.size}>"
718     end
719   end
721   # The error thrown when the parser encounters illegal CSV formatting.
722   class MalformedCSVError < RuntimeError; end
723   
724   # 
725   # A FieldInfo Struct contains details about a field's position in the data
726   # source it was read from.  FasterCSV will pass this Struct to some blocks
727   # that make decisions based on field structure.  See 
728   # FasterCSV.convert_fields() for an example.
729   # 
730   # <b><tt>index</tt></b>::  The zero-based index of the field in its row.
731   # <b><tt>line</tt></b>::   The line of the data source this row is from.
732   # <b><tt>header</tt></b>:: The header for the column, when available.
733   # 
734   FieldInfo = Struct.new(:index, :line, :header)
735   
736   # A Regexp used to find and convert some common Date formats.
737   DateMatcher     = / \A(?: (\w+,?\s+)?\w+\s+\d{1,2},?\s+\d{2,4} |
738                             \d{4}-\d{2}-\d{2} )\z /x
739   # A Regexp used to find and convert some common DateTime formats.
740   DateTimeMatcher =
741     / \A(?: (\w+,?\s+)?\w+\s+\d{1,2}\s+\d{1,2}:\d{1,2}:\d{1,2},?\s+\d{2,4} |
742             \d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2} )\z /x
743   # 
744   # This Hash holds the built-in converters of FasterCSV that can be accessed by
745   # name.  You can select Converters with FasterCSV.convert() or through the
746   # +options+ Hash passed to FasterCSV::new().
747   # 
748   # <b><tt>:integer</tt></b>::    Converts any field Integer() accepts.
749   # <b><tt>:float</tt></b>::      Converts any field Float() accepts.
750   # <b><tt>:numeric</tt></b>::    A combination of <tt>:integer</tt> 
751   #                               and <tt>:float</tt>.
752   # <b><tt>:date</tt></b>::       Converts any field Date::parse() accepts.
753   # <b><tt>:date_time</tt></b>::  Converts any field DateTime::parse() accepts.
754   # <b><tt>:all</tt></b>::        All built-in converters.  A combination of 
755   #                               <tt>:date_time</tt> and <tt>:numeric</tt>.
756   # 
757   # This Hash is intetionally left unfrozen and users should feel free to add
758   # values to it that can be accessed by all FasterCSV objects.
759   # 
760   # To add a combo field, the value should be an Array of names.  Combo fields
761   # can be nested with other combo fields.
762   # 
763   Converters  = { :integer   => lambda { |f| Integer(f)        rescue f },
764                   :float     => lambda { |f| Float(f)          rescue f },
765                   :numeric   => [:integer, :float],
766                   :date      => lambda { |f|
767                     f =~ DateMatcher ? (Date.parse(f) rescue f) : f
768                   },
769                   :date_time => lambda { |f|
770                     f =~ DateTimeMatcher ? (DateTime.parse(f) rescue f) : f
771                   },
772                   :all       => [:date_time, :numeric] }
774   # 
775   # This Hash holds the built-in header converters of FasterCSV that can be
776   # accessed by name.  You can select HeaderConverters with
777   # FasterCSV.header_convert() or through the +options+ Hash passed to
778   # FasterCSV::new().
779   # 
780   # <b><tt>:downcase</tt></b>::  Calls downcase() on the header String.
781   # <b><tt>:symbol</tt></b>::    The header String is downcased, spaces are
782   #                              replaced with underscores, non-word characters
783   #                              are dropped, and finally to_sym() is called.
784   # 
785   # This Hash is intetionally left unfrozen and users should feel free to add
786   # values to it that can be accessed by all FasterCSV objects.
787   # 
788   # To add a combo field, the value should be an Array of names.  Combo fields
789   # can be nested with other combo fields.
790   # 
791   HeaderConverters = {
792     :downcase => lambda { |h| h.downcase },
793     :symbol   => lambda { |h|
794       h.downcase.tr(" ", "_").delete("^a-z0-9_").to_sym
795     }
796   }
797   
798   # 
799   # The options used when no overrides are given by calling code.  They are:
800   # 
801   # <b><tt>:col_sep</tt></b>::            <tt>","</tt>
802   # <b><tt>:row_sep</tt></b>::            <tt>:auto</tt>
803   # <b><tt>:quote_char</tt></b>::         <tt>'"'</tt>
804   # <b><tt>:converters</tt></b>::         +nil+
805   # <b><tt>:unconverted_fields</tt></b>:: +nil+
806   # <b><tt>:headers</tt></b>::            +false+
807   # <b><tt>:return_headers</tt></b>::     +false+
808   # <b><tt>:header_converters</tt></b>::  +nil+
809   # <b><tt>:skip_blanks</tt></b>::        +false+
810   # <b><tt>:force_quotes</tt></b>::       +false+
811   # 
812   DEFAULT_OPTIONS = { :col_sep            => ",",
813                       :row_sep            => :auto,
814                       :quote_char         => '"', 
815                       :converters         => nil,
816                       :unconverted_fields => nil,
817                       :headers            => false,
818                       :return_headers     => false,
819                       :header_converters  => nil,
820                       :skip_blanks        => false,
821                       :force_quotes       => false }.freeze
822   
823   # 
824   # This method will build a drop-in replacement for many of the standard CSV
825   # methods.  It allows you to write code like:
826   # 
827   #   begin
828   #     require "faster_csv"
829   #     FasterCSV.build_csv_interface
830   #   rescue LoadError
831   #     require "csv"
832   #   end
833   #   # ... use CSV here ...
834   # 
835   # This is not a complete interface with completely identical behavior.
836   # However, it is intended to be close enough that you won't notice the
837   # difference in most cases.  CSV methods supported are:
838   # 
839   # * foreach()
840   # * generate_line()
841   # * open()
842   # * parse()
843   # * parse_line()
844   # * readlines()
845   # 
846   # Be warned that this interface is slower than vanilla FasterCSV due to the
847   # extra layer of method calls.  Depending on usage, this can slow it down to 
848   # near CSV speeds.
849   # 
850   def self.build_csv_interface
851     Object.const_set(:CSV, Class.new).class_eval do
852       def self.foreach(path, rs = :auto, &block)  # :nodoc:
853         FasterCSV.foreach(path, :row_sep => rs, &block)
854       end
855       
856       def self.generate_line(row, fs = ",", rs = "")  # :nodoc:
857         FasterCSV.generate_line(row, :col_sep => fs, :row_sep => rs)
858       end
859       
860       def self.open(path, mode, fs = ",", rs = :auto, &block)  # :nodoc:
861         if block and mode.include? "r"
862           FasterCSV.open(path, mode, :col_sep => fs, :row_sep => rs) do |csv|
863             csv.each(&block)
864           end
865         else
866           FasterCSV.open(path, mode, :col_sep => fs, :row_sep => rs, &block)
867         end
868       end
869       
870       def self.parse(str_or_readable, fs = ",", rs = :auto, &block)  # :nodoc:
871         FasterCSV.parse(str_or_readable, :col_sep => fs, :row_sep => rs, &block)
872       end
873       
874       def self.parse_line(src, fs = ",", rs = :auto)  # :nodoc:
875         FasterCSV.parse_line(src, :col_sep => fs, :row_sep => rs)
876       end
877       
878       def self.readlines(path, rs = :auto)  # :nodoc:
879         FasterCSV.readlines(path, :row_sep => rs)
880       end
881     end
882   end
883   
884   # 
885   # This method allows you to serialize an Array of Ruby objects to a String or
886   # File of CSV data.  This is not as powerful as Marshal or YAML, but perhaps
887   # useful for spreadsheet and database interaction.
888   # 
889   # Out of the box, this method is intended to work with simple data objects or
890   # Structs.  It will serialize a list of instance variables and/or
891   # Struct.members().
892   # 
893   # If you need need more complicated serialization, you can control the process
894   # by adding methods to the class to be serialized.
895   # 
896   # A class method csv_meta() is responsible for returning the first row of the
897   # document (as an Array).  This row is considered to be a Hash of the form
898   # key_1,value_1,key_2,value_2,...  FasterCSV::load() expects to find a class
899   # key with a value of the stringified class name and FasterCSV::dump() will
900   # create this, if you do not define this method.  This method is only called
901   # on the first object of the Array.
902   # 
903   # The next method you can provide is an instance method called csv_headers().
904   # This method is expected to return the second line of the document (again as
905   # an Array), which is to be used to give each column a header.  By default,
906   # FasterCSV::load() will set an instance variable if the field header starts
907   # with an @ character or call send() passing the header as the method name and
908   # the field value as an argument.  This method is only called on the first
909   # object of the Array.
910   # 
911   # Finally, you can provide an instance method called csv_dump(), which will
912   # be passed the headers.  This should return an Array of fields that can be
913   # serialized for this object.  This method is called once for every object in
914   # the Array.
915   # 
916   # The +io+ parameter can be used to serialize to a File, and +options+ can be
917   # anything FasterCSV::new() accepts.
918   # 
919   def self.dump(ary_of_objs, io = "", options = Hash.new)
920     obj_template = ary_of_objs.first
921     
922     csv = FasterCSV.new(io, options)
923     
924     # write meta information
925     begin
926       csv << obj_template.class.csv_meta
927     rescue NoMethodError
928       csv << [:class, obj_template.class]
929     end
931     # write headers
932     begin
933       headers = obj_template.csv_headers
934     rescue NoMethodError
935       headers = obj_template.instance_variables.sort
936       if obj_template.class.ancestors.find { |cls| cls.to_s =~ /\AStruct\b/ }
937         headers += obj_template.members.map { |mem| "#{mem}=" }.sort
938       end
939     end
940     csv << headers
941     
942     # serialize each object
943     ary_of_objs.each do |obj|
944       begin
945         csv << obj.csv_dump(headers)
946       rescue NoMethodError
947         csv << headers.map do |var|
948           if var[0] == ?@
949             obj.instance_variable_get(var)
950           else
951             obj[var[0..-2]]
952           end
953         end
954       end
955     end
956     
957     if io.is_a? String
958       csv.string
959     else
960       csv.close
961     end
962   end
963   
964   # 
965   # :call-seq:
966   #   filter( options = Hash.new ) { |row| ... }
967   #   filter( input, options = Hash.new ) { |row| ... }
968   #   filter( input, output, options = Hash.new ) { |row| ... }
969   # 
970   # This method is a convenience for building Unix-like filters for CSV data.
971   # Each row is yielded to the provided block which can alter it as needed.  
972   # After the block returns, the row is appended to +output+ altered or not.
973   # 
974   # The +input+ and +output+ arguments can be anything FasterCSV::new() accepts
975   # (generally String or IO objects).  If not given, they default to 
976   # <tt>ARGF</tt> and <tt>$stdout</tt>.
977   # 
978   # The +options+ parameter is also filtered down to FasterCSV::new() after some
979   # clever key parsing.  Any key beginning with <tt>:in_</tt> or 
980   # <tt>:input_</tt> will have that leading identifier stripped and will only
981   # be used in the +options+ Hash for the +input+ object.  Keys starting with
982   # <tt>:out_</tt> or <tt>:output_</tt> affect only +output+.  All other keys 
983   # are assigned to both objects.
984   # 
985   # The <tt>:output_row_sep</tt> +option+ defaults to
986   # <tt>$INPUT_RECORD_SEPARATOR</tt> (<tt>$/</tt>).
987   # 
988   def self.filter(*args)
989     # parse options for input, output, or both
990     in_options, out_options = Hash.new, {:row_sep => $INPUT_RECORD_SEPARATOR}
991     if args.last.is_a? Hash
992       args.pop.each do |key, value|
993         case key.to_s
994         when /\Ain(?:put)?_(.+)\Z/
995           in_options[$1.to_sym] = value
996         when /\Aout(?:put)?_(.+)\Z/
997           out_options[$1.to_sym] = value
998         else
999           in_options[key]  = value
1000           out_options[key] = value
1001         end
1002       end
1003     end
1004     # build input and output wrappers
1005     input   = FasterCSV.new(args.shift || ARGF,    in_options)
1006     output  = FasterCSV.new(args.shift || $stdout, out_options)
1007     
1008     # read, yield, write
1009     input.each do |row|
1010       yield row
1011       output << row
1012     end
1013   end
1014   
1015   # 
1016   # This method is intended as the primary interface for reading CSV files.  You
1017   # pass a +path+ and any +options+ you wish to set for the read.  Each row of
1018   # file will be passed to the provided +block+ in turn.
1019   # 
1020   # The +options+ parameter can be anything FasterCSV::new() understands.
1021   # 
1022   def self.foreach(path, options = Hash.new, &block)
1023     open(path, "rb", options) do |csv|
1024       csv.each(&block)
1025     end
1026   end
1028   # 
1029   # :call-seq:
1030   #   generate( str, options = Hash.new ) { |faster_csv| ... }
1031   #   generate( options = Hash.new ) { |faster_csv| ... }
1032   # 
1033   # This method wraps a String you provide, or an empty default String, in a 
1034   # FasterCSV object which is passed to the provided block.  You can use the 
1035   # block to append CSV rows to the String and when the block exits, the 
1036   # final String will be returned.
1037   # 
1038   # Note that a passed String *is* modfied by this method.  Call dup() before
1039   # passing if you need a new String.
1040   # 
1041   # The +options+ parameter can be anthing FasterCSV::new() understands.
1042   # 
1043   def self.generate(*args)
1044     # add a default empty String, if none was given
1045     if args.first.is_a? String
1046       io = StringIO.new(args.shift)
1047       io.seek(0, IO::SEEK_END)
1048       args.unshift(io)
1049     else
1050       args.unshift("")
1051     end
1052     faster_csv = new(*args)  # wrap
1053     yield faster_csv         # yield for appending
1054     faster_csv.string        # return final String
1055   end
1057   # 
1058   # This method is a shortcut for converting a single row (Array) into a CSV 
1059   # String.
1060   # 
1061   # The +options+ parameter can be anthing FasterCSV::new() understands.
1062   # 
1063   # The <tt>:row_sep</tt> +option+ defaults to <tt>$INPUT_RECORD_SEPARATOR</tt>
1064   # (<tt>$/</tt>) when calling this method.
1065   # 
1066   def self.generate_line(row, options = Hash.new)
1067     options = {:row_sep => $INPUT_RECORD_SEPARATOR}.merge(options)
1068     (new("", options) << row).string
1069   end
1070   
1071   # 
1072   # This method will return a FasterCSV instance, just like FasterCSV::new(), 
1073   # but the instance will be cached and returned for all future calls to this 
1074   # method for the same +data+ object (tested by Object#object_id()) with the
1075   # same +options+.
1076   # 
1077   # If a block is given, the instance is passed to the block and the return
1078   # value becomes the return value of the block.
1079   # 
1080   def self.instance(data = $stdout, options = Hash.new)
1081     # create a _signature_ for this method call, data object and options
1082     sig = [data.object_id] +
1083           options.values_at(*DEFAULT_OPTIONS.keys.sort_by { |sym| sym.to_s })
1084     
1085     # fetch or create the instance for this signature
1086     @@instances ||= Hash.new
1087     instance    =   (@@instances[sig] ||= new(data, options))
1089     if block_given?
1090       yield instance  # run block, if given, returning result
1091     else
1092       instance        # or return the instance
1093     end
1094   end
1095   
1096   # 
1097   # This method is the reading counterpart to FasterCSV::dump().  See that
1098   # method for a detailed description of the process.
1099   # 
1100   # You can customize loading by adding a class method called csv_load() which 
1101   # will be passed a Hash of meta information, an Array of headers, and an Array
1102   # of fields for the object the method is expected to return.
1103   # 
1104   # Remember that all fields will be Strings after this load.  If you need
1105   # something else, use +options+ to setup converters or provide a custom
1106   # csv_load() implementation.
1107   # 
1108   def self.load(io_or_str, options = Hash.new)
1109     csv = FasterCSV.new(io_or_str, options)
1110     
1111     # load meta information
1112     meta = Hash[*csv.shift]
1113     cls  = meta["class"].split("::").inject(Object) do |c, const|
1114       c.const_get(const)
1115     end
1116     
1117     # load headers
1118     headers = csv.shift
1119     
1120     # unserialize each object stored in the file
1121     results = csv.inject(Array.new) do |all, row|
1122       begin
1123         obj = cls.csv_load(meta, headers, row)
1124       rescue NoMethodError
1125         obj = cls.allocate
1126         headers.zip(row) do |name, value|
1127           if name[0] == ?@
1128             obj.instance_variable_set(name, value)
1129           else
1130             obj.send(name, value)
1131           end
1132         end
1133       end
1134       all << obj
1135     end
1136     
1137     csv.close unless io_or_str.is_a? String
1138     
1139     results
1140   end
1141   
1142   # 
1143   # :call-seq:
1144   #   open( filename, mode="rb", options = Hash.new ) { |faster_csv| ... }
1145   #   open( filename, mode="rb", options = Hash.new )
1146   # 
1147   # This method opens an IO object, and wraps that with FasterCSV.  This is
1148   # intended as the primary interface for writing a CSV file.
1149   # 
1150   # You may pass any +args+ Ruby's open() understands followed by an optional
1151   # Hash containing any +options+ FasterCSV::new() understands.
1152   # 
1153   # This method works like Ruby's open() call, in that it will pass a FasterCSV
1154   # object to a provided block and close it when the block termminates, or it
1155   # will return the FasterCSV object when no block is provided.  (*Note*: This
1156   # is different from the standard CSV library which passes rows to the block.  
1157   # Use FasterCSV::foreach() for that behavior.)
1158   # 
1159   # An opened FasterCSV object will delegate to many IO methods, for 
1160   # convenience.  You may call:
1161   # 
1162   # * binmode()
1163   # * close()
1164   # * close_read()
1165   # * close_write()
1166   # * closed?()
1167   # * eof()
1168   # * eof?()
1169   # * fcntl()
1170   # * fileno()
1171   # * flush()
1172   # * fsync()
1173   # * ioctl()
1174   # * isatty()
1175   # * pid()
1176   # * pos()
1177   # * reopen()
1178   # * seek()
1179   # * stat()
1180   # * sync()
1181   # * sync=()
1182   # * tell()
1183   # * to_i()
1184   # * to_io()
1185   # * tty?()
1186   # 
1187   def self.open(*args)
1188     # find the +options+ Hash
1189     options = if args.last.is_a? Hash then args.pop else Hash.new end
1190     # default to a binary open mode
1191     args << "rb" if args.size == 1
1192     # wrap a File opened with the remaining +args+
1193     csv     = new(File.open(*args), options)
1194     
1195     # handle blocks like Ruby's open(), not like the CSV library
1196     if block_given?
1197       begin
1198         yield csv
1199       ensure
1200         csv.close
1201       end
1202     else
1203       csv
1204     end
1205   end
1206   
1207   # 
1208   # :call-seq:
1209   #   parse( str, options = Hash.new ) { |row| ... }
1210   #   parse( str, options = Hash.new )
1211   # 
1212   # This method can be used to easily parse CSV out of a String.  You may either
1213   # provide a +block+ which will be called with each row of the String in turn,
1214   # or just use the returned Array of Arrays (when no +block+ is given).
1215   # 
1216   # You pass your +str+ to read from, and an optional +options+ Hash containing
1217   # anything FasterCSV::new() understands.
1218   # 
1219   def self.parse(*args, &block)
1220     csv = new(*args)
1221     if block.nil?  # slurp contents, if no block is given
1222       begin
1223         csv.read
1224       ensure
1225         csv.close
1226       end
1227     else           # or pass each row to a provided block
1228       csv.each(&block)
1229     end
1230   end
1231   
1232   # 
1233   # This method is a shortcut for converting a single line of a CSV String into 
1234   # a into an Array.  Note that if +line+ contains multiple rows, anything 
1235   # beyond the first row is ignored.
1236   # 
1237   # The +options+ parameter can be anthing FasterCSV::new() understands.
1238   # 
1239   def self.parse_line(line, options = Hash.new)
1240     new(line, options).shift
1241   end
1242   
1243   # 
1244   # Use to slurp a CSV file into an Array of Arrays.  Pass the +path+ to the 
1245   # file and any +options+ FasterCSV::new() understands.
1246   # 
1247   def self.read(path, options = Hash.new)
1248     open(path, "rb", options) { |csv| csv.read }
1249   end
1250   
1251   # Alias for FasterCSV::read().
1252   def self.readlines(*args)
1253     read(*args)
1254   end
1255   
1256   # 
1257   # A shortcut for:
1258   # 
1259   #   FasterCSV.read( path, { :headers           => true,
1260   #                           :converters        => :numeric,
1261   #                           :header_converters => :symbol }.merge(options) )
1262   # 
1263   def self.table(path, options = Hash.new)
1264     read( path, { :headers           => true,
1265                   :converters        => :numeric,
1266                   :header_converters => :symbol }.merge(options) )
1267   end
1268   
1269   # 
1270   # This constructor will wrap either a String or IO object passed in +data+ for
1271   # reading and/or writing.  In addition to the FasterCSV instance methods, 
1272   # several IO methods are delegated.  (See FasterCSV::open() for a complete 
1273   # list.)  If you pass a String for +data+, you can later retrieve it (after
1274   # writing to it, for example) with FasterCSV.string().
1275   # 
1276   # Note that a wrapped String will be positioned at at the beginning (for 
1277   # reading).  If you want it at the end (for writing), use 
1278   # FasterCSV::generate().  If you want any other positioning, pass a preset 
1279   # StringIO object instead.
1280   # 
1281   # You may set any reading and/or writing preferences in the +options+ Hash.  
1282   # Available options are:
1283   # 
1284   # <b><tt>:col_sep</tt></b>::            The String placed between each field.
1285   # <b><tt>:row_sep</tt></b>::            The String appended to the end of each
1286   #                                       row.  This can be set to the special
1287   #                                       <tt>:auto</tt> setting, which requests
1288   #                                       that FasterCSV automatically discover
1289   #                                       this from the data.  Auto-discovery
1290   #                                       reads ahead in the data looking for
1291   #                                       the next <tt>"\r\n"</tt>,
1292   #                                       <tt>"\n"</tt>, or <tt>"\r"</tt>
1293   #                                       sequence.  A sequence will be selected
1294   #                                       even if it occurs in a quoted field,
1295   #                                       assuming that you would have the same
1296   #                                       line endings there.  If none of those
1297   #                                       sequences is found, +data+ is
1298   #                                       <tt>ARGF</tt>, <tt>STDIN</tt>,
1299   #                                       <tt>STDOUT</tt>, or <tt>STDERR</tt>,
1300   #                                       or the stream is only available for
1301   #                                       output, the default
1302   #                                       <tt>$INPUT_RECORD_SEPARATOR</tt>
1303   #                                       (<tt>$/</tt>) is used.  Obviously,
1304   #                                       discovery takes a little time.  Set
1305   #                                       manually if speed is important.  Also
1306   #                                       note that IO objects should be opened
1307   #                                       in binary mode on Windows if this
1308   #                                       feature will be used as the
1309   #                                       line-ending translation can cause
1310   #                                       problems with resetting the document
1311   #                                       position to where it was before the
1312   #                                       read ahead.
1313   # <b><tt>:quote_char</tt></b>::         The character used to quote fields.
1314   #                                       This has to be a single character
1315   #                                       String.  This is useful for
1316   #                                       application that incorrectly use
1317   #                                       <tt>'</tt> as the quote character
1318   #                                       instead of the correct <tt>"</tt>.
1319   #                                       FasterCSV will always consider a
1320   #                                       double sequence this character to be
1321   #                                       an escaped quote.
1322   # <b><tt>:encoding</tt></b>::           The encoding to use when parsing the
1323   #                                       file. Defaults to your <tt>$KDOCE</tt>
1324   #                                       setting. Valid values: <tt>`n’</tt> or
1325   #                                       <tt>`N’</tt> for none, <tt>`e’</tt> or
1326   #                                       <tt>`E’</tt> for EUC, <tt>`s’</tt> or
1327   #                                       <tt>`S’</tt> for SJIS, and
1328   #                                       <tt>`u’</tt> or <tt>`U’</tt> for UTF-8
1329   #                                       (see Regexp.new()).
1330   # <b><tt>:field_size_limit</tt></b>::   This is a maximum size FasterCSV will
1331   #                                       read ahead looking for the closing
1332   #                                       quote for a field.  (In truth, it
1333   #                                       reads to the first line ending beyond
1334   #                                       this size.)  If a quote cannot be
1335   #                                       found within the limit FasterCSV will
1336   #                                       raise a MalformedCSVError, assuming
1337   #                                       the data is faulty.  You can use this
1338   #                                       limit to prevent what are effectively
1339   #                                       DoS attacks on the parser.  However,
1340   #                                       this limit can cause a legitimate
1341   #                                       parse to fail and thus is set to
1342   #                                       +nil+, or off, by default.
1343   # <b><tt>:converters</tt></b>::         An Array of names from the Converters
1344   #                                       Hash and/or lambdas that handle custom
1345   #                                       conversion.  A single converter
1346   #                                       doesn't have to be in an Array.
1347   # <b><tt>:unconverted_fields</tt></b>:: If set to +true+, an
1348   #                                       unconverted_fields() method will be
1349   #                                       added to all returned rows (Array or
1350   #                                       FasterCSV::Row) that will return the
1351   #                                       fields as they were before convertion.
1352   #                                       Note that <tt>:headers</tt> supplied
1353   #                                       by Array or String were not fields of
1354   #                                       the document and thus will have an
1355   #                                       empty Array attached.
1356   # <b><tt>:headers</tt></b>::            If set to <tt>:first_row</tt> or 
1357   #                                       +true+, the initial row of the CSV
1358   #                                       file will be treated as a row of
1359   #                                       headers.  If set to an Array, the
1360   #                                       contents will be used as the headers.
1361   #                                       If set to a String, the String is run
1362   #                                       through a call of
1363   #                                       FasterCSV::parse_line() with the same
1364   #                                       <tt>:col_sep</tt>, <tt>:row_sep</tt>,
1365   #                                       and <tt>:quote_char</tt> as this
1366   #                                       instance to produce an Array of
1367   #                                       headers.  This setting causes
1368   #                                       FasterCSV.shift() to return rows as
1369   #                                       FasterCSV::Row objects instead of
1370   #                                       Arrays and FasterCSV.read() to return
1371   #                                       FasterCSV::Table objects instead of
1372   #                                       an Array of Arrays.
1373   # <b><tt>:return_headers</tt></b>::     When +false+, header rows are silently
1374   #                                       swallowed.  If set to +true+, header
1375   #                                       rows are returned in a FasterCSV::Row
1376   #                                       object with identical headers and
1377   #                                       fields (save that the fields do not go
1378   #                                       through the converters).
1379   # <b><tt>:write_headers</tt></b>::      When +true+ and <tt>:headers</tt> is
1380   #                                       set, a header row will be added to the
1381   #                                       output.
1382   # <b><tt>:header_converters</tt></b>::  Identical in functionality to
1383   #                                       <tt>:converters</tt> save that the
1384   #                                       conversions are only made to header
1385   #                                       rows.
1386   # <b><tt>:skip_blanks</tt></b>::        When set to a +true+ value, FasterCSV
1387   #                                       will skip over any rows with no
1388   #                                       content.
1389   # <b><tt>:force_quotes</tt></b>::       When set to a +true+ value, FasterCSV
1390   #                                       will quote all CSV fields it creates.
1391   # 
1392   # See FasterCSV::DEFAULT_OPTIONS for the default settings.
1393   # 
1394   # Options cannot be overriden in the instance methods for performance reasons,
1395   # so be sure to set what you want here.
1396   # 
1397   def initialize(data, options = Hash.new)
1398     # build the options for this read/write
1399     options = DEFAULT_OPTIONS.merge(options)
1400     
1401     # create the IO object we will read from
1402     @io = if data.is_a? String then StringIO.new(data) else data end
1403     
1404     init_separators(options)
1405     init_parsers(options)
1406     init_converters(options)
1407     init_headers(options)
1408     
1409     unless options.empty?
1410       raise ArgumentError, "Unknown options:  #{options.keys.join(', ')}."
1411     end
1412     
1413     # track our own lineno since IO gets confused about line-ends is CSV fields
1414     @lineno = 0
1415   end
1416   
1417   # 
1418   # The line number of the last row read from this file.  Fields with nested 
1419   # line-end characters will not affect this count.
1420   # 
1421   attr_reader :lineno
1422   
1423   ### IO and StringIO Delegation ###
1424   
1425   extend Forwardable
1426   def_delegators :@io, :binmode, :close, :close_read, :close_write, :closed?,
1427                        :eof, :eof?, :fcntl, :fileno, :flush, :fsync, :ioctl,
1428                        :isatty, :pid, :pos, :reopen, :seek, :stat, :string,
1429                        :sync, :sync=, :tell, :to_i, :to_io, :tty?
1430   
1431   # Rewinds the underlying IO object and resets FasterCSV's lineno() counter.
1432   def rewind
1433     @headers = nil
1434     @lineno  = 0
1435     
1436     @io.rewind
1437   end
1439   ### End Delegation ###
1440   
1441   # 
1442   # The primary write method for wrapped Strings and IOs, +row+ (an Array or
1443   # FasterCSV::Row) is converted to CSV and appended to the data source.  When a
1444   # FasterCSV::Row is passed, only the row's fields() are appended to the
1445   # output.
1446   # 
1447   # The data source must be open for writing.
1448   # 
1449   def <<(row)
1450     # make sure headers have been assigned
1451     if header_row? and [Array, String].include? @use_headers.class
1452       parse_headers  # won't read data for Array or String
1453       self << @headers if @write_headers
1454     end
1455     
1456     # Handle FasterCSV::Row objects and Hashes
1457     row = case row
1458           when self.class::Row then row.fields
1459           when Hash            then @headers.map { |header| row[header] }
1460           else                      row
1461           end
1463     @headers =  row if header_row?
1464     @lineno  += 1
1466     @io << row.map(&@quote).join(@col_sep) + @row_sep  # quote and separate
1467     
1468     self  # for chaining
1469   end
1470   alias_method :add_row, :<<
1471   alias_method :puts,    :<<
1472   
1473   # 
1474   # :call-seq:
1475   #   convert( name )
1476   #   convert { |field| ... }
1477   #   convert { |field, field_info| ... }
1478   # 
1479   # You can use this method to install a FasterCSV::Converters built-in, or 
1480   # provide a block that handles a custom conversion.
1481   # 
1482   # If you provide a block that takes one argument, it will be passed the field
1483   # and is expected to return the converted value or the field itself.  If your
1484   # block takes two arguments, it will also be passed a FieldInfo Struct, 
1485   # containing details about the field.  Again, the block should return a 
1486   # converted field or the field itself.
1487   # 
1488   def convert(name = nil, &converter)
1489     add_converter(:converters, self.class::Converters, name, &converter)
1490   end
1492   # 
1493   # :call-seq:
1494   #   header_convert( name )
1495   #   header_convert { |field| ... }
1496   #   header_convert { |field, field_info| ... }
1497   # 
1498   # Identical to FasterCSV.convert(), but for header rows.
1499   # 
1500   # Note that this method must be called before header rows are read to have any
1501   # effect.
1502   # 
1503   def header_convert(name = nil, &converter)
1504     add_converter( :header_converters,
1505                    self.class::HeaderConverters,
1506                    name,
1507                    &converter )
1508   end
1509   
1510   include Enumerable
1511   
1512   # 
1513   # Yields each row of the data source in turn.
1514   # 
1515   # Support for Enumerable.
1516   # 
1517   # The data source must be open for reading.
1518   # 
1519   def each
1520     while row = shift
1521       yield row
1522     end
1523   end
1524   
1525   # 
1526   # Slurps the remaining rows and returns an Array of Arrays.
1527   # 
1528   # The data source must be open for reading.
1529   # 
1530   def read
1531     rows = to_a
1532     if @use_headers
1533       Table.new(rows)
1534     else
1535       rows
1536     end
1537   end
1538   alias_method :readlines, :read
1539   
1540   # Returns +true+ if the next row read will be a header row.
1541   def header_row?
1542     @use_headers and @headers.nil?
1543   end
1544   
1545   # 
1546   # The primary read method for wrapped Strings and IOs, a single row is pulled
1547   # from the data source, parsed and returned as an Array of fields (if header
1548   # rows are not used) or a FasterCSV::Row (when header rows are used).
1549   # 
1550   # The data source must be open for reading.
1551   # 
1552   def shift
1553     #########################################################################
1554     ### This method is purposefully kept a bit long as simple conditional ###
1555     ### checks are faster than numerous (expensive) method calls.         ###
1556     #########################################################################
1557     
1558     # handle headers not based on document content
1559     if header_row? and @return_headers and
1560        [Array, String].include? @use_headers.class
1561       if @unconverted_fields
1562         return add_unconverted_fields(parse_headers, Array.new)
1563       else
1564         return parse_headers
1565       end
1566     end
1567     
1568     # begin with a blank line, so we can always add to it
1569     line = String.new
1571     # 
1572     # it can take multiple calls to <tt>@io.gets()</tt> to get a full line,
1573     # because of \r and/or \n characters embedded in quoted fields
1574     # 
1575     loop do
1576       # add another read to the line
1577       begin
1578         line  += @io.gets(@row_sep)
1579       rescue
1580         return nil
1581       end
1582       # copy the line so we can chop it up in parsing
1583       parse =  line.dup
1584       parse.sub!(@parsers[:line_end], "")
1585       
1586       # 
1587       # I believe a blank line should be an <tt>Array.new</tt>, not 
1588       # CSV's <tt>[nil]</tt>
1589       # 
1590       if parse.empty?
1591         @lineno += 1
1592         if @skip_blanks
1593           line = ""
1594           next
1595         elsif @unconverted_fields
1596           return add_unconverted_fields(Array.new, Array.new)
1597         elsif @use_headers
1598           return FasterCSV::Row.new(Array.new, Array.new)
1599         else
1600           return Array.new
1601         end
1602       end
1604       # parse the fields with a mix of String#split and regular expressions
1605       csv           = Array.new
1606       current_field = String.new
1607       field_quotes  = 0
1608       parse.split(@col_sep, -1).each do |match|
1609         if current_field.empty? && match.count(@quote_and_newlines).zero?
1610           csv           << (match.empty? ? nil : match)
1611         elsif(current_field.empty? ? match[0] : current_field[0]) == @quote_char[0]
1612           current_field << match
1613           field_quotes += match.count(@quote_char)
1614           if field_quotes % 2 == 0
1615             in_quotes = current_field[@parsers[:quoted_field], 1]
1616             raise MalformedCSVError unless in_quotes
1617             current_field = in_quotes
1618             current_field.gsub!(@quote_char * 2, @quote_char) # unescape contents
1619             csv           << current_field
1620             current_field =  String.new
1621             field_quotes  =  0
1622           else # we found a quoted field that spans multiple lines
1623             current_field << @col_sep
1624           end
1625         elsif match.count("\r\n").zero?
1626           raise MalformedCSVError, "Illegal quoting on line #{lineno + 1}."
1627         else
1628           raise MalformedCSVError, "Unquoted fields do not allow " +
1629                                    "\\r or \\n (line #{lineno + 1})."
1630         end
1631       end
1633       # if parse is empty?(), we found all the fields on the line...
1634       if field_quotes % 2 == 0
1635         @lineno += 1
1637         # save fields unconverted fields, if needed...
1638         unconverted = csv.dup if @unconverted_fields
1640         # convert fields, if needed...
1641         csv = convert_fields(csv) unless @use_headers or @converters.empty?
1642         # parse out header rows and handle FasterCSV::Row conversions...
1643         csv = parse_headers(csv)  if     @use_headers
1645         # inject unconverted fields and accessor, if requested...
1646         if @unconverted_fields and not csv.respond_to? :unconverted_fields
1647           add_unconverted_fields(csv, unconverted)
1648         end
1650         # return the results
1651         break csv
1652       end
1653       # if we're not empty?() but at eof?(), a quoted field wasn't closed...
1654       if @io.eof?
1655         raise MalformedCSVError, "Unclosed quoted field on line #{lineno + 1}."
1656       elsif @field_size_limit and current_field.size >= @field_size_limit
1657         raise MalformedCSVError, "Field size exceeded on line #{lineno + 1}."
1658       end
1659       # otherwise, we need to loop and pull some more data to complete the row
1660     end
1661   end
1662   alias_method :gets,     :shift
1663   alias_method :readline, :shift
1664   
1665   # Returns a simplified description of the key FasterCSV attributes.
1666   def inspect
1667     str = "<##{self.class} io_type:"
1668     # show type of wrapped IO
1669     if    @io == $stdout then str << "$stdout"
1670     elsif @io == $stdin  then str << "$stdin"
1671     elsif @io == $stderr then str << "$stderr"
1672     else                      str << @io.class.to_s
1673     end
1674     # show IO.path(), if available
1675     if @io.respond_to?(:path) and (p = @io.path)
1676       str << " io_path:#{p.inspect}"
1677     end
1678     # show other attributes
1679     %w[ lineno     col_sep     row_sep
1680         quote_char skip_blanks encoding ].each do |attr_name|
1681       if a = instance_variable_get("@#{attr_name}")
1682         str << " #{attr_name}:#{a.inspect}"
1683       end
1684     end
1685     if @use_headers
1686       str << " headers:#{(@headers || true).inspect}"
1687     end
1688     str << ">"
1689   end
1690   
1691   private
1692   
1693   # 
1694   # Stores the indicated separators for later use.
1695   # 
1696   # If auto-discovery was requested for <tt>@row_sep</tt>, this method will read
1697   # ahead in the <tt>@io</tt> and try to find one.  +ARGF+, +STDIN+, +STDOUT+,
1698   # +STDERR+ and any stream open for output only with a default
1699   # <tt>@row_sep</tt> of <tt>$INPUT_RECORD_SEPARATOR</tt> (<tt>$/</tt>).
1700   # 
1701   # This method also establishes the quoting rules used for CSV output.
1702   # 
1703   def init_separators(options)
1704     # store the selected separators
1705     @col_sep            = options.delete(:col_sep)
1706     @row_sep            = options.delete(:row_sep)
1707     @quote_char         = options.delete(:quote_char)
1708     @quote_and_newlines = "#{@quote_char}\r\n"
1710     if @quote_char.length != 1
1711       raise ArgumentError, ":quote_char has to be a single character String"
1712     end
1713     
1714     # automatically discover row separator when requested
1715     if @row_sep == :auto
1716       if [ARGF, STDIN, STDOUT, STDERR].include?(@io) or
1717         (defined?(Zlib) and @io.class == Zlib::GzipWriter)
1718         @row_sep = $INPUT_RECORD_SEPARATOR
1719       else
1720         begin
1721           saved_pos = @io.pos  # remember where we were
1722           while @row_sep == :auto
1723             # 
1724             # if we run out of data, it's probably a single line 
1725             # (use a sensible default)
1726             # 
1727             if @io.eof?
1728               @row_sep = $INPUT_RECORD_SEPARATOR
1729               break
1730             end
1731       
1732             # read ahead a bit
1733             sample =  @io.read(1024)
1734             sample += @io.read(1) if sample[-1..-1] == "\r" and not @io.eof?
1735       
1736             # try to find a standard separator
1737             if sample =~ /\r\n?|\n/
1738               @row_sep = $&
1739               break
1740             end
1741           end
1742           # tricky seek() clone to work around GzipReader's lack of seek()
1743           @io.rewind
1744           # reset back to the remembered position
1745           while saved_pos > 1024  # avoid loading a lot of data into memory
1746             @io.read(1024)
1747             saved_pos -= 1024
1748           end
1749           @io.read(saved_pos) if saved_pos.nonzero?
1750         rescue IOError  # stream not opened for reading
1751           @row_sep = $INPUT_RECORD_SEPARATOR
1752         end
1753       end
1754     end
1755     
1756     # establish quoting rules
1757     do_quote = lambda do |field|
1758       @quote_char                                      +
1759       String(field).gsub(@quote_char, @quote_char * 2) +
1760       @quote_char
1761     end
1762     @quote = if options.delete(:force_quotes)
1763       do_quote
1764     else
1765       lambda do |field|
1766         if field.nil?  # represent +nil+ fields as empty unquoted fields
1767           ""
1768         else
1769           field = String(field)  # Stringify fields
1770           # represent empty fields as empty quoted fields
1771           if field.empty? or
1772              field.count("\r\n#{@col_sep}#{@quote_char}").nonzero?
1773             do_quote.call(field)
1774           else
1775             field  # unquoted field
1776           end
1777         end
1778       end
1779     end
1780   end
1781   
1782   # Pre-compiles parsers and stores them by name for access during reads.
1783   def init_parsers(options)
1784     # store the parser behaviors
1785     @skip_blanks      = options.delete(:skip_blanks)
1786     @encoding         = options.delete(:encoding)  # nil will use $KCODE
1787     @field_size_limit = options.delete(:field_size_limit)
1789     # prebuild Regexps for faster parsing
1790     esc_col_sep = Regexp.escape(@col_sep)
1791     esc_row_sep = Regexp.escape(@row_sep)
1792     esc_quote   = Regexp.escape(@quote_char)
1793     @parsers = {
1794       :any_field      => Regexp.new( "[^#{esc_col_sep}]+",
1795                                      Regexp::MULTILINE,
1796                                      @encoding ),
1797       :quoted_field   => Regexp.new( "^#{esc_quote}(.*)#{esc_quote}$",
1798                                      Regexp::MULTILINE,
1799                                      @encoding ),
1800       # safer than chomp!()
1801       :line_end       => Regexp.new("#{esc_row_sep}\\z", nil, @encoding)
1802     }
1803   end
1804   
1805   # 
1806   # Loads any converters requested during construction.
1807   # 
1808   # If +field_name+ is set <tt>:converters</tt> (the default) field converters
1809   # are set.  When +field_name+ is <tt>:header_converters</tt> header converters
1810   # are added instead.
1811   # 
1812   # The <tt>:unconverted_fields</tt> option is also actived for 
1813   # <tt>:converters</tt> calls, if requested.
1814   # 
1815   def init_converters(options, field_name = :converters)
1816     if field_name == :converters
1817       @unconverted_fields = options.delete(:unconverted_fields)
1818     end
1820     instance_variable_set("@#{field_name}", Array.new)
1821     
1822     # find the correct method to add the coverters
1823     convert = method(field_name.to_s.sub(/ers\Z/, ""))
1824     
1825     # load converters
1826     unless options[field_name].nil?
1827       # allow a single converter not wrapped in an Array
1828       unless options[field_name].is_a? Array
1829         options[field_name] = [options[field_name]]
1830       end
1831       # load each converter...
1832       options[field_name].each do |converter|
1833         if converter.is_a? Proc  # custom code block
1834           convert.call(&converter)
1835         else                     # by name
1836           convert.call(converter)
1837         end
1838       end
1839     end
1840     
1841     options.delete(field_name)
1842   end
1843   
1844   # Stores header row settings and loads header converters, if needed.
1845   def init_headers(options)
1846     @use_headers    = options.delete(:headers)
1847     @return_headers = options.delete(:return_headers)
1848     @write_headers  = options.delete(:write_headers)
1850     # headers must be delayed until shift(), in case they need a row of content
1851     @headers = nil
1852     
1853     init_converters(options, :header_converters)
1854   end
1855   
1856   # 
1857   # The actual work method for adding converters, used by both 
1858   # FasterCSV.convert() and FasterCSV.header_convert().
1859   # 
1860   # This method requires the +var_name+ of the instance variable to place the
1861   # converters in, the +const+ Hash to lookup named converters in, and the
1862   # normal parameters of the FasterCSV.convert() and FasterCSV.header_convert()
1863   # methods.
1864   # 
1865   def add_converter(var_name, const, name = nil, &converter)
1866     if name.nil?  # custom converter
1867       instance_variable_get("@#{var_name}") << converter
1868     else          # named converter
1869       combo = const[name]
1870       case combo
1871       when Array  # combo converter
1872         combo.each do |converter_name|
1873           add_converter(var_name, const, converter_name)
1874         end
1875       else        # individual named converter
1876         instance_variable_get("@#{var_name}") << combo
1877       end
1878     end
1879   end
1880   
1881   # 
1882   # Processes +fields+ with <tt>@converters</tt>, or <tt>@header_converters</tt>
1883   # if +headers+ is passed as +true+, returning the converted field set.  Any
1884   # converter that changes the field into something other than a String halts
1885   # the pipeline of conversion for that field.  This is primarily an efficiency
1886   # shortcut.
1887   # 
1888   def convert_fields(fields, headers = false)
1889     # see if we are converting headers or fields
1890     converters = headers ? @header_converters : @converters
1891     
1892     fields.enum_for(:each_with_index).map do |field, index|  # map_with_index
1893       converters.each do |converter|
1894         field = if converter.arity == 1  # straight field converter
1895           converter[field]
1896         else                             # FieldInfo converter
1897           header = @use_headers && !headers ? @headers[index] : nil
1898           converter[field, FieldInfo.new(index, lineno, header)]
1899         end
1900         break unless field.is_a? String  # short-curcuit pipeline for speed
1901       end
1902       field  # return final state of each field, converted or original
1903     end
1904   end
1905   
1906   # 
1907   # This methods is used to turn a finished +row+ into a FasterCSV::Row.  Header
1908   # rows are also dealt with here, either by returning a FasterCSV::Row with
1909   # identical headers and fields (save that the fields do not go through the
1910   # converters) or by reading past them to return a field row. Headers are also
1911   # saved in <tt>@headers</tt> for use in future rows.
1912   # 
1913   # When +nil+, +row+ is assumed to be a header row not based on an actual row
1914   # of the stream.
1915   # 
1916   def parse_headers(row = nil)
1917     if @headers.nil?                # header row
1918       @headers = case @use_headers  # save headers
1919                  # Array of headers
1920                  when Array  then @use_headers
1921                  # CSV header String
1922                  when String
1923                    self.class.parse_line( @use_headers,
1924                                           :col_sep    => @col_sep,
1925                                           :row_sep    => @row_sep,
1926                                           :quote_char => @quote_char )
1927                  # first row is headers
1928                  else             row
1929                  end
1930       
1931       # prepare converted and unconverted copies
1932       row      = @headers                       if row.nil?
1933       @headers = convert_fields(@headers, true)
1934       
1935       if @return_headers                                     # return headers
1936         return FasterCSV::Row.new(@headers, row, true)
1937       elsif not [Array, String].include? @use_headers.class  # skip to field row
1938         return shift
1939       end
1940     end
1942     FasterCSV::Row.new(@headers, convert_fields(row))  # field row
1943   end
1944   
1945   # 
1946   # Thiw methods injects an instance variable <tt>unconverted_fields</tt> into
1947   # +row+ and an accessor method for it called unconverted_fields().  The
1948   # variable is set to the contents of +fields+.
1949   # 
1950   def add_unconverted_fields(row, fields)
1951     class << row
1952       attr_reader :unconverted_fields
1953     end
1954     row.instance_eval { @unconverted_fields = fields }
1955     row
1956   end
1959 # Another name for FasterCSV.
1960 FCSV = FasterCSV
1962 # Another name for FasterCSV::instance().
1963 def FasterCSV(*args, &block)
1964   FasterCSV.instance(*args, &block)
1967 # Another name for FCSV::instance().
1968 def FCSV(*args, &block)
1969   FCSV.instance(*args, &block)
1972 class Array
1973   # Equivalent to <tt>FasterCSV::generate_line(self, options)</tt>.
1974   def to_csv(options = Hash.new)
1975     FasterCSV.generate_line(self, options)
1976   end
1979 class String
1980   # Equivalent to <tt>FasterCSV::parse_line(self, options)</tt>.
1981   def parse_csv(options = Hash.new)
1982     FasterCSV.parse_line(self, options)
1983   end