lib: add Seq:insert_all as a generalized `insert`
authorJean Privat <jean@pryen.org>
Fri, 15 Aug 2014 19:55:50 +0000 (15:55 -0400)
committerJean Privat <jean@pryen.org>
Fri, 15 Aug 2014 19:55:50 +0000 (15:55 -0400)
Signed-off-by: Jean Privat <jean@pryen.org>

lib/standard/collection/abstract_collection.nit
lib/standard/collection/array.nit

index 93d882a..b99c465 100644 (file)
@@ -835,10 +835,30 @@ interface Sequence[E]
        #     a.insert(100, 2)
        #     assert a      ==  [10, 20, 100, 30, 40]
        #
-       # REQUIRE `index >= 0 and index < length`
+       # REQUIRE `index >= 0 and index <= length`
        # ENSURE `self[index] == item`
        fun insert(item: E, index: Int) is abstract
 
+       # Insert all elements at a given position, following elements are shifted.
+       #
+       #     var a = [10, 20, 30, 40]
+       #     a.insert_all([100..102], 2)
+       #     assert a      ==  [10, 20, 100, 101, 102, 30, 40]
+       #
+       # REQUIRE `index >= 0 and index <= length`
+       # ENSURE `self[index] == coll.first`
+       fun insert_all(coll: Collection[E], index: Int)
+       do
+               assert index >= 0 and index < length
+               if index == length then
+                       add_all(coll)
+               end
+               for c in coll do
+                       insert(c, index)
+                       index += 1
+               end
+       end
+
        # Remove the item at `index` and shift all following elements
        #
        #     var a = [10,20,30]
index e98ddea..9482c8f 100644 (file)
@@ -186,6 +186,19 @@ abstract class AbstractArray[E]
                self[pos] = item
        end
 
+       redef fun insert_all(coll, pos)
+       do
+               var l = coll.length
+               if l == 0 then return
+               enlarge(length + l)
+               _length += l
+               copy_to(pos, length-pos-l, self, pos + l)
+               for c in coll do
+                       self[pos] = c
+                       pos += 1
+               end
+       end
+
        redef fun add(item) do self[length] = item
 
        redef fun clear do _length = 0