On Friday, 25 February 2022 at 05:23:22 UTC, Ali Çehreli wrote:
> SumType Güzel konu. Kendimiz yazmaya başlayarak öğreniriz.
Bir başka güzel konu (bence), geçen hafta yabancı forumda sorulan ve burda da irdelediğim std.bitmanip'deki read/write olayları ama daha çok bigEndian/littleEndian konusu:
Bir yerde yazıyor mu bilmiyorum, Union'lar Little Endian'ı dikkate alıyormuş. Bunu az önce denediğim aşağıdaki kodla anladım:
import std.system;
auto read(T, Endian E = Endian.littleEndian, R)
(R range) {
import bop = std.bitmanip;
return bop.read!(T, E)(range);
}
void write(T, Endian E = Endian.bigEndian, R)
(R range, T value, size_t index = 0) {
import bop = std.bitmanip;
bop.write!(T, E)(range, value, index);
}
struct rgb {
union Colors {
uint RGBA;
ubyte[4] bytes;
string toString() const {
import std.format;
return format("%X", RGBA);
}
}
Colors colors;
this(int r, int g, int b, int a = 0) {
this.colors.bytes[3] = cast(ubyte)r;
this.colors.bytes[2] = cast(ubyte)g;
this.colors.bytes[1] = cast(ubyte)b;
this.colors.bytes[0] = cast(ubyte)a;
}
auto opCast(T : uint)() {
return colors.bytes[].read!T;
}
string toString() const {
import std.format;
return format("#%02X%02X%02X",
this.colors.bytes[3],
this.colors.bytes[2],
this.colors.bytes[1]);
}
}
void main()
{
rgb[string] Colors = [
"LIGHTGRAY" : rgb( 200, 200, 200 ),
"GRAY" : rgb( 130, 130, 130 ),
"DARKGRAY" : rgb( 80, 80, 80 ),
"YELLOW" : rgb( 253, 249, 0 ),
"GOLD" : rgb( 255, 203, 0 ),
"ORANGE": rgb( 255, 161, 0 )
];
foreach(color; Colors.keys) {
auto c = Colors[color];
writef("%8X => ", cast(uint)c);
c.writeln(": ", color);
}
} unittest {
auto test = rgb(1, 2, 3);//
auto rgba = cast(uint)test; // 16909056
assert(rgba == test.colors.RGBA);
}
Belki bunu üzerinden size birşeyler anlatırım.
Sevgiler, saygılar...