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`
77 redef var length
: Int is noinit
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
102 length
= left
.length
+ right
.length
110 redef fun iterator
do return new RopeIter(self)
114 for j
in [1 .. i
[ do x
+= self
119 var llen
= left
.length
120 if i
>= llen
then return right
[i
- llen
]
124 redef fun substring
(from
, len
) do
125 var llen
= left
.length
127 if from
+ len
< llen
then return left
.substring
(from
,len
)
128 var lsublen
= llen
- from
129 return left
.substring_from
(from
) + right
.substring
(0, len
- lsublen
)
131 return right
.substring
(from
- llen
, len
)
135 redef fun reversed
do return new Concat(right
.reversed
, left
.reversed
)
137 redef fun insert_at
(s
, pos
) do
138 if pos
> left
.length
then
139 return left
+ right
.insert_at
(s
, pos
- left
.length
)
141 return left
.insert_at
(s
, pos
) + right
144 redef fun to_upper
do return new Concat(left
.to_upper
, right
.to_upper
)
146 redef fun to_lower
do return new Concat(left
.to_lower
, right
.to_lower
)
152 return new Concat(self, s
)
156 if rlen
+ slen
> maxlen
then return new Concat(self, s
)
157 return new Concat(left
, r
+ s
)
162 # Mutable `Rope`, optimized for concatenation operations
164 # A `RopeBuffer` is an efficient way of building a `String` when
165 # concatenating small strings.
167 # It does concatenations in an optimized way by having a
168 # mutable part and an immutable part built by efficiently
169 # concatenating strings in chain.
171 # Every concatenation operation is done by copying a string to
172 # the mutable part and flushing it when full.
174 # However, when a long string is appended to the `Buffer`,
175 # the concatenation is done at it would be in a `Rope`.
180 redef fun chars
: Sequence[Char] is cached
do return new RopeBufferChars(self)
182 # The final string being built on the fly
183 private var str
: String is noinit
185 # Current concatenation buffer
186 private var ns
: NativeString is noinit
188 # Next available (e.g. unset) character in the `Buffer`
191 # Keeps track of the buffer's currently dumped part
193 # This might happen if for instance, a String was being
194 # built by concatenating small parts of string and suddenly
195 # a long string (length > maxlen) is appended.
196 private var dumped
: Int is noinit
198 # Length of the complete rope
201 # Length of the mutable part
203 # Is also used as base to compute the size of the next
204 # mutable native string (`ns`)
205 private var buf_size
: Int is noinit
207 redef fun substrings
: Iterator[String] do return new RopeBufSubstringIterator(self)
209 # Builds an empty `RopeBuffer`
212 ns
= new NativeString(maxlen
)
217 # Builds a new `RopeBuffer` with `str` in it.
218 init from
(str
: String) do
220 ns
= new NativeString(maxlen
)
226 # Resets the informations of the `Buffer`
228 # This is called when doing in-place modifications
229 # on a previously to_s'd `RopeBuffer`
231 var nns
= new NativeString(buf_size
)
232 var blen
= rpos
- dumped
233 ns
.copy_to
(nns
, blen
, dumped
, 0)
240 redef fun empty
do return new RopeBuffer
248 ns
= new NativeString(buf_size
)
253 redef fun substring
(from
, count
) do
254 var strlen
= str
.length
258 if count
< 0 then count
= 0
262 if count
> length
then count
= length
- from
264 if count
== 0 then return empty
266 if from
< strlen
then
267 var subpos
= strlen
- from
268 if count
<= subpos
then
269 return new RopeBuffer.from
(str
.substring
(from
, count
))
271 var l
= str
.substring_from
(from
)
272 var rem
= count
- subpos
273 var nns
= new NativeString(rem
)
274 ns
.copy_to
(nns
, rem
, dumped
, 0)
275 return new RopeBuffer.from
(l
+ nns
.to_s_with_length
(rem
))
278 var nns
= new NativeString(count
)
279 ns
.copy_to
(nns
, count
, dumped
, 0)
280 return new RopeBuffer.from
(nns
.to_s_with_length
(count
))
284 redef fun append
(s
) do
288 if s
isa Rope or slen
> maxlen
then
289 if rp
> 0 and dumped
!= rp
then
290 str
+= new FlatString.with_infos
(ns
, rp
- dumped
, dumped
, rp
- 1)
296 var remsp
= buf_size
- rp
297 var sits
: NativeString
299 if s
isa FlatString then
302 else if s
isa FlatBuffer then
306 if slen
<= remsp
then
313 for i
in [0..remsp
[ do
327 if slen
<= remsp
then
332 sits
.copy_to
(ns
, slen
, begin
, rp
)
336 sits
.copy_to
(ns
, remsp
, begin
, rp
)
339 var nlen
= slen
- remsp
340 sits
.copy_to
(ns
, nlen
, begin
+ remsp
, 0)
347 if rp
>= buf_size
then
357 # Converts the Buffer to a FlatString, appends it to
358 # the final String and re-allocates a new larger Buffer.
359 private fun dump_buffer
do
361 var nstr
= new FlatString.with_infos
(ns
, rpos
- dumped
, dumped
, rpos
- 1)
365 ns
= new NativeString(bs
)
372 new FlatString.with_infos
(ns
, rpos
- dumped
, dumped
, rpos
- 1).output
375 # Enlarge is useless here since the `Buffer`
376 # part is automatically dumped when necessary.
378 # Also, since the buffer can not be overused by a
379 # single string, there is no need for manual
382 # "You have no power here !"
383 redef fun enlarge
(i
) do end
387 var nnslen
= rpos
- dumped
388 if nnslen
== 0 then return str
389 return str
+ new FlatString.with_infos
(ns
, rpos
- dumped
, dumped
, rpos
- 1)
393 # Flush the buffer in order to only have to reverse `str`.
394 if rpos
> 0 and dumped
!= rpos
then
395 str
+= new FlatString.with_infos
(ns
, rpos
- dumped
, dumped
, rpos
- 1)
402 if written
then reset
405 for i
in [0 .. rpos
[ do
406 mits
[i
] = mits
[i
].to_upper
411 if written
then reset
414 for i
in [0 .. rpos
[ do
415 mits
[i
] = mits
[i
].to_lower
420 redef class FlatString
422 redef fun insert_at
(s
, pos
) do
423 var l
= substring
(0, pos
)
424 var r
= substring_from
(pos
)
432 if slen
== 0 then return self
433 if mlen
== 0 then return s
434 var nlen
= slen
+ mlen
435 if s
isa FlatString then
436 if nlen
> maxlen
then return new Concat(self, s
)
438 var sifrom
= s
.index_from
439 var mifrom
= index_from
441 var ns
= new NativeString(nlen
+ 1)
442 mits
.copy_to
(ns
, mlen
, mifrom
, 0)
443 sits
.copy_to
(ns
, slen
, sifrom
, mlen
)
444 return ns
.to_s_with_length
(nlen
)
445 else if s
isa Concat then
447 var sllen
= sl
.length
448 if sllen
+ mlen
> maxlen
then return new Concat(self, s
)
449 return new Concat(self + sl
, s
.right
)
456 # A simple linked list for use with iterators
457 private class RopeIterPiece
458 # The encapsulated node of the `Rope`
460 # Was its left child (if any) visited ?
462 # Was its right child (if any) visited ?
464 # The previous node in the list.
465 var prev
: nullable RopeIterPiece
468 # A reverse iterator capable of working with `Rope` objects
469 private class RopeReviter
470 super IndexedIterator[Char]
472 # Current NativeString
474 # Current position in NativeString
476 # Position in the Rope (0-indexed)
478 # Iterator on the substrings, does the Postfix part of
479 # the Rope traversal.
480 var subs
: IndexedIterator[String]
482 init(root
: RopeString) is old_style_init
do
483 pos
= root
.length
- 1
484 subs
= new ReverseRopeSubstrings(root
)
489 init from
(root
: RopeString, pos
: Int) do
491 subs
= new ReverseRopeSubstrings.from
(root
, pos
)
493 pns
= pos
- subs
.index
496 redef fun index
do return pos
498 redef fun is_ok
do return pos
>= 0
500 redef fun item
do return ns
[pns
]
505 if pns
>= 0 then return
506 if not subs
.is_ok
then return
508 if not subs
.is_ok
then return
514 # Forward iterator on the chars of a `Rope`
515 private class RopeIter
516 super IndexedIterator[Char]
518 # Position in current `String`
520 # Current `String` being iterated on
522 # Substrings of the Rope
523 var subs
: IndexedIterator[String]
524 # Maximum position to iterate on (e.g. Rope.length)
526 # Position (char) in the Rope (0-indexed)
529 init(root
: RopeString) is old_style_init
do
530 subs
= new RopeSubstrings(root
)
533 max
= root
.length
- 1
537 init from
(root
: RopeString, pos
: Int) do
538 subs
= new RopeSubstrings.from
(root
, pos
)
539 pns
= pos
- subs
.index
542 max
= root
.length
- 1
545 redef fun item
do return str
[pns
]
547 redef fun is_ok
do return pos
<= max
549 redef fun index
do return pos
554 if pns
< subs
.item
.length
then return
555 if not subs
.is_ok
then return
557 if not subs
.is_ok
then return
563 # Substrings of a Rope (i.e. Reverse postfix iterator on leaves)
564 private class ReverseRopeSubstrings
565 super IndexedIterator[String]
568 var iter
: RopeIterPiece is noinit
570 var pos
: Int is noinit
573 var str
: String is noinit
575 init(root
: RopeString) is old_style_init
do
576 var r
= new RopeIterPiece(root
, false, true, null)
577 pos
= root
.length
- 1
578 var lnod
: String = root
580 if lnod
isa Concat then
582 r
= new RopeIterPiece(lnod
, false, true, r
)
591 init from
(root
: RopeString, pos
: Int) do
592 var r
= new RopeIterPiece(root
, false, true, null)
593 var rnod
: String = root
596 if rnod
isa Concat then
597 if off
>= rnod
.left
.length
then
598 off
-= rnod
.left
.length
600 r
= new RopeIterPiece(rnod
, false, true, r
)
604 r
= new RopeIterPiece(rnod
, false, true, r
)
616 redef fun item
do return str
618 redef fun index
do return pos
620 redef fun is_ok
do return pos
>= 0
623 if pos
< 0 then return
625 var currit
= curr
.node
626 while curr
!= null do
628 if not currit
isa Concat then
634 if not curr
.rdone
then
636 curr
= new RopeIterPiece(currit
.right
, false, false, curr
)
639 if not curr
.ldone
then
641 curr
= new RopeIterPiece(currit
.left
, false, false, curr
)
650 private class RopeBufSubstringIterator
651 super Iterator[String]
653 # Iterator on the substrings of the building string
654 var iter
: Iterator[String]
655 # Makes a String out of the buffered part of the Ropebuffer
657 # Did we attain the buffered part ?
658 var nsstr_done
= false
660 init(str
: RopeBuffer) is old_style_init
do
661 iter
= str
.str
.substrings
662 nsstr
= new FlatString.with_infos
(str
.ns
, str
.rpos
- str
.dumped
, str
.dumped
, str
.rpos
- 1)
663 if str
.length
== 0 then nsstr_done
= true
666 redef fun is_ok
do return iter
.is_ok
or not nsstr_done
670 if iter
.is_ok
then return iter
.item
683 # Substrings of a Rope (i.e. Postfix iterator on leaves)
684 private class RopeSubstrings
685 super IndexedIterator[String]
688 var iter
: RopeIterPiece is noinit
690 var pos
: Int is noinit
691 # Maximum position in `Rope` (i.e. length - 1)
692 var max
: Int is noinit
695 var str
: String is noinit
697 init(root
: RopeString) is old_style_init
do
698 var r
= new RopeIterPiece(root
, true, false, null)
700 max
= root
.length
- 1
701 var rnod
: String = root
703 if rnod
isa Concat then
705 r
= new RopeIterPiece(rnod
, true, false, r
)
715 init from
(root
: RopeString, pos
: Int) do
716 var r
= new RopeIterPiece(root
, true, false, null)
717 max
= root
.length
- 1
718 var rnod
: String = root
721 if rnod
isa Concat then
722 if off
>= rnod
.left
.length
then
724 off
-= rnod
.left
.length
726 r
= new RopeIterPiece(rnod
, true, false, r
)
729 r
= new RopeIterPiece(rnod
, true, false, r
)
741 redef fun item
do return str
743 redef fun is_ok
do return pos
<= max
745 redef fun index
do return pos
749 if pos
> max
then return
753 if not rnod
isa Concat then
757 iter
= it
.as(not null)
763 it
= new RopeIterPiece(rnod
, false, false, it
)
764 else if not it
.rdone
then
767 it
= new RopeIterPiece(rnod
, false, false, it
)
777 # Implementation of a `StringCharView` for `RopeString` objects
778 private class RopeChars
781 redef type SELFTYPE: RopeString
787 redef fun iterator_from
(i
) do return new RopeIter.from
(target
, i
)
789 redef fun reverse_iterator_from
(i
) do return new RopeReviter.from
(target
, i
)
793 # An Iterator over a RopeBuffer.
795 super IndexedIterator[Char]
798 var sit
: IndexedIterator[Char]
800 # Native string iterated over.
803 # Current position in `ns`.
806 # Maximum position iterable.
811 # Init the iterator from a RopeBuffer.
812 init(t
: RopeBuffer) is old_style_init
do
815 sit
= t
.str
.chars
.iterator
820 # Init the iterator from a RopeBuffer starting from `pos`.
821 init from
(t
: RopeBuffer, pos
: Int) do
824 sit
= t
.str
.chars
.iterator_from
(pos
)
825 pns
= pos
- t
.str
.length
829 redef fun is_ok
do return index
< maxpos
832 if sit
.is_ok
then return sit
.item
846 # Reverse iterator over a RopeBuffer.
847 class RopeBufferReviter
848 super IndexedIterator[Char]
851 var sit
: IndexedIterator[Char]
853 # Native string iterated over.
856 # Current position in `ns`.
861 # Init the iterator from a RopeBuffer.
862 init(tgt
: RopeBuffer) is old_style_init
do
863 sit
= tgt
.str
.chars
.reverse_iterator
865 index
= tgt
.length
- 1
869 # Init the iterator from a RopeBuffer starting from `pos`.
870 init from
(tgt
: RopeBuffer, pos
: Int) do
871 sit
= tgt
.str
.chars
.reverse_iterator_from
(pos
- tgt
.rpos
- tgt
.dumped
)
872 pns
= pos
- tgt
.str
.length
877 redef fun is_ok
do return index
> 0
880 if pns
>= 0 then return ns
[pns
]
894 # View on the chars of a `RopeBuffer`
895 class RopeBufferChars
898 redef type SELFTYPE: RopeBuffer
901 if i
< target
.str
.length
then
904 return target
.ns
[i
- target
.str
.length
]
908 redef fun []=(i
,c
) do
909 if i
== target
.length
then target
.add c
910 if i
< target
.str
.length
then
912 var l
= s
.substring
(0, i
)
913 var r
= s
.substring_from
(i
+ 1)
914 target
.str
= l
+ c
.to_s
+ r
916 target
.ns
[i
- target
.str
.length
] = c
920 redef fun add
(c
) do target
.add c
922 redef fun push
(c
) do target
.add c
924 redef fun iterator_from
(i
) do return new RopeBufferIter.from
(target
, i
)
926 redef fun reverse_iterator_from
(i
) do return new RopeBufferReviter.from
(target
, i
)