1 # This file is part of NIT (http://www.nitlanguage.org).
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
15 # Tree-based representation of a String.
17 # Ropes are a data structure introduced in a 1995 paper from
18 # Hans J. Boehm, Russ Atkinson and Michael Plass.
22 # > Ropes: an Alternative to Strings,
23 # > *Software - Practice and Experience*,
24 # > Vol. 25(12), 1315-1330 (December 1995).
26 # The implementation developed here provides an automatic change
27 # of data structure depending on the length of the leaves.
29 # The length from which a `Rope` is built from a `flat` string
30 # if defined at top-level (see `maxlen`) and can be redefined by clients
31 # depending on their needs (e.g. if you need to bench the speed of
32 # the creation of concat nodes, lower the size of maxlen).
34 # A Rope as defined in the original paper is a Tree made of concatenation
35 # nodes and containing `Flat` (that is Array-based) strings as Leaves.
43 # "My" " Name" " is" " Simon."
45 # Note that the above example is not representative of the actual implementation
46 # of `Ropes`, since short leaves are merged to keep the rope at an acceptable
47 # height (hence, this rope here might actually be a `FlatString` !).
52 # Maxlen is the maximum length of a Leaf node
54 # When concatenating two leaves, if `new_length` > `maxlen`,
55 # A `Concat` node is created instead
57 # Its purpose is to limit the depth of the `Rope` (this
58 # improves performance when accessing/iterating).
59 fun maxlen
: Int do return 64
61 # String using a tree-based representation with leaves as `FlatStrings`
62 private abstract class Rope
66 private abstract class RopeString
70 redef fun chars
is cached
do return new RopeChars(self)
73 # Node that represents a concatenation between two `String`
79 redef fun substrings
do return new RopeSubstrings(self)
81 redef fun empty
do return ""
83 redef fun to_cstring
is cached
do
85 var ns
= new NativeString(len
+ 1)
88 for i
in substrings
do
90 i
.as(FlatString).items
.copy_to
(ns
, ilen
, i
.as(FlatString).index_from
, off
)
96 # Left child of the node
98 # Right child of the node
101 init(l
: String, r
: String) is old_style_init
do
104 length
= l
.length
+ r
.length
112 redef fun iterator
do return new RopeIter(self)
116 for j
in [1 .. i
[ do x
+= self
121 var llen
= left
.length
122 if i
>= llen
then return right
[i
- llen
]
126 redef fun substring
(from
, len
) do
127 var llen
= left
.length
129 if from
+ len
< llen
then return left
.substring
(from
,len
)
130 var lsublen
= llen
- from
131 return left
.substring_from
(from
) + right
.substring
(0, len
- lsublen
)
133 return right
.substring
(from
- llen
, len
)
137 redef fun reversed
do return new Concat(right
.reversed
, left
.reversed
)
139 redef fun insert_at
(s
, pos
) do
140 if pos
> left
.length
then
141 return left
+ right
.insert_at
(s
, pos
- left
.length
)
143 return left
.insert_at
(s
, pos
) + right
146 redef fun to_upper
do return new Concat(left
.to_upper
, right
.to_upper
)
148 redef fun to_lower
do return new Concat(left
.to_lower
, right
.to_lower
)
154 return new Concat(self, s
)
158 if rlen
+ slen
> maxlen
then return new Concat(left
, new Concat(r
, s
))
159 return new Concat(left
, r
+ s
)
164 # Mutable `Rope`, optimized for concatenation operations
166 # A `RopeBuffer` is an efficient way of building a `String` when
167 # concatenating small strings.
169 # It does concatenations in an optimized way by having a
170 # mutable part and an immutable part built by efficiently
171 # concatenating strings in chain.
173 # Every concatenation operation is done by copying a string to
174 # the mutable part and flushing it when full.
176 # However, when a long string is appended to the `Buffer`,
177 # the concatenation is done at it would be in a `Rope`.
182 redef fun chars
: Sequence[Char] is cached
do return new RopeBufferChars(self)
184 # The final string being built on the fly
185 private var str
: String is noinit
187 # Current concatenation buffer
188 private var ns
: NativeString is noinit
190 # Next available (e.g. unset) character in the `Buffer`
193 # Keeps track of the buffer's currently dumped part
195 # This might happen if for instance, a String was being
196 # built by concatenating small parts of string and suddenly
197 # a long string (length > maxlen) is appended.
198 private var dumped
: Int is noinit
200 # Length of the complete rope
203 # Length of the mutable part
205 # Is also used as base to compute the size of the next
206 # mutable native string (`ns`)
207 private var buf_size
: Int is noinit
209 redef fun substrings
: Iterator[String] do return new RopeBufSubstringIterator(self)
211 # Builds an empty `RopeBuffer`
214 ns
= new NativeString(maxlen
)
219 # Builds a new `RopeBuffer` with `str` in it.
220 init from
(str
: String) do
222 ns
= new NativeString(maxlen
)
228 # Resets the informations of the `Buffer`
230 # This is called when doing in-place modifications
231 # on a previously to_s'd `RopeBuffer`
233 var nns
= new NativeString(buf_size
)
234 var blen
= rpos
- dumped
235 ns
.copy_to
(nns
, blen
, dumped
, 0)
242 redef fun empty
do return new RopeBuffer
250 ns
= new NativeString(buf_size
)
255 redef fun substring
(from
, count
) do
256 var strlen
= str
.length
260 if count
< 0 then count
= 0
264 if count
> length
then count
= length
- from
266 if count
== 0 then return empty
268 if from
< strlen
then
269 var subpos
= strlen
- from
270 if count
<= subpos
then
271 return new RopeBuffer.from
(str
.substring
(from
, count
))
273 var l
= str
.substring_from
(from
)
274 var rem
= count
- subpos
275 var nns
= new NativeString(rem
)
276 ns
.copy_to
(nns
, rem
, dumped
, 0)
277 return new RopeBuffer.from
(l
+ nns
.to_s_with_length
(rem
))
280 var nns
= new NativeString(count
)
281 ns
.copy_to
(nns
, count
, dumped
, 0)
282 return new RopeBuffer.from
(nns
.to_s_with_length
(count
))
286 redef fun append
(s
) do
290 if s
isa Rope or slen
> maxlen
then
291 if rp
> 0 and dumped
!= rp
then
292 str
+= new FlatString.with_infos
(ns
, rp
- dumped
, dumped
, rp
- 1)
298 var remsp
= buf_size
- rp
299 var sits
: NativeString
301 if s
isa FlatString then
304 else if s
isa FlatBuffer then
308 if slen
<= remsp
then
315 for i
in [0..remsp
[ do
329 if slen
<= remsp
then
334 sits
.copy_to
(ns
, slen
, begin
, rp
)
338 sits
.copy_to
(ns
, remsp
, begin
, rp
)
341 var nlen
= slen
- remsp
342 sits
.copy_to
(ns
, nlen
, begin
+ remsp
, 0)
349 if rp
>= buf_size
then
359 # Converts the Buffer to a FlatString, appends it to
360 # the final String and re-allocates a new larger Buffer.
361 private fun dump_buffer
do
363 var nstr
= new FlatString.with_infos
(ns
, rpos
- dumped
, dumped
, rpos
- 1)
367 ns
= new NativeString(bs
)
374 new FlatString.with_infos
(ns
, rpos
- dumped
, dumped
, rpos
- 1).output
377 # Enlarge is useless here since the `Buffer`
378 # part is automatically dumped when necessary.
380 # Also, since the buffer can not be overused by a
381 # single string, there is no need for manual
384 # "You have no power here !"
385 redef fun enlarge
(i
) do end
389 var nnslen
= rpos
- dumped
390 if nnslen
== 0 then return str
391 return str
+ new FlatString.with_infos
(ns
, rpos
- dumped
, dumped
, rpos
- 1)
395 # Flush the buffer in order to only have to reverse `str`.
396 if rpos
> 0 and dumped
!= rpos
then
397 str
+= new FlatString.with_infos
(ns
, rpos
- dumped
, dumped
, rpos
- 1)
404 if written
then reset
407 for i
in [0 .. rpos
[ do
408 mits
[i
] = mits
[i
].to_upper
413 if written
then reset
416 for i
in [0 .. rpos
[ do
417 mits
[i
] = mits
[i
].to_lower
422 redef class FlatString
424 redef fun insert_at
(s
, pos
) do
425 var l
= substring
(0, pos
)
426 var r
= substring_from
(pos
)
434 if slen
== 0 then return self
435 if mlen
== 0 then return s
436 var nlen
= slen
+ mlen
437 if s
isa FlatString then
438 if nlen
> maxlen
then return new Concat(self, s
)
440 var sifrom
= s
.index_from
441 var mifrom
= index_from
443 var ns
= new NativeString(nlen
+ 1)
444 mits
.copy_to
(ns
, mlen
, mifrom
, 0)
445 sits
.copy_to
(ns
, slen
, sifrom
, mlen
)
446 return ns
.to_s_with_length
(nlen
)
447 else if s
isa Concat then
449 var sllen
= sl
.length
450 if sllen
+ mlen
> maxlen
then return new Concat(self, s
)
451 return new Concat(self + sl
, s
.right
)
458 # A simple linked list for use with iterators
459 private class RopeIterPiece
460 # The encapsulated node of the `Rope`
462 # Was its left child (if any) visited ?
464 # Was its right child (if any) visited ?
466 # The previous node in the list.
467 var prev
: nullable RopeIterPiece
470 # A reverse iterator capable of working with `Rope` objects
471 private class RopeReviter
472 super IndexedIterator[Char]
474 # Current NativeString
476 # Current position in NativeString
478 # Position in the Rope (0-indexed)
480 # Iterator on the substrings, does the Postfix part of
481 # the Rope traversal.
482 var subs
: IndexedIterator[String]
484 init(root
: RopeString) is old_style_init
do
485 pos
= root
.length
- 1
486 subs
= new ReverseRopeSubstrings(root
)
491 init from
(root
: RopeString, pos
: Int) do
493 subs
= new ReverseRopeSubstrings.from
(root
, pos
)
495 pns
= pos
- subs
.index
498 redef fun index
do return pos
500 redef fun is_ok
do return pos
>= 0
502 redef fun item
do return ns
[pns
]
507 if pns
>= 0 then return
508 if not subs
.is_ok
then return
510 if not subs
.is_ok
then return
516 # Forward iterator on the chars of a `Rope`
517 private class RopeIter
518 super IndexedIterator[Char]
520 # Position in current `String`
522 # Current `String` being iterated on
524 # Substrings of the Rope
525 var subs
: IndexedIterator[String]
526 # Maximum position to iterate on (e.g. Rope.length)
528 # Position (char) in the Rope (0-indexed)
531 init(root
: RopeString) is old_style_init
do
532 subs
= new RopeSubstrings(root
)
535 max
= root
.length
- 1
539 init from
(root
: RopeString, pos
: Int) do
540 subs
= new RopeSubstrings.from
(root
, pos
)
541 pns
= pos
- subs
.index
544 max
= root
.length
- 1
547 redef fun item
do return str
[pns
]
549 redef fun is_ok
do return pos
<= max
551 redef fun index
do return pos
556 if pns
< subs
.item
.length
then return
557 if not subs
.is_ok
then return
559 if not subs
.is_ok
then return
565 # Substrings of a Rope (i.e. Reverse postfix iterator on leaves)
566 private class ReverseRopeSubstrings
567 super IndexedIterator[String]
570 var iter
: RopeIterPiece is noinit
572 var pos
: Int is noinit
575 var str
: String is noinit
577 init(root
: RopeString) is old_style_init
do
578 var r
= new RopeIterPiece(root
, false, true, null)
579 pos
= root
.length
- 1
580 var lnod
: String = root
582 if lnod
isa Concat then
584 r
= new RopeIterPiece(lnod
, false, true, r
)
593 init from
(root
: RopeString, pos
: Int) do
594 var r
= new RopeIterPiece(root
, false, true, null)
595 var rnod
: String = root
598 if rnod
isa Concat then
599 if off
>= rnod
.left
.length
then
600 off
-= rnod
.left
.length
602 r
= new RopeIterPiece(rnod
, false, true, r
)
606 r
= new RopeIterPiece(rnod
, false, true, r
)
618 redef fun item
do return str
620 redef fun index
do return pos
622 redef fun is_ok
do return pos
>= 0
625 if pos
< 0 then return
627 var currit
= curr
.node
628 while curr
!= null do
630 if not currit
isa Concat then
636 if not curr
.rdone
then
638 curr
= new RopeIterPiece(currit
.right
, false, false, curr
)
641 if not curr
.ldone
then
643 curr
= new RopeIterPiece(currit
.left
, false, false, curr
)
652 private class RopeBufSubstringIterator
653 super Iterator[String]
655 # Iterator on the substrings of the building string
656 var iter
: Iterator[String]
657 # Makes a String out of the buffered part of the Ropebuffer
659 # Did we attain the buffered part ?
660 var nsstr_done
= false
662 init(str
: RopeBuffer) is old_style_init
do
663 iter
= str
.str
.substrings
664 nsstr
= new FlatString.with_infos
(str
.ns
, str
.rpos
- str
.dumped
, str
.dumped
, str
.rpos
- 1)
665 if str
.length
== 0 then nsstr_done
= true
668 redef fun is_ok
do return iter
.is_ok
or not nsstr_done
672 if iter
.is_ok
then return iter
.item
685 # Substrings of a Rope (i.e. Postfix iterator on leaves)
686 private class RopeSubstrings
687 super IndexedIterator[String]
690 var iter
: RopeIterPiece is noinit
692 var pos
: Int is noinit
693 # Maximum position in `Rope` (i.e. length - 1)
694 var max
: Int is noinit
697 var str
: String is noinit
699 init(root
: RopeString) is old_style_init
do
700 var r
= new RopeIterPiece(root
, true, false, null)
702 max
= root
.length
- 1
703 var rnod
: String = root
705 if rnod
isa Concat then
707 r
= new RopeIterPiece(rnod
, true, false, r
)
717 init from
(root
: RopeString, pos
: Int) do
718 var r
= new RopeIterPiece(root
, true, false, null)
719 max
= root
.length
- 1
720 var rnod
: String = root
723 if rnod
isa Concat then
724 if off
>= rnod
.left
.length
then
726 off
-= rnod
.left
.length
728 r
= new RopeIterPiece(rnod
, true, false, r
)
731 r
= new RopeIterPiece(rnod
, true, false, r
)
743 redef fun item
do return str
745 redef fun is_ok
do return pos
<= max
747 redef fun index
do return pos
751 if pos
> max
then return
755 if not rnod
isa Concat then
759 iter
= it
.as(not null)
765 it
= new RopeIterPiece(rnod
, false, false, it
)
766 else if not it
.rdone
then
769 it
= new RopeIterPiece(rnod
, false, false, it
)
779 # Implementation of a `StringCharView` for `RopeString` objects
780 private class RopeChars
785 init(s
: RopeString) is old_style_init
do tgt
= s
791 redef fun iterator_from
(i
) do return new RopeIter.from
(tgt
, i
)
793 redef fun reverse_iterator_from
(i
) do return new RopeReviter.from
(tgt
, i
)
797 # An Iterator over a RopeBuffer.
799 super IndexedIterator[Char]
802 var sit
: IndexedIterator[Char]
804 # Native string iterated over.
807 # Current position in `ns`.
810 # Maximum position iterable.
815 # Init the iterator from a RopeBuffer.
816 init(t
: RopeBuffer) is old_style_init
do
819 sit
= t
.str
.chars
.iterator
824 # Init the iterator from a RopeBuffer starting from `pos`.
825 init from
(t
: RopeBuffer, pos
: Int) do
828 sit
= t
.str
.chars
.iterator_from
(pos
)
829 pns
= pos
- t
.str
.length
833 redef fun is_ok
do return index
< maxpos
836 if sit
.is_ok
then return sit
.item
850 # Reverse iterator over a RopeBuffer.
851 class RopeBufferReviter
852 super IndexedIterator[Char]
855 var sit
: IndexedIterator[Char]
857 # Native string iterated over.
860 # Current position in `ns`.
865 # Init the iterator from a RopeBuffer.
866 init(tgt
: RopeBuffer) is old_style_init
do
867 sit
= tgt
.str
.chars
.reverse_iterator
869 index
= tgt
.length
- 1
873 # Init the iterator from a RopeBuffer starting from `pos`.
874 init from
(tgt
: RopeBuffer, pos
: Int) do
875 sit
= tgt
.str
.chars
.reverse_iterator_from
(pos
- tgt
.rpos
- tgt
.dumped
)
876 pns
= pos
- tgt
.str
.length
881 redef fun is_ok
do return index
> 0
884 if pns
>= 0 then return ns
[pns
]
898 # View on the chars of a `RopeBuffer`
899 class RopeBufferChars
902 redef type SELFTYPE: RopeBuffer
905 if i
< target
.str
.length
then
908 return target
.ns
[i
- target
.str
.length
]
912 redef fun []=(i
,c
) do
913 if i
== target
.length
then target
.add c
914 if i
< target
.str
.length
then
916 var l
= s
.substring
(0, i
)
917 var r
= s
.substring_from
(i
+ 1)
918 target
.str
= l
+ c
.to_s
+ r
920 target
.ns
[i
- target
.str
.length
] = c
924 redef fun add
(c
) do target
.add c
926 redef fun push
(c
) do target
.add c
928 redef fun iterator_from
(i
) do return new RopeBufferIter.from
(target
, i
)
930 redef fun reverse_iterator_from
(i
) do return new RopeBufferReviter.from
(target
, i
)