Refactor data reading

This commit is contained in:
Les De Ridder 2019-02-23 06:04:31 +01:00
parent 6e7136aaea
commit 1b83e18cc4
2 changed files with 61 additions and 52 deletions

View File

@ -1,6 +1,5 @@
module cm3d2.menu;
import std.bitmanip;
import std.conv;
import std.math;
import std.array;
@ -8,6 +7,8 @@ import std.range;
import sdlang;
import cm3d2.util;
class Menu
{
private static string[string] _translations;
@ -38,65 +39,23 @@ class Menu
{
auto menu = new Menu();
ubyte readByte()
{
auto value = data[0];
data = data[1 .. $];
return value;
}
assert(data.readString() == "CM3D2_MENU", "Not a valid .menu file");
string readString()
{
auto length = 0;
ubyte[] chars;
menu.fileVersion = data.readInt();
menu.path = data.readString();
menu.name = data.readString();
menu.category = data.readString();
menu.description = data.readString();
while (true)
{
auto lengthByte = readByte();
if (length != 0 && lengthByte < 128)
{
break;
}
length = length << 8 | lengthByte;
if (lengthByte < 128)
{
break;
}
}
auto value = cast(string) data[0 .. length];
data = data[length .. $];
return value;
}
uint readInt()
{
auto value = littleEndianToNative!uint(data[0 .. 4]);
data = data[4 .. $];
return value;
}
assert(readString() == "CM3D2_MENU", "Not a valid .menu file");
menu.fileVersion = readInt();
menu.path = readString();
menu.name = readString();
menu.category = readString();
menu.description = readString();
assert(readInt() == data.length, "Unexpected data at end of file");
assert(data.readInt() == data.length, "Unexpected data at end of file");
while(data.length > 0)
{
string[] line;
foreach (_; 0 .. readByte())
foreach (_; 0 .. data.readByte())
{
line ~= readString();
line ~= data.readString();
}
if (line.length > 0)

50
source/cm3d2/util.d Normal file
View File

@ -0,0 +1,50 @@
module cm3d2.util;
import std.bitmanip;
import std.range;
import std.traits;
ubyte readByte(Range)(ref Range data)
if (isRandomAccessRange!(Unqual!(Range)) && is(ElementType!Range == ubyte) && hasSlicing!Range)
{
auto value = data[0];
data = data[1 .. $];
return value;
}
string readString(Range)(ref Range data)
if (isRandomAccessRange!(Unqual!(Range)) && is(ElementType!Range == ubyte) && hasSlicing!Range)
{
auto length = 0;
ubyte[] chars;
while (true)
{
auto lengthByte = data.readByte();
if (length != 0 && lengthByte < 128)
{
break;
}
length = length << 8 | lengthByte;
if (lengthByte < 128)
{
break;
}
}
auto value = cast(string) data[0 .. length];
data = data[length .. $];
return value;
}
uint readInt(Range)(ref Range data)
if (isRandomAccessRange!(Unqual!(Range)) && is(ElementType!Range == ubyte) && hasSlicing!Range)
{
auto value = littleEndianToNative!uint(data[0 .. 4]);
data = data[4 .. $];
return value;
}