aboutsummaryrefslogtreecommitdiffhomepage
path: root/pyecsca/codegen/templates/ops.c
blob: 30a762216d2a4fcb2a7a7bb5b03af5c181e6b7df (plain) (blame)
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
{% macro render_full_allocs(allocations, err_name="err") -%}
	{%- for alloc in allocations %}
		bn_t {{ alloc }};
	{%- endfor %}
	{{ err_name }} = bn_init_multi(&{{ allocations | join(", &") }}, NULL);
{%- endmacro %}

{% macro render_static_allocs(allocations) -%}
	{%- for alloc in allocations %}
		static bn_t {{ alloc }};
	{%- endfor %}
{%- endmacro %}

{% macro render_init_allocs(allocations, err_name="err") -%}
	{{err_name}} = bn_init_multi(&{{ allocations | join(", &") }}, NULL);
{%- endmacro %}

{% macro render_initializations(initializations) -%}
	{%- for init, (value, encode) in initializations.items() %}
		bn_from_int({{ value }}, &{{ init }});
		{%- if encode %}
		    bn_red_encode(&{{ init }}, &curve->p, &curve->p_red);
		{%- endif %}
	{%- endfor %}
{%- endmacro %}

{% macro render_ops(operations) -%}
	{%- for op, result, left, right in operations %}
		{{ render_op(op, result, left, right, "curve->p", "curve->p_red")}}
	{%- endfor %}
{%- endmacro %}

{% macro render_returns(returns) -%}
	{%- for src, dst in returns.items() %}
		bn_copy(&{{ src }}, &{{ dst }});
	{%- endfor %}
{%- endmacro %}

{% macro render_frees(frees) -%}
	{% if frees %}
		bn_clear_multi(&{{ frees | join(", &") }}, NULL);
	{%- endif %}
{%- endmacro %}

{% macro render_static_init(allocations, name) -%}
	{{ render_static_allocs(allocations) }}

	bool point_{{ name }}_init(void) {
		bn_err err;
		{{ render_init_allocs(allocations, "err") }}
		if (err != BN_OKAY) {
			return false;
		}
		return true;
	}
{%- endmacro %}

{% macro render_static_zero(allocations, name) -%}
	void point_{{ name }}_zero(void) {
		{%- for alloc in allocations -%}
		    bn_from_int(0, &{{alloc}});
		{%- endfor -%}
	}
{%- endmacro %}


{% macro render_static_clear(frees, name) -%}
	void point_{{ name }}_clear(void) {
		{{ render_frees(frees) }}
	}
{%- endmacro %}

{% macro render_all(allocations, initializations, operations, returns, frees, err_name="err") -%}
	bn_err {{err_name}};
	{{ render_full_allocs(allocations, err_name) }}
	{{ render_initializations(initializations) }}
	{{ render_ops(operations) }}
	{{ render_returns(returns) }}
	{{ render_frees(frees) }}
{%- endmacro %}