WIP FPC-III support
[linux/fpc-iii.git] / tools / testing / selftests / kvm / lib / test_util.c
blob8e04c0b1608e65aaa55fe8c5ce8db4d486b302ed
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * tools/testing/selftests/kvm/lib/test_util.c
5 * Copyright (C) 2020, Google LLC.
6 */
8 #include <assert.h>
9 #include <ctype.h>
10 #include <limits.h>
11 #include <stdlib.h>
12 #include <time.h>
14 #include "test_util.h"
17 * Parses "[0-9]+[kmgt]?".
19 size_t parse_size(const char *size)
21 size_t base;
22 char *scale;
23 int shift = 0;
25 TEST_ASSERT(size && isdigit(size[0]), "Need at least one digit in '%s'", size);
27 base = strtoull(size, &scale, 0);
29 TEST_ASSERT(base != ULLONG_MAX, "Overflow parsing size!");
31 switch (tolower(*scale)) {
32 case 't':
33 shift = 40;
34 break;
35 case 'g':
36 shift = 30;
37 break;
38 case 'm':
39 shift = 20;
40 break;
41 case 'k':
42 shift = 10;
43 break;
44 case 'b':
45 case '\0':
46 shift = 0;
47 break;
48 default:
49 TEST_ASSERT(false, "Unknown size letter %c", *scale);
52 TEST_ASSERT((base << shift) >> shift == base, "Overflow scaling size!");
54 return base << shift;
57 int64_t timespec_to_ns(struct timespec ts)
59 return (int64_t)ts.tv_nsec + 1000000000LL * (int64_t)ts.tv_sec;
62 struct timespec timespec_add_ns(struct timespec ts, int64_t ns)
64 struct timespec res;
66 res.tv_nsec = ts.tv_nsec + ns;
67 res.tv_sec = ts.tv_sec + res.tv_nsec / 1000000000LL;
68 res.tv_nsec %= 1000000000LL;
70 return res;
73 struct timespec timespec_add(struct timespec ts1, struct timespec ts2)
75 int64_t ns1 = timespec_to_ns(ts1);
76 int64_t ns2 = timespec_to_ns(ts2);
77 return timespec_add_ns((struct timespec){0}, ns1 + ns2);
80 struct timespec timespec_sub(struct timespec ts1, struct timespec ts2)
82 int64_t ns1 = timespec_to_ns(ts1);
83 int64_t ns2 = timespec_to_ns(ts2);
84 return timespec_add_ns((struct timespec){0}, ns1 - ns2);
87 struct timespec timespec_diff_now(struct timespec start)
89 struct timespec end;
91 clock_gettime(CLOCK_MONOTONIC, &end);
92 return timespec_sub(end, start);
95 struct timespec timespec_div(struct timespec ts, int divisor)
97 int64_t ns = timespec_to_ns(ts) / divisor;
99 return timespec_add_ns((struct timespec){0}, ns);
102 void print_skip(const char *fmt, ...)
104 va_list ap;
106 assert(fmt);
107 va_start(ap, fmt);
108 vprintf(fmt, ap);
109 va_end(ap);
110 puts(", skipping test");