Do strings support indexing, or not?

Sentinel Language - Values | Sentinel by HashiCorp :

Strings support indexing. Indexing a string will access that byte in the string as if the string were a byte array. This is an important distinction: it will not access the character at that position if you’re using multi-byte characters.

Sentinel Playground :

myfunc = func() {
  value = "foo"
  print(value[0])
  return true
}

main = rule {
    myfunc()
}

policy.sentinel:3:9: only a list or map can be indexed, got string

Hey @maxb! Thank you so much for raising the issue. Strangely, the documentation and implementation seem well out of sync here. Strings have support for Slice Expressions, but support for Index Expressions seems to not be implemented.

We will have this implemented shortly and it will be included in the next Sentinel release. I am so sorry for the confusion!

Thanks,

Cameron

Hello again @maxb!

I’ve been doing some investigation into this and there are a few potential challenges with implementing string indexing precisely as the spec defines. For example, Sentinel currently has no byte type, and so will have difficulty in handling the return type.

Additionally, if we were to have indexing of a string return the character at the index, we have the issue of handling multi-byte characters and what we should return.

For now, I am going to remove the mention of string indexing from the spec and update with an alternative approach via the strings import. By using strings.split, with an empty sep parameter, it will split on each UTF-8 sequence. As split returns a list, we can easily index on it.

https://play.sentinelproject.io/p/OQiLV5CHu85

Thanks again for raising this.

Thank you for your very prompt responses.

I agree with you that it would be inappropriate to implement string indexing in exactly the way the spec currently documents, as it is inconsistent with the rest of the Sentinel language, which is string, not binary data, focussed.

I am happy the documentation will be corrected.

1 Like