stdlib/strings: Detached the Text block from Collection.
[nit.git] / lib / standard / string.nit
index b9ee718..de11bac 100644 (file)
@@ -5,7 +5,7 @@
 #
 # This file is free software, which comes along with NIT.  This software is
 # distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
-# without  even  the implied warranty of  MERCHANTABILITY or  FITNESS FOR A 
+# without  even  the implied warranty of  MERCHANTABILITY or  FITNESS FOR A
 # PARTICULAR PURPOSE.  You can modify it is you want,  provided this header
 # is kept unaltered, and a notification of the changes is added.
 # You  are  allowed  to  redistribute it and sell it, alone or is a part of
@@ -14,6 +14,7 @@
 # Basic manipulations of strings of characters
 module string
 
+import math
 intrude import collection # FIXME should be collection::array
 
 `{
@@ -24,18 +25,14 @@ intrude import collection # FIXME should be collection::array
 # String                                                                      #
 ###############################################################################
 
-# Common subclass for String and Buffer
-abstract class AbstractString
-       super AbstractArrayRead[Char]
-
-       readable private var _items: NativeString
+# High-level abstraction for all text representations
+abstract class Text
 
+       # Gets a view on the chars of the Text object
        fun chars: StringCharView is abstract
 
-       # Access a character at `index` in the string.
-       #
-       #     assert "abcd"[2]         == 'c'
-       redef fun [](index) do return _items[index]
+       # Number of characters contained in self.
+       fun length: Int is abstract
 
        # Create a substring.
        #
@@ -47,24 +44,103 @@ abstract class AbstractString
        # A `from` index < 0 will be replaced by 0.
        # Unless a `count` value is > 0 at the same time.
        # In this case, `from += count` and `count -= from`.
-       fun substring(from: Int, count: Int): String
+       fun substring(from: Int, count: Int): String is abstract
+
+       # Is the current Text empty (== "")
+       #       assert "".is_empty
+       #       assert not "foo".is_empty
+       fun is_empty: Bool do return self.length == 0
+
+       # Gets the first char of the Text
+       #
+       # DEPRECATED : Use self.chars.first instead
+       fun first: Char do return self.chars[0]
+
+       # Access a character at `index` in the string.
+       #
+       #     assert "abcd"[2]         == 'c'
+       #
+       # DEPRECATED : Use self.chars.[] instead
+       fun [](index: Int): Char do return self.chars[index]
+
+       # Gets the index of the first occurence of 'c'
+       #
+       # Returns -1 if not found
+       #
+       # DEPRECATED : Use self.chars.index_of instead
+       fun index_of(c: Char): Int
        do
-               assert count >= 0
-               count += from
-               if from < 0 then from = 0
-               if count > length then count = length
-               if from < count then
-                       var r = new Buffer.with_capacity(count - from)
-                       while from < count do
-                               r.chars.push(_items[from])
-                               from += 1
-                       end
-                       return r.to_s
-               else
-                       return ""
+               return index_of_from(c, 0)
+       end
+
+       # Gets the last char of self
+       #
+       # DEPRECATED : Use self.chars.last instead
+       fun last: Char do return self.chars[length-1]
+
+       # Gets the index of the first occurence of ´c´ starting from ´pos´
+       #
+       # Returns -1 if not found
+       #
+       # DEPRECATED : Use self.chars.index_of_from instead
+       fun index_of_from(c: Char, pos: Int): Int
+       do
+               var iter = self.chars.iterator_from(pos)
+               while iter.is_ok do
+                       if iter.item == c then return iter.index
+               end
+               return -1
+       end
+
+       # Gets the last index of char ´c´
+       #
+       # Returns -1 if not found
+       #
+       # DEPRECATED : Use self.chars.last_index_of instead
+       fun last_index_of(c: Char): Int
+       do
+               return last_index_of_from(c, length - 1)
+       end
+
+       # The index of the last occurrence of an element starting from pos (in reverse order).
+       # Example :
+       #               assert "/etc/bin/test/test.nit".last_index_of_from('/', length-1) == 13
+       #               assert "/etc/bin/test/test.nit".last_index_of_from('/', 12) == 8
+       #
+       # Returns -1 if not found
+       #
+       # DEPRECATED : Use self.chars.last_index_of_from instead
+       fun last_index_of_from(item: Char, pos: Int): Int
+       do
+               var iter = self.chars.reverse_iterator_from(pos)
+               while iter.is_ok do
+                       if iter.item == item then return iter.index
+                       iter.next
                end
+               return -1
+       end
+
+       # Gets an iterator on the chars of self
+       #
+       # DEPRECATED : Use self.chars.iterator instead
+       fun iterator: Iterator[Char]
+       do
+               return self.chars.iterator
        end
 
+       # Is 'c' contained in self ?
+       #
+       # DEPRECATED : Use self.chars.has instead
+       fun has(c: Char): Bool
+       do
+               return self.chars.has(c)
+       end
+
+       # Gets an Array containing the chars of self
+       #
+       # DEPRECATED : Use self.chars.to_a instead
+       fun to_a: Array[Char] do return chars.to_a
+
        # Create a substring from `self` beginning at the `from` position
        #
        #     assert "abcd".substring_from(1)    ==  "bcd"
@@ -84,18 +160,14 @@ abstract class AbstractString
        #     assert "abcd".has_substring("bc",2)            ==  false
        fun has_substring(str: String, pos: Int): Bool
        do
-               var itsindex = str.length - 1
-               var myindex = pos + itsindex
-               var myitems = _items
-               var itsitems = str._items
-               if myindex > length or itsindex > myindex  then return false
-               var its_index_from = str._index_from
-               itsindex += its_index_from
-               while itsindex >= its_index_from do
-                       if myitems[myindex] != itsitems[itsindex] then return false
-                       myindex -= 1
-                       itsindex -= 1
+               var myiter = self.chars.iterator_from(pos)
+               var itsiter = str.iterator
+               while myiter.is_ok and itsiter.is_ok do
+                       if myiter.item != itsiter.item then return false
+                       myiter.next
+                       itsiter.next
                end
+               if itsiter.is_ok then return false
                return true
        end
 
@@ -233,15 +305,6 @@ abstract class AbstractString
                return self.substring(start_pos, end_pos - start_pos + 1)
        end
 
-       redef fun output
-       do
-               var i = 0
-               while i < length do
-                       _items[i].output
-                       i += 1
-               end
-       end
-
        # Mangle a string to be a unique string only made of alphanumeric characters
        fun to_cmangle: String
        do
@@ -308,7 +371,7 @@ abstract class AbstractString
        do
                var b = new Buffer
                for c in escape_to_c do
-                       if chars.has(c) then
+                       if chars.chars.has(c) then
                                b.add('\\')
                        end
                        b.add(c)
@@ -357,6 +420,27 @@ abstract class AbstractString
                end
                return res.to_s
        end
+
+end
+
+# Common subclass for String and Buffer
+abstract class AbstractString
+       super Text
+
+       readable private var _items: NativeString
+
+       redef readable private var _length: Int
+
+       init do end
+
+       redef fun output
+       do
+               var i = 0
+               while i < length do
+                       _items[i].output
+                       i += 1
+               end
+       end
 end
 
 # Abstract class for the SequenceRead compatible
@@ -364,7 +448,7 @@ end
 abstract class StringCharView
        super SequenceRead[Char]
 
-       type SELFTYPE: AbstractString
+       type SELFTYPE: Text
 
        private var target: SELFTYPE
 
@@ -377,6 +461,44 @@ abstract class StringCharView
 
        redef fun length do return target.length
 
+       redef fun iterator: IndexedIterator[Char] do return self.iterator_from(0)
+
+       # Gets a new Iterator starting at position `pos`
+       #
+       # Ex :
+       #       var iter = "abcd".iterator_from(2)
+       #       while iter.is_ok do
+       #               printn iter.item
+       #               iter.next
+       #       end
+       #
+       # Outputs : cd
+       fun iterator_from(pos: Int): IndexedIterator[Char] is abstract
+
+       # Gets an iterator starting at the end and going backwards
+       #
+       # Ex :
+       #       var reviter = "now step live...".reverse_iterator
+       #       while reviter.is_ok do
+       #               printn reviter.item
+       #               reviter.next
+       #       end
+       #
+       # Outputs : ...evil pets won
+       fun reverse_iterator: IndexedIterator[Char] do return self.reverse_iterator_from(self.length - 1)
+
+       # Gets an iterator on the chars of self starting from `pos`
+       #
+       # Ex :
+       #       var iter = "abcd".reverse_iterator_from(1)
+       #       while iter.is_ok do
+       #               printn iter.item
+       #               iter.next
+       #       end
+       #
+       # Outputs : ba
+       fun reverse_iterator_from(pos: Int): IndexedIterator[Char] is abstract
+
        redef fun has(c: Char): Bool
        do
                for i in self do
@@ -446,36 +568,6 @@ class String
                return new String.with_infos(_items, to - realFrom + 1, realFrom, to)
        end
 
-       redef fun substring_from(from: Int): String
-       do
-               if from > _length then return ""
-               if from < 0 then from = 0
-               return substring(from, _length)
-       end
-
-       redef fun has_substring(str: String, pos: Int): Bool
-       do
-               var itsindex = str._length - 1
-
-               var myindex = pos + itsindex
-               var myitems = _items
-
-               var itsitems = str._items
-
-               if myindex > _length or itsindex > myindex then return false
-
-               var itsindexfrom = str.index_from
-               itsindex += itsindexfrom
-               myindex += index_from
-
-               while itsindex >= itsindexfrom do
-                       if myitems[myindex] != itsitems[itsindex] then return false
-                       myindex -= 1
-                       itsindex -= 1
-               end
-
-               return true
-       end
 
        redef fun to_upper: String
        do
@@ -706,6 +798,32 @@ class String
        end
 end
 
+private class FlatStringReverseIterator
+       super IndexedIterator[Char]
+
+       var target: String
+
+       var target_items: NativeString
+
+       var curr_pos: Int
+
+       init with_pos(tgt: String, pos: Int)
+       do
+               target = tgt
+               target_items = tgt.items
+               curr_pos = pos + tgt.index_from
+       end
+
+       redef fun is_ok do return curr_pos >= 0
+
+       redef fun item do return target_items[curr_pos]
+
+       redef fun next do curr_pos -= 1
+
+       redef fun index do return curr_pos - target.index_from
+
+end
+
 private class FlatStringIterator
        super IndexedIterator[Char]
 
@@ -746,7 +864,9 @@ private class FlatStringCharView
                return target._items[index + target._index_from]
        end
 
-       redef fun iterator: IndexedIterator[Char] do return new FlatStringIterator.with_pos(target, 0)
+       redef fun iterator_from(start) do return new FlatStringIterator.with_pos(target, start)
+
+       redef fun reverse_iterator_from(start) do return new FlatStringReverseIterator.with_pos(target, start)
 
 end
 
@@ -755,13 +875,15 @@ class Buffer
        super AbstractString
        super Comparable
        super StringCapable
-       super AbstractArray[Char]
 
        redef type OTHER: String
 
        redef var chars: BufferCharView = new FlatBufferCharView(self)
 
-       redef fun []=(index, item)
+       # Modifies the char contained at pos `index`
+       #
+       # DEPRECATED : Use self.chars.[]= instead
+       fun []=(index: Int, item: Char)
        do
                if index == length then
                        add(item)
@@ -771,14 +893,21 @@ class Buffer
                _items[index] = item
        end
 
-       redef fun add(c)
+       # Adds a char `c` at the end of self
+       #
+       # DEPRECATED : Use self.chars.add instead
+       fun add(c: Char)
        do
                if _capacity <= length then enlarge(length + 5)
                _items[length] = c
                _length += 1
        end
 
-       redef fun enlarge(cap)
+       # Clears the buffer
+       fun clear do _length = 0
+
+       # Enlarges the subsequent array containing the chars of self
+       fun enlarge(cap: Int)
        do
                var c = _capacity
                if cap <= c then return
@@ -787,18 +916,7 @@ class Buffer
                _items.copy_to(a, length, 0, 0)
                _items = a
                _capacity = c
-       end
-
-       redef fun append(s)
-       do
-               if s isa String then
-                       var sl = s.length
-                       if _capacity < _length + sl then enlarge(_length + sl)
-                       s.items.copy_to(_items, sl, s._index_from, _length)
-                       _length += sl
-               else
-                       super
-               end
+               items.copy_to(a, length, 0, 0)
        end
 
        redef fun to_s: String
@@ -859,6 +977,15 @@ class Buffer
                _length = 0
        end
 
+       # Adds the content of string `s` at the end of self
+       fun append(s: String)
+       do
+               var sl = s.length
+               if capacity < length + sl then enlarge(length + sl)
+               s.items.copy_to(items, sl, s.index_from, length)
+               _length += sl
+       end
+
        redef fun ==(o)
        do
                if not o isa Buffer then return false
@@ -875,6 +1002,60 @@ class Buffer
        end
 
        readable private var _capacity: Int
+
+       # Copies the content of self in `dest`
+       fun copy(start: Int, len: Int, dest: Buffer, new_start: Int)
+       do
+               var self_chars = self.chars
+               var dest_chars = dest.chars
+               for i in [0..len-1] do
+                       dest_chars[new_start+i] = self_chars[start+i]
+               end
+       end
+
+       redef fun substring(from, count)
+       do
+               assert count >= 0
+               count += from
+               if from < 0 then from = 0
+               if count > length then count = length
+               if from < count then
+                       var r = new Buffer.with_capacity(count - from)
+                       while from < count do
+                               r.chars.push(_items[from])
+                               from += 1
+                       end
+                       return r.to_s
+               else
+                       return ""
+               end
+       end
+end
+
+private class FlatBufferReverseIterator
+       super IndexedIterator[Char]
+
+       var target: Buffer
+
+       var target_items: NativeString
+
+       var curr_pos: Int
+
+       init with_pos(tgt: Buffer, pos: Int)
+       do
+               target = tgt
+               target_items = tgt.items
+               curr_pos = pos
+       end
+
+       redef fun index do return curr_pos
+
+       redef fun is_ok do return curr_pos >= 0
+
+       redef fun item do return target_items[curr_pos]
+
+       redef fun next do curr_pos -= 1
+
 end
 
 private class FlatBufferCharView
@@ -883,11 +1064,6 @@ private class FlatBufferCharView
 
        redef type SELFTYPE: Buffer
 
-       init(tgt: Buffer)
-       do
-               self.target = tgt
-       end
-
        redef fun [](index) do return target._items[index]
 
        redef fun []=(index, item)
@@ -922,7 +1098,9 @@ private class FlatBufferCharView
                if target.capacity < s.length then enlarge(s_length + target.length)
        end
 
-       redef fun iterator: IndexedIterator[Char] do return new FlatBufferIterator.with_pos(target, 0)
+       redef fun iterator_from(pos) do return new FlatBufferIterator.with_pos(target, pos)
+
+       redef fun reverse_iterator_from(pos) do return new FlatBufferReverseIterator.with_pos(target, pos)
 
 end
 
@@ -992,13 +1170,13 @@ redef class Bool
        #     assert true.to_s         == "true"
        #     assert false.to_s        == "false"
        redef fun to_s
-       do 
-               if self then 
-                       return once "true" 
-               else 
-                       return once "false" 
+       do
+               if self then
+                       return once "true"
+               else
+                       return once "false"
                end
-       end   
+       end
 end
 
 redef class Int
@@ -1019,7 +1197,7 @@ redef class Int
                end
                # Fill digits
                var pos = digit_count(base) - 1
-               while pos >= 0 and n > 0 do 
+               while pos >= 0 and n > 0 do
                        s.chars[pos] = (n % base).to_c
                        n = n / base # /
                        pos -= 1
@@ -1055,6 +1233,7 @@ redef class Float
        # Pretty print self, print needoed decimals up to a max of 3.
        redef fun to_s do
                var str = to_precision( 3 )
+               if is_inf != 0 or is_nan then return str
                var len = str.length
                for i in [0..len-1] do
                        var j = len-1-i
@@ -1073,6 +1252,15 @@ redef class Float
        # `self` representation with `nb` digits after the '.'.
        fun to_precision(nb: Int): String
        do
+               if is_nan then return "nan"
+
+               var isinf = self.is_inf
+               if isinf == 1 then
+                       return "inf"
+               else if isinf == -1 then
+                       return  "-inf"
+               end
+
                if nb == 0 then return self.to_i.to_s
                var f = self
                for i in [0..nb[ do f = f * 10.0
@@ -1156,14 +1344,14 @@ redef class Collection[E]
        fun join(sep: String): String
        do
                if is_empty then return ""
-               
+
                var s = new Buffer # Result
 
                # Concat first item
                var i = iterator
                var e = i.item
                if e != null then s.append(e.to_s)
-               
+
                # Concat other items
                i.next
                while i.is_ok do
@@ -1204,7 +1392,7 @@ redef class Map[K,V]
        fun join(sep: String, couple_sep: String): String
        do
                if is_empty then return ""
-               
+
                var s = new Buffer # Result
 
                # Concat first item