Skip to content

Rope from stream #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Dec 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion rope.lisp
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,22 @@
;;-------;;

(defgeneric make-rope (source)
(:documentation "Create a new rope from a string.")
(:documentation "Create a new rope from a string, stream, or pathname.")
(:method ((source rope))
source)
(:method ((source stream))
(labels ((read-leaves (&optional acc)
(let* ((string (make-string *long-leaf*))
(length (read-sequence string source))
(leaf (make-instance 'leaf :length length :string (subseq string 0 length))))
(if (= *long-leaf* length)
(read-leaves (cons leaf acc))
(cons leaf acc)))))
(let ((leaves (nreverse (read-leaves))))
(merge-leaves leaves 0 (length leaves)))))
(:method ((source pathname))
(with-open-file (s source)
(make-rope s)))
(:method ((source string))
(let ((length (length source)))
(if (<= *long-leaf* length)
Expand Down
9 changes: 9 additions & 0 deletions test/basic.lisp
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,12 @@ can be done efficiently.")
(let* ((rope (rope:make-rope "0123456789")))
(is (string= #\1 (rope:index-rope rope 1)))
(is (string= #\9 (rope:index-rope rope 9)))))

(deftest read-files-and-streams ()
"Test reading a file to a rope."
(let* ((pathname (merge-pathnames "README.md" (asdf:system-source-directory :rope)))
(rope (rope:make-rope pathname)))
(is (string= (uiop:read-file-string pathname) (rope:write-rope rope nil))))
(let* ((stream (make-string-input-stream *string-2*))
(rope (rope:make-rope stream)))
(is (string= *string-2* (rope:write-rope rope nil)))))
Loading