[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: How to effectively insert into string?

From: Mike Gran
Subject: Re: How to effectively insert into string?
Date: Mon, 9 Mar 2020 07:24:19 -0700

On Mon, Mar 09, 2020 at 01:20:45PM +0100, Jan Synacek wrote:
> Hello,
> how do I write a function that inserts into a string (or deletes from a
> string) effectively in guile? There's some mention about how strings are
> implemented in the info manual, but it's not really clear to me. Is it
> necessary to implement a gap buffer / rope / something similar, or can it
> effectively be achieved with only guile's strings?

Strings in guile are codepoints stored in contiguous memory locations. So,
like for C strings, a standard string insert would be to
- allocate a new memory buffer
- copy sections from the old string to the beginning and end of that buffer
- copy the new text into the middle of that buffer

You can get close to that by
  (string-append (substring OLD 0 POS) newstring (substring OLD POS))
Fortunately, 'substring' does not make a new copy of the string.  The
substring's memory is the same as the original strings memory, until
a modification is made (copy-on-write).

The same theory applies for deleting from a string.

You can learn a bit about the guts of any string by using the
%string-dump procedure.

But if you want to do many small insertions into lengthy strings, you
may want to put together a gap buffer.

Guile comes with a rather unmaintained and under-documented gap buffer
in the (ice-9 gap-buffer) module.  I've never used it personally.

Mike Gran

reply via email to

[Prev in Thread] Current Thread [Next in Thread]