Voldemort toHexString Compile Error
Salih Dincer
salihdb at hotmail.com
Mon Mar 18 03:52:51 UTC 2024
On Sunday, 17 March 2024 at 13:08:14 UTC, Richard (Rikki) Andrew
Cattermole wrote:
> It is because Hex is nested, it has an outer pointer to the
> call frame of toHexString.
>
> Make Hex static, and it works.
Thank you for your contributions. It's great to develop something
with you. So is having such a forum. Thanks everyone, here is the
new version:
```d
auto toHexRange(T)(const char[] str)
{
static struct HexRange {
int i;
auto nibbleSplit() {
auto MSB = i >> 4;
auto LSB = i & 15;
return [MSB, LSB];
}
}
import std.utf : byCodeUnit;
import std.algorithm : map;
import std.range : join;
return str.byCodeUnit.map!HexRange
.map!(e => e.nibbleSplit).join
.map!(n => n += n > 9 ? '7' : '0')
.map!(c => c.to!T);
}
auto toHex(T)(const char[] str)
{
static if(is(T : string))
{
import std.algorithm : copy;
auto result = new char[str.length * 2];
str.toHexRange!char.copy(result);
return cast(string)result;
} else {
import std.array;
return str.toHexRange!T.array;
}
}
unittest
{
enum Expected = "61626320C3A4C3B6C3BC50C39FE282AC207B447D";
enum str = "abc äöüP߀ {D}";
assert(str.toHex!string == Expected);
import std.conv : hexString;
static assert(hexString!Expected == str);
enum NATO {
Alpha = '0', Bravo, Charlie, Delta, Echo,
Foxtrot, Golf, Hotel, India, Juliett,
Kilo = 'A', Lima, Mike, November, Oscar, Papa
}
auto test = str.toHex!NATO;
assert(is(typeof(test) : NATO[]));
}
```
SDB at 79
More information about the Digitalmars-d
mailing list