Elixir string slice method traverses the whole string when given negative range - why?

When going through the hexdocs for slice/2 method on string module, its explained that when the range is given as negative numbers then the whole string has to be traversed to establish the positive equivalent of the negative range.
Why does elixir have to traverse the whole string?

1 Like

Because strings in Elixir are encoded in UTF-8, in UTF-8 each character can have a width between 1 and 4 byte. So the String has to be traversed fully, to know that we a) have an valid string until the split-point and b) the number of bytes that represent your number of characters.

4 Likes

I think the question was “why does Elixir traverse the entire string when given a range using negative offsets (n characters from the end of the string)”. Indeed, the characters between the start of the string and the end of the range must be traversed for the reasons you stated. In addition, if negative indices are used for the range, the whole string must be traversed so that we know how to count n characters from the end of the string.

However, the source for this function indicates that the entire string is traversed anyway, even if only positive indices are used.

1 Like