medfall

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs

int_conversions.lua (1376B)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#! /usr/bin/lua

local s = { "s64", "s32", "s16", "s8" }
local u = { "u64", "u32", "u16", "u8" }

local function printf( form, ... )
	print( form:format( ... ) )
end

local function codes( t )
	printf(
		"template< typename T >\n" ..
		"%s check_%s( T x ) {\n" ..
			"\tif( IS_SIGNED( T ) ) assert( x >= %s_MIN );\n" ..
			"\tassert( x <= %s_MAX );\n" ..
			"\treturn ( %s ) x;\n" ..
		"}\n" ..
		"\n" ..
		"template< typename T >\n" ..
		"%s check_%s( T x ) {\n" ..
			"#pragma GCC diagnostic push // GCC warns even though the optimiser removes the branch\n" ..
			"#pragma GCC diagnostic ignored \"-Wsign-compare\"\n" ..
			"\tif( IS_SIGNED( T ) ) assert( x >= %s_MIN );\n" ..
			"#pragma GCC diagnostic pop\n" ..
			"\tassert( x <= %s_MAX );\n" ..
			"\treturn ( %s ) x;\n" ..
		"}",
		t, t, t:upper(), t:upper(), t,
		t, t, t:upper(), t:upper(), t )
end

local function codeu( t )
	printf(
		"template< typename T >\n" ..
		"%s check_%s( T x ) {\n" ..
			"\tassert( x >= 0 && x <= %s_MAX );\n" ..
			"\treturn ( %s ) x;\n" ..
		"}\n" ..
		"\n" ..
		"template< typename T >\n" ..
		"%s clamp_%s( T x ) {\n" ..
			"\tif( x < 0 ) return 0;\n" ..
			"\tif( x > %s_MAX ) return %s_MAX;\n" ..
			"\treturn ( %s ) x;\n" ..
		"}\n",
		t, t, t:upper(), t,
		t, t, t:upper(), t:upper(), t )
end

for _, t in ipairs( s ) do
	codes( t )
end
for _, t in ipairs( u ) do
	codeu( t )
end