| 1 |
@safe unittest |
| 2 |
{ |
| 3 |
import std.internal.cstring; |
| 4 |
|
| 5 |
version (Posix) |
| 6 |
{ |
| 7 |
import core.stdc.stdlib : free; |
| 8 |
import core.sys.posix.stdlib : setenv; |
| 9 |
import std.exception : enforce; |
| 10 |
|
| 11 |
void setEnvironment(scope const(char)[] name, scope const(char)[] value) |
| 12 |
{ enforce(setenv(name.tempCString(), value.tempCString(), 1) != -1); } |
| 13 |
} |
| 14 |
|
| 15 |
version (Windows) |
| 16 |
{ |
| 17 |
import core.sys.windows.winbase : SetEnvironmentVariableW; |
| 18 |
import std.exception : enforce; |
| 19 |
|
| 20 |
void setEnvironment(scope const(char)[] name, scope const(char)[] value) |
| 21 |
{ enforce(SetEnvironmentVariableW(name.tempCStringW(), value.tempCStringW())); } |
| 22 |
} |
| 23 |
} |
| 24 |
|
| 25 |
nothrow @nogc @system unittest |
| 26 |
{ |
| 27 |
import std.internal.cstring; |
| 28 |
|
| 29 |
import core.stdc.string; |
| 30 |
|
| 31 |
string str = "abc"; |
| 32 |
|
| 33 |
// Intended usage |
| 34 |
assert(strlen(str.tempCString()) == 3); |
| 35 |
|
| 36 |
// Correct usage |
| 37 |
auto tmp = str.tempCString(); |
| 38 |
assert(strlen(tmp) == 3); // or `tmp.ptr`, or `tmp.buffPtr` |
| 39 |
|
| 40 |
// $(RED WARNING): $(RED Incorrect usage) |
| 41 |
auto pInvalid1 = str.tempCString().ptr; |
| 42 |
const char* pInvalid2 = str.tempCString(); |
| 43 |
// Both pointers refer to invalid memory here as |
| 44 |
// returned values aren't assigned to a variable and |
| 45 |
// both primary expressions are ended. |
| 46 |
} |
| 47 |
|