summaryrefslogtreecommitdiffstats
path: root/lib/tc.c
blob: 2e45add843d06ea9b43eb86ae4af90b6bef9ffc1 (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
// SPDX-License-Identifier: GPL-2.0-or-later
/*
 * Traffic Control (TC) main library
 * Copyright (C) 2022  Shichu Yang
 */

#include "tc.h"

int tc_getrate(const char *str, uint64_t *rate)
{
	char *endp;
	uint64_t raw = strtoull(str, &endp, 10);

	if (endp == str)
		return -1;

	/* if the string only contains a number, it must be valid rate (bps) */
	bool valid = (*endp == '\0');

	const char *p = endp;
	bool bytes = false, binary_base = false;
	int power = 0;

	while (*p) {
		if (strcmp(p, "Bps") == 0) {
			bytes = true;
			valid = true;
			break;
		} else if (strcmp(p, "bit") == 0) {
			valid = true;
			break;
		}
		switch (*p) {
		case 'k':
		case 'K':
			power = 1;
			break;
		case 'm':
		case 'M':
			power = 2;
			break;
		case 'g':
		case 'G':
			power = 3;
			break;
		case 't':
		case 'T':
			power = 4;
			break;
		case 'i':
		case 'I':
			if (power != 0)
				binary_base = true;
			else
				return -1;
			break;
		default:
			return -1;
		}
		p++;
	}

	if (!valid)
		return -1;

	for (int i = 0; i < power; i++)
		raw *= binary_base ? 1024ULL : 1000ULL;

	if (bytes)
		*rate = raw;
	else
		*rate = raw / 8ULL;

	return 0;
}