Search code examples
d

Cannot use parallel on a char array?


I have tried this both on the online tour of D and with ldc locally. This Error puzzles me. What is so special about char compared to int so that it cannot be made a ref from parallel?

import std.stdio : writeln;
import std.parallelism;

void main()
{
    auto arr = [1,2,3,4,5,6,7,8];
    foreach(ref i; parallel(arr)) {
        //writeln(typeid(i));
        i = i*i;
    }
    
    writeln(arr);
    
    auto result = [ 'w','e','l','c','o','m','e','t','o','d'];
    //foreach( ref c; parallel(result)) --> Error: foreach: cannot make c ref
    foreach( ref c; result)
    {
        //writeln(typeid(c));
        c = 'a';
    }
    writeln(result);
    
    writeln(typeid(arr));
    writeln(typeid(result));
}

Solution

  • char is somewhat of a partial type - it represents a piece of a unicode character, not a whole character. Consider the Chinese character 维 - its representation in memory is E7 BB B4, or an array of three chars. Because of this, D does not let you operate on char the same way you would other types.

    D does not have a separate type for ASCII text, so if you want to treat a string as ASCII, you should use ubyte[] instead of char[].