isRandomAccessRange

Returns true if R is a random-access range. A random-access range is a bidirectional range that also offers the primitive opIndex, OR an infinite forward range that offers opIndex. In either case, the range must either offer length or be infinite. The following code should compile for any random-access range.

The semantics of a random-access range (not checkable during compilation) are assumed to be the following (r is an object of type R):

  • r.opIndex(n) returns a reference to the nth element in the range.

Although char[] and wchar[] (as well as their qualified versions including string and wstring) are arrays, isRandomAccessRange yields false for them because they use variable-length encodings (UTF-8 and UTF-16 respectively). These types are bidirectional ranges only.

  1. enum bool isRandomAccessRange(R);
    enum bool isRandomAccessRange(R);
  2. enum bool isRandomAccessRange(R, E);
  3. import std.traits;
  4. enum bool isInputRange(R, E);

Return Value

true if R is a random-access range (possibly with element type E), false if not

Examples

import std.traits : isAggregateType, isAutodecodableString;

alias R = int[];

// range is finite and bidirectional or infinite and forward.
static assert(isBidirectionalRange!R ||
              isForwardRange!R && isInfinite!R);

R r = [0,1];
auto e = r[1]; // can index
auto f = r.front;
static assert(is(typeof(e) == typeof(f))); // same type for indexed and front
static assert(!(isAutodecodableString!R && !isAggregateType!R)); // narrow strings cannot be indexed as ranges
static assert(hasLength!R || isInfinite!R); // must have length or be infinite

// $ must work as it does with arrays if opIndex works with $
static if (is(typeof(r[$])))
{
    static assert(is(typeof(f) == typeof(r[$])));

    // $ - 1 doesn't make sense with infinite ranges but needs to work
    // with finite ones.
    static if (!isInfinite!R)
        static assert(is(typeof(f) == typeof(r[$ - 1])));
}

// Checking the element type
static assert( isRandomAccessRange!(int[], const int));
static assert(!isRandomAccessRange!(int[], immutable int));

static assert(!isRandomAccessRange!(const(int)[], int));
static assert( isRandomAccessRange!(const(int)[], const int));
static assert(!isRandomAccessRange!(const(int)[], immutable int));

static assert(!isRandomAccessRange!(immutable(int)[], int));
static assert( isRandomAccessRange!(immutable(int)[], const int));
static assert( isRandomAccessRange!(immutable(int)[], immutable int));

See Also

The header of std.range for tutorials on ranges.

Meta