Merge: Bench scripts
[nit.git] / lib / standard / string.nit
index 3e3dd65..fcc1f1b 100644 (file)
@@ -19,6 +19,7 @@ intrude import collection # FIXME should be collection::array
 
 `{
 #include <stdio.h>
+#include <string.h>
 `}
 
 ###############################################################################
@@ -32,16 +33,13 @@ abstract class Text
 
        redef type OTHER: Text
 
-       # Type of the view on self (.chars)
-       type SELFVIEW: StringCharView
-
        # Type of self (used for factorization of several methods, ex : substring_from, empty...)
        type SELFTYPE: Text
 
        # Gets a view on the chars of the Text object
        #
        #     assert "hello".chars.to_a == ['h', 'e', 'l', 'l', 'o']
-       fun chars: SELFVIEW is abstract
+       fun chars: SequenceRead[Char] is abstract
 
        # Number of characters contained in self.
        #
@@ -61,6 +59,9 @@ abstract class Text
        # In this case, `from += count` and `count -= from`.
        fun substring(from: Int, count: Int): SELFTYPE is abstract
 
+       # Iterates on the substrings of self if any
+       fun substrings: Iterator[Text] is abstract
+
        # Concatenates `o` to `self`
        #
        #     assert "hello" + "world"  == "helloworld"
@@ -123,6 +124,7 @@ abstract class Text
                var iter = self.chars.iterator_from(pos)
                while iter.is_ok do
                        if iter.item == c then return iter.index
+                       iter.next
                end
                return -1
        end
@@ -208,7 +210,7 @@ abstract class Text
        fun has_substring(str: String, pos: Int): Bool
        do
                var myiter = self.chars.iterator_from(pos)
-               var itsiter = str.iterator
+               var itsiter = str.chars.iterator
                while myiter.is_ok and itsiter.is_ok do
                        if myiter.item != itsiter.item then return false
                        myiter.next
@@ -425,7 +427,7 @@ abstract class Text
        fun escape_more_to_c(chars: String): String
        do
                var b = new FlatBuffer
-               for c in escape_to_c do
+               for c in escape_to_c.chars do
                        if chars.chars.has(c) then
                                b.add('\\')
                        end
@@ -445,12 +447,12 @@ abstract class Text
        #     assert s.length        ==  2
        #     var u = s.unescape_nit
        #     assert u.length        ==  1
-       #     assert u[0].ascii      ==  10 # (the ASCII value of the "new line" character)
+       #     assert u.chars[0].ascii      ==  10 # (the ASCII value of the "new line" character)
        fun unescape_nit: String
        do
                var res = new FlatBuffer.with_capacity(self.length)
                var was_slash = false
-               for c in self do
+               for c in chars do
                        if not was_slash then
                                if c == '\\' then
                                        was_slash = true
@@ -533,11 +535,9 @@ abstract class Text
                if hash_cache == null then
                        # djb2 hash algorithm
                        var h = 5381
-                       var i = length - 1
 
                        for char in self.chars do
-                               h = (h * 32) + h + char.ascii
-                               i -= 1
+                               h = h.lshift(5) + h + char.ascii
                        end
 
                        hash_cache = h
@@ -556,7 +556,7 @@ abstract class FlatText
        # Real items, used as cache for to_cstring is called
        private var real_items: nullable NativeString = null
 
-       redef var length: Int
+       redef var length: Int = 0
 
        init do end
 
@@ -574,7 +574,7 @@ end
 
 # Abstract class for the SequenceRead compatible
 # views on String and Buffer objects
-abstract class StringCharView
+private abstract class StringCharView
        super SequenceRead[Char]
 
        type SELFTYPE: Text
@@ -592,48 +592,12 @@ abstract class StringCharView
 
        redef fun iterator: IndexedIterator[Char] do return self.iterator_from(0)
 
-       # Gets a new Iterator starting at position `pos`
-       #
-       #     var iter = "abcd".chars.iterator_from(2)
-       #     assert iter.to_a == ['c', 'd']
-       fun iterator_from(pos: Int): IndexedIterator[Char] is abstract
-
-       # Gets an iterator starting at the end and going backwards
-       #
-       #     var reviter = "hello".chars.reverse_iterator
-       #     assert reviter.to_a == ['o', 'l', 'l', 'e', 'h']
-       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`
-       #
-       #     var reviter = "hello".chars.reverse_iterator_from(2)
-       #     assert reviter.to_a == ['l', 'e', 'h']
-       fun reverse_iterator_from(pos: Int): IndexedIterator[Char] is abstract
-
-       redef fun has(c: Char): Bool
-       do
-               for i in self do
-                       if i == c then return true
-               end
-               return false
-       end
-
-       redef fun ==(other)
-       do
-               if other == null then return false
-               if not other isa StringCharView then return false
-               var other_chars = other.iterator
-               for i in self do
-                       if i != other_chars.item then return false
-                       other_chars.next
-               end
-               return true
-       end
+       redef fun reverse_iterator do return self.reverse_iterator_from(self.length - 1)
 end
 
 # View on Buffer objects, extends Sequence
 # for mutation operations
-abstract class BufferCharView
+private abstract class BufferCharView
        super StringCharView
        super Sequence[Char]
 
@@ -648,6 +612,28 @@ abstract class String
 
        redef fun to_s do return self
 
+       fun append(s: String): SELFTYPE is abstract
+
+       fun prepend(s: String): SELFTYPE is abstract
+
+       fun insert_at(s: String, pos: Int): SELFTYPE is abstract
+end
+
+private class FlatSubstringsIter
+       super Iterator[FlatText]
+
+       var tgt: nullable FlatText
+
+       init(tgt: FlatText) do self.tgt = tgt
+
+       redef fun item do
+               assert is_ok
+               return tgt.as(not null)
+       end
+
+       redef fun is_ok do return tgt != null
+
+       redef fun next do tgt = null
 end
 
 # Immutable strings of characters.
@@ -655,37 +641,29 @@ class FlatString
        super FlatText
        super String
 
-       redef type SELFTYPE: FlatString
-
        # Index in _items of the start of the string
        private var index_from: Int
 
        # Indes in _items of the last item of the string
        private var index_to: Int
 
-       redef var chars: SELFVIEW = new FlatStringCharView(self)
+       redef var chars: SequenceRead[Char] = new FlatStringCharView(self)
 
        ################################################
        #       AbstractString specific methods        #
        ################################################
 
-       redef fun [](index) do
-               assert index >= 0
-               # Check that the index (+ index_from) is not larger than indexTo
-               # In other terms, if the index is valid
-               assert (index + index_from) <= index_to
-               return items[index + index_from]
-       end
-
        redef fun reversed
        do
                var native = calloc_string(self.length + 1)
-               var reviter = chars.reverse_iterator
+               var length = self.length
+               var items = self.items
                var pos = 0
-               while reviter.is_ok do
-                       native[pos] = reviter.item
+               var ipos = length-1
+               while pos < length do
+                       native[pos] = items[ipos]
                        pos += 1
-                       reviter.next
+                       ipos -= 1
                end
                return native.to_s_with_length(self.length)
        end
@@ -905,18 +883,15 @@ class FlatString
        redef fun hash
        do
                if hash_cache == null then
-                       # djb2 hash algorythm
+                       # djb2 hash algorithm
                        var h = 5381
-                       var i = length - 1
+                       var i = index_from
 
                        var myitems = items
-                       var strStart = index_from
-
-                       i += strStart
 
-                       while i >= strStart do
-                               h = (h * 32) + h + self.items[i].ascii
-                               i -= 1
+                       while i <= index_to do
+                               h = h.lshift(5) + h + myitems[i].ascii
+                               i += 1
                        end
 
                        hash_cache = h
@@ -924,6 +899,8 @@ class FlatString
 
                return hash_cache.as(not null)
        end
+
+       redef fun substrings do return new FlatSubstringsIter(self)
 end
 
 private class FlatStringReverseIterator
@@ -988,6 +965,7 @@ private class FlatStringCharView
                # Check that the index (+ index_from) is not larger than indexTo
                # In other terms, if the index is valid
                assert index >= 0
+               var target = self.target
                assert (index + target.index_from) <= target.index_to
                return target.items[index + target.index_from]
        end
@@ -1001,7 +979,6 @@ end
 abstract class Buffer
        super Text
 
-       redef type SELFVIEW: BufferCharView
        redef type SELFTYPE: Buffer
 
        # Specific implementations MUST set this to `true` in order to invalidate caches
@@ -1043,6 +1020,9 @@ abstract class Buffer
                return super
        end
 
+       # In Buffers, the internal sequence of character is mutable
+       # Thus, `chars` can be used to modify the buffer.
+       redef fun chars: Sequence[Char] is abstract
 end
 
 # Mutable strings of characters.
@@ -1052,9 +1032,11 @@ class FlatBuffer
 
        redef type SELFTYPE: FlatBuffer
 
-       redef var chars: SELFVIEW = new FlatBufferCharView(self)
+       redef var chars: Sequence[Char] = new FlatBufferCharView(self)
+
+       private var capacity: Int = 0
 
-       private var capacity: Int
+       redef fun substrings do return new FlatSubstringsIter(self)
 
        redef fun []=(index, item)
        do
@@ -1084,15 +1066,13 @@ class FlatBuffer
 
        redef fun enlarge(cap)
        do
-               is_dirty = true
                var c = capacity
                if cap <= c then return
                while c <= cap do c = c * 2 + 2
                var a = calloc_string(c+1)
-               items.copy_to(a, length, 0, 0)
+               if length > 0 then items.copy_to(a, length, 0, 0)
                items = a
                capacity = c
-               items.copy_to(a, length, 0, 0)
        end
 
        redef fun to_s: String
@@ -1105,7 +1085,7 @@ class FlatBuffer
                if is_dirty then
                        var new_native = calloc_string(length + 1)
                        new_native[length] = '\0'
-                       items.copy_to(new_native, length, 0, 0)
+                       if length > 0 then items.copy_to(new_native, length, 0, 0)
                        real_items = new_native
                        is_dirty = false
                end
@@ -1113,7 +1093,7 @@ class FlatBuffer
        end
 
        # Create a new empty string.
-       init do with_capacity(5)
+       init do end
 
        init from(s: Text)
        do
@@ -1145,6 +1125,7 @@ class FlatBuffer
 
        redef fun append(s)
        do
+               if s.is_empty then return
                is_dirty = true
                var sl = s.length
                if capacity < length + sl then enlarge(length + sl)
@@ -1217,6 +1198,24 @@ class FlatBuffer
                end
                return new_buf
        end
+
+       redef fun to_upper
+       do
+               var new_buf = new FlatBuffer.with_capacity(self.length)
+               for i in self.chars do
+                       new_buf.add(i.to_upper)
+               end
+               return new_buf
+       end
+
+       redef fun to_lower
+       do
+               var new_buf = new FlatBuffer.with_capacity(self.length)
+               for i in self.chars do
+                       new_buf.add(i.to_lower)
+               end
+               return new_buf
+       end
 end
 
 private class FlatBufferReverseIterator
@@ -1231,7 +1230,7 @@ private class FlatBufferReverseIterator
        init with_pos(tgt: FlatBuffer, pos: Int)
        do
                target = tgt
-               target_items = tgt.items
+               if tgt.length > 0 then target_items = tgt.items
                curr_pos = pos
        end
 
@@ -1303,7 +1302,7 @@ private class FlatBufferIterator
        init with_pos(tgt: FlatBuffer, pos: Int)
        do
                target = tgt
-               target_items = tgt.items
+               if tgt.length > 0 then target_items = tgt.items
                curr_pos = pos
        end
 
@@ -1367,6 +1366,15 @@ redef class Bool
 end
 
 redef class Int
+
+       # Wrapper of strerror C function
+       private fun strerror_ext: NativeString is extern `{
+               return strerror(recv);
+       `}
+
+       # Returns a string describing error number
+       fun strerror: String do return strerror_ext.to_s
+
        # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
        # assume < to_c max const of char
        private fun fill_buffer(s: Buffer, base: Int, signed: Bool)
@@ -1557,7 +1565,7 @@ redef class Collection[E]
        #
        #     assert [1, 2, 3].join(":")         == "1:2:3"
        #     assert [1..3].join(":")            == "1:2:3"
-       fun join(sep: String): String
+       fun join(sep: Text): String
        do
                if is_empty then return ""