summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorEkaitz Zarraga <ekaitz@elenq.tech>2024-01-18 14:46:22 +0100
committerEkaitz Zarraga <ekaitz@elenq.tech>2024-01-18 22:48:57 +0100
commit5f3fea525ded153e2ceb244b14b41bbf2afd5bc5 (patch)
tree8a03aecd33c3f6c652bf6852ef24f48e1cc0e5c9
parent6e062ef3fb2b18698a4c4ea3f203a544d2fa5097 (diff)
par: piece-table: add substring and rewrite ->string
Now ->string is rewritten in terms of substring, but later we'll need to rewrite this in a more generic way
-rw-r--r--par/piece-table.scm20
-rw-r--r--par/piece-table.sld1
-rw-r--r--tests/piece-table.scm9
3 files changed, 22 insertions, 8 deletions
diff --git a/par/piece-table.scm b/par/piece-table.scm
index a9b61f1..2892578 100644
--- a/par/piece-table.scm
+++ b/par/piece-table.scm
@@ -262,16 +262,20 @@
;; From/to string
(define string->piece-table make-piece-table)
-(define (piece-table->string piece-table)
- (let ((out-string (make-string (piece-table-text-length piece-table))))
+(define (piece-table-substring piece-table from to)
+ (let ((out-string (make-string (- to from))))
(let loop ((pieces (piece-table-pieces piece-table))
(acc 0))
- (if (null? pieces)
+ (if (or (null? pieces) (>= acc to))
out-string
(let ((piece (car pieces)))
- (string-copy! out-string
- acc
- (buffer->string (piece-buffer piece))
- (piece-start piece)
- (+ (piece-start piece) (piece-length piece)))
+ (string-copy!
+ out-string
+ (max (- acc from) 0)
+ (buffer->string (piece-buffer piece))
+ (+ (piece-start piece) (max (- from acc) 0))
+ (+ (piece-start piece) (min (- to acc) (piece-length piece))))
(loop (cdr pieces) (+ acc (piece-length piece))))))))
+
+(define (piece-table->string piece-table)
+ (piece-table-substring piece-table 0 (piece-table-text-length piece-table)))
diff --git a/par/piece-table.sld b/par/piece-table.sld
index 420175f..4650cb7 100644
--- a/par/piece-table.sld
+++ b/par/piece-table.sld
@@ -7,6 +7,7 @@
piece-table-insert!
piece-table-delete!
piece-table->string
+ piece-table-substring
string->piece-table
add-buffer-length)
(include "piece-table.scm"))
diff --git a/tests/piece-table.scm b/tests/piece-table.scm
index d6c1105..317286c 100644
--- a/tests/piece-table.scm
+++ b/tests/piece-table.scm
@@ -21,6 +21,15 @@
(test-equal "HOLA910" (piece-table->string table))
(test-end "insert")
+(test-begin "substring")
+ (parameterize ((add-buffer-length 10))
+ (define table (make-piece-table "1234567890"))
+ (test-equal "1234567890" (piece-table-substring table 0 10))
+ (test-equal "67890" (piece-table-substring table 5 10))
+ (piece-table-insert! table 6 "X" 'normal)
+ (test-equal "6X78" (piece-table-substring table 5 9)))
+(test-end "substring")
+
(test-begin "delete")
(define table (make-piece-table "HOLA SOY EKAITZ"))
(piece-table-delete! table 4 1)