|
From: | John Croisant |
Subject: | [PATCH] Add `locative-index` procedure in (chicken locative) |
Date: | Sat, 8 Jan 2022 14:20:08 -0600 |
User-agent: | Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Thunderbird/78.14.0 |
Hi all,
This patch adds a locative-index procedure, which returns the index of a locative, i.e. the optional second argument to make-locative.
A locative does not actually store the index directly, but rather
stores a byte offset, which is index * bytes_per_item +
sizeof(C_header). So, locative-index performs the inverse
calculation to convert the byte offset back into the index. This
avoids changing the data layout of locatives.
I'm new to contributing to CHICKEN core, so I just followed the example of how locative->object was defined and registered (in extended-bindings, etc.). However, I did not add a rewrite rule in c-platform.scm because I wasn't sure about the correct arguments to (rewrite).
My use case for this feature is to implement a locative equivalent of the pointer+ procedure: given a locative, return a new locative referring to the same object but with an increased index. Using locative-index, I can implement this as:
(define (locative+ LOC N)
(make-locative
(locative->object LOC)
(+ N (locative-index LOC))))
Assuming it is not a weak locative, to keep the example code
simple.
Then I can use that to implement "views" of data stored in a
blob, to expose a limited range of the data, without copying. This
is especially useful for C libraries that use arrays, because an
array pointer + offset can be treated as an array. This is trivial
for arrays stored in unmanaged memory, using pointer math, but not
for arrays stored in blobs.
For example, suppose I have a blob containing a C array of Foo
structs. I can define a foo-array record type with a slot for a
locative to the blob, and another slot for the array length. I
could implement a (foo-array-slice array start end) procedure
which returns a new foo-array record, with an increased locative
index and decreased array length. This smaller array could then be
passed to any procedure or C function that expects a foo-array,
even passed to foo-array-slice again to make an even smaller view.
And, I could calculate the locative to a single Foo instance at an
index relative to the start of the view, not relative to the start
of the original array.
To accomplish this without the locative-index procedure, the foo-array record type would need an additional slot to store the index, which is a bit inconvenient and redundant, because that information is already stored in the locative.
- John Croisant
0001-Add-locative-index-procedure-in-chicken-locative.patch
Description: Text Data
[Prev in Thread] | Current Thread | [Next in Thread] |