Last active
May 2, 2020 20:26
-
-
Save ikod/2c35851581b59677a0d9511812592df0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import std.stdio; | |
import std.algorithm; | |
import std.string; | |
import nbuff; | |
void main() @safe | |
{ | |
string someData = "abc"; | |
MutableNbuffChunk mutBuff = Nbuff.get(64); | |
() @trusted { | |
// you can access MutableChunkData only in @system or @trusted code | |
copy(someData, mutBuff.data); | |
assert(mutBuff.data[0..3] == someData); | |
}(); | |
// auto v = mutBuff.data; // <- fails: can't access in @safe code | |
MutableNbuffChunk mutBuff2; | |
// mutBuff2 = mutBuff; // <- fails: you can't have several pointers to mutable data | |
// But you can convert mutable buffer to immutable (and consume its data) | |
NbuffChunk buff0 = NbuffChunk(mutBuff, someData.length); | |
// assert(mutBuff.empty); // fails at runtime with sigsegv as mutBuff is null now | |
// you can have several views on immutable data | |
NbuffChunk buff1 = buff0[1..$]; | |
// and can apply algorithms to content, but again in trusted code | |
() @trusted | |
{ | |
assert(buff0.data.canFind('a')); | |
assert(!buff1.data.canFind('a')); | |
}(); | |
// you can't mutate immutable data | |
// buff0[0] = 'b'; // <- fails to compile | |
// buff0.data[0] = 'b'; // <- fails to compile | |
// but you can still do illegal thisngs with lifetimes like this | |
immutable(ubyte)[] v; | |
() @trusted | |
{ | |
v = buff0.data; | |
}(); | |
assert(v[0] == 'a'); // v is dangling now | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment