text/flat: FlatText::char_to_byte_index do the +1 first (and 0 last)
[nit.git] / lib / core / text / flat.nit
index 9a70db8..200fdcf 100644 (file)
@@ -52,8 +52,8 @@ redef class FlatText
        fun char_to_byte_index(index: Int): Int do
                var dpos = index - _position
                var b = _bytepos
+               var its = _items
 
-               if dpos == 0 then return b
                if dpos == 1 then
                        b += _items.length_of_char_at(b)
                        _bytepos = b
@@ -61,11 +61,12 @@ redef class FlatText
                        return b
                end
                if dpos == -1 then
-                       b = _items.find_beginning_of_char_at(b - 1)
+                       b = its.find_beginning_of_char_at(b - 1)
                        _bytepos = b
                        _position = index
                        return b
                end
+               if dpos == 0 then return b
 
                var ln = _length
                var pos = _position
@@ -74,7 +75,6 @@ redef class FlatText
                var delta_end = (ln - 1) - index
                var delta_cache = (pos - index).abs
                var min = delta_begin
-               var its = _items
 
                if delta_cache < min then min = delta_cache
                if delta_end < min then min = delta_end
@@ -370,7 +370,7 @@ class FlatString
 
        redef fun substring(from, count)
        do
-               assert count >= 0
+               if count <= 0 then return ""
 
                if from < 0 then
                        count += from
@@ -1250,6 +1250,10 @@ redef class NativeString
        #
        # Very unsafe, make sure to have room for this char prior to calling this function.
        private fun set_char_at(pos: Int, c: Char) do
+               if c.code_point < 128 then
+                       self[pos] = c.code_point.to_b
+                       return
+               end
                var ln = c.u8char_len
                native_set_char(pos, c, ln)
        end