aboutsummaryrefslogtreecommitdiff
path: root/src/io/input.c
blob: 3dcca00b2ba7832289a0ac9be30381d4b0792731 (plain)
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
/*
 * ecgen, tool for generating Elliptic curve domain parameters
 * Copyright (C) 2017 J08nY
 */
#include <parson/parson.h>
#include "input.h"

FILE *in;

GEN fread_i(FILE *stream, const char *prompt, long bits, int delim) {
	if (prompt) {
		printf("%s ", prompt);
	}
	char *line = NULL;
	size_t n = 0;

	ssize_t len = getdelim(&line, &n, delim, stream);
	if (len == 1) {
		free(line);
		return gen_m1;
	}
	pari_sp ltop = avma;
	GEN in = strtoi(line);
	free(line);

	// check bitsize here
	GEN size = int2n(bits);
	if (cmpii(in, size)) {
		return gerepileupto(ltop, in);
	} else {
		fprintf(stderr, "Number too big(> %ld bits).\n", bits);
		return gen_m1;
	}
}

GEN fread_prime(FILE *stream, const char *prompt, long bits, int delim) {
	GEN read = fread_i(stream, prompt, bits, delim);
	if (equalii(read, gen_m1)) {
		return read;
	} else {
		if (isprime(read)) {
			return read;
		} else {
			fprintf(stderr, "Number is not prime. Prime required.\n");
			return gen_m1;
		}
	}
}

GEN fread_int(FILE *stream, const char *prompt, long bits, int delim) {
	return fread_i(stream, prompt, bits, delim);
}

GEN fread_short(FILE *stream, const char *prompt, int delim) {
	return fread_i(stream, prompt, 16, delim);
}

GEN fread_string(FILE *stream, const char *prompt, int delim) {
	if (prompt) {
		printf("%s ", prompt);
	}
	char *line = NULL;
	size_t n = 0;

	ssize_t len = getdelim(&line, &n, delim, stream);
	if (len == 1) {
		free(line);
		return strtoGENstr("");
	}

	line[len - 1] = 0;
	GEN result = strtoGENstr(line);
	free(line);
	return result;
}

GEN fread_param(param_t param, FILE *stream, const char *prompt, long bits,
				int delim) {
	switch (param) {
		case PARAM_PRIME:
			return fread_prime(stream, prompt, bits, delim);
		case PARAM_INT:
			return fread_int(stream, prompt, bits, delim);
		case PARAM_SHORT:
			return fread_short(stream, prompt, delim);
		case PARAM_STRING:
			return fread_string(stream, prompt, delim);
	}
	return gen_m1;
}

GEN read_param(param_t param, const char *prompt, long bits, int delim) {
	return fread_param(param, stdin, prompt, bits, delim);
}

FILE *input_open(const char *input) {
	json_set_allocation_functions(pari_malloc, pari_free);
	if (input) {
		FILE *in = fopen(input, "r");
		if (!in) {
			// fallback to stdin or quit?
			in = stdin;
			perror("Failed to open input file.");
		}
		return in;
	} else {
		return stdin;
	}
}

void input_close(FILE *in) {
	if (in != NULL && in != stdout) {
		fclose(in);
	}
}