Bug 13796 – A simple "array head const" struct for Phobos

Status
RESOLVED
Resolution
FIXED
Severity
enhancement
Priority
P1
Component
phobos
Product
D
Version
D2
Platform
x86
OS
Windows
Creation time
2014-11-29T13:25:00Z
Last change time
2016-10-01T11:47:05Z
Assigned to
nobody
Creator
bearophile_hugs

Comments

Comment #0 by bearophile_hugs — 2014-11-29T13:25:44Z
In D code it's a good idea to set as const/immutable (where possible) all variables that don't need to change, for both safety and compiler-enforced code documentation. In my D functions sometimes I create dynamic arrays that later don't have to change length nor to be reassigned, but I have to mutate or assign their items. So their length and ptr can be const/immutable, unlike the array contents. The D type system doesn't allow this. So is it a good idea to try to add to Phobos a arrayHeadConst function similar to this (only for built-in dynamic arrays) that tries to enforce those constraints? import std.traits, std.range; struct ArrayHeadConst(T) { T[] data; alias data this; @property size_t length() const pure nothrow @safe @nogc { return data.length; } @disable void opAssign(); } ArrayHeadConst!(ElementType!R) arrayHeadConst(R)(R arr) if (isDynamicArray!R) { return typeof(return)(arr); } void main() { import std.stdio; auto arr = new int[2].arrayHeadConst; arr[1] = 10; arr[1].writeln; arr.length.writeln; //arr.length = arr.length + 1; // error auto b = new int[2]; //arr = b; // error arr[] = b[]; b = arr; arr[] = 1; ArrayHeadConst!int c = arr; ArrayHeadConst!int d; arr = d; // fail }
Comment #1 by github-bugzilla — 2016-08-29T16:34:37Z
Commit pushed to master at https://github.com/dlang/phobos https://github.com/dlang/phobos/commit/415d573a3c8688396f0f46643bd1fedc923620dc Add std.experimental.typecons.HeadConst - fix issue 13796
Comment #2 by github-bugzilla — 2016-10-01T11:47:05Z
Commit pushed to stable at https://github.com/dlang/phobos https://github.com/dlang/phobos/commit/415d573a3c8688396f0f46643bd1fedc923620dc Add std.experimental.typecons.HeadConst - fix issue 13796