Hi, I have an use case where I need to get the offset of a tuple item, that may be different depending on memory alignment, I can detail the use case if necessary.
offsetof pseudo-method nowadays accept just instance variables as second argument, so, my suggestion is to extend this and in case of Tuples, accept a Int, to get the offset of the nth item in the tuple.
Similar thing can be done for NamedTuple as well, accepting a symbol or a stringliteral.
Is this feasible? Is there already a way to get the offset of a tuple item and I don’t know?
For NamedTuples I guess there might be some details regarding permutations of keys. A named tuple of type {a: Int32, b: String} can be used as a {b: String, a: Int32}. Either there is a cannonical representation or the compiler converts one to the other (I don’t recall). In the later escenario the offsets will not work, but the type restrictions might not complain.
Regarding the implementation places, yeah. It seems right.
If you need tuples I would say to start with those.
I was writing a paged GapBuffer implementation as a experimentation to measure the work needed to write a text-editor widget for GTK that can load huge files (50M-100M, i.e. log files) very fast.
Then I was trying to avoid the memory copy at maximum and read the files in chunks of 8Kb on demand. So to avoid the overhead of string copying I did a non-safe hack to be able to create String objects that doesn’t copy the memory, the ugly hack is this:
It still have the overhead of the malloc few bytes… and to_unsafe wont return a \0 ended string, but at least I can use all string methods and pass this pieces of strings to any place in stdlib that expects a string.
The hack works because by what I remember 255 isn’t a valid UTF-8 byte… I would store this info a the space we still have in String object due to memory alignment, but I remember to see some branch that used this extra space for something, so this way the hack is more safe for future internal changes of String object.
So instead of that 4 you would use offsetof? But in this case the tuple was known to you, so using a hardcoded value is fine. Or just sizeof(Int32).
I don’t think we need to change the language or introduce this change for just this, specially since this is just an experiment. I can’t imagine any use case for this. In fact, this example isn’t a valid use case for this for me.
The reason is: this makes the language more complex but it’s probably not worth it.
But alignment can change from platform to platform, otherwise the offsetof wouldn’t exist, since people can always just to a sum with sizeof expressions…