Skip to content

NEP20 Indexing Exceptions

Greg Hewgill edited this page Oct 27, 2020 · 2 revisions

This proposal eliminates most uses of StringIndexException and BytesIndexException, and makes indexing behaviour consistent across types.

Motivation

The current rules around when a StringIndexException is raised are rather restrictive. For example, here are some selected behaviours:

CONSTANT s: String := "abc"

TESTCASE s[0 TO 2] = "abc"
TESTCASE s[0 TO 3] EXPECT StringIndexException

TESTCASE s[2 TO 2] = "c"
TESTCASE s[3 TO 2] EXPECT StringIndexException

These sorts of boundary conditions where a StringIndexException is raised are inconvenient to work with. For example, there almost always has to be a check against a string .length() before indexing, to ensure that an exception is not raised.

Proposal

For the String, Bytes, and Array types, the following rules will hold:

  • Non-integer indexes raise an exception.
  • Indexing a single specific element causes a bounds check against the bounds of the container, raising an exception when out of bounds.
  • Indexing a range ([first TO last]) returns as much of the elements of the container as the range requests, with no exceptions for out of bounds access.

So from the example above:

TESTCASE s[0 TO 2] = "abc"
TESTCASE s[0 TO 3] = "abc" -- Four characters requested, but only three available

TESTCASE s[2 TO 2] = "c"
TESTCASE s[3 TO 2] = "" -- Index endpoints do not form a valid index range

Similarly, indexing a string like s[4] where the index is beyond the range of valid characters in the string, would raise an exception.