Skip to content

Commit 5bd2d3a

Browse files
committed
Collection summation overflow checks!
1 parent 4830b44 commit 5bd2d3a

File tree

6 files changed

+619
-106
lines changed

6 files changed

+619
-106
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
HEADER = '''
2+
@file:OptIn(ExperimentalTypeInference::class)
3+
@file:Suppress("NOTHING_TO_INLINE", "unused")
4+
5+
package com.sschr15.aoc.annotations
6+
7+
import kotlin.experimental.ExperimentalTypeInference
8+
'''.strip()
9+
10+
FUNCTION_BODY = '''
11+
var sum = 0%s
12+
for (item in items) {
13+
sum = Math.addExact(sum, %s.to%s())
14+
}
15+
return sum
16+
'''.strip('\n')
17+
18+
TYPED_COLLECTIONS = [
19+
'Iterable', 'Sequence', 'Array'
20+
]
21+
22+
PRIMITIVES = [
23+
'Byte', 'Short', 'Int', 'Long'
24+
]
25+
26+
def generate(collection: str, name: str, sum_type: str, generic: bool = False, alt: str | None = None, second_param: str | None = None) -> str:
27+
output = [
28+
'@OverloadResolutionByLambdaReturnType' if second_param else None,
29+
f'@JvmName("{alt}")' if alt else None,
30+
f'inline fun {"<T> " if generic else ""}{name}(items: {collection}{f", transform: {second_param}" if second_param else ""}): {sum_type} {"{"}',
31+
FUNCTION_BODY % ('L' if sum_type == 'Long' else '', 'transform(item)' if second_param else 'item', sum_type),
32+
'}',
33+
]
34+
return '\n'.join([i for i in output if i is not None])
35+
36+
def get_sum_type(typ: str):
37+
return 'Long' if typ == 'Long' else 'Int'
38+
39+
if __name__ == '__main__':
40+
declarations = []
41+
42+
for prim in PRIMITIVES:
43+
for typ in TYPED_COLLECTIONS:
44+
declarations.append(generate(f'{typ}<{prim}>', 'sum', get_sum_type(prim), alt=f'sumOf{prim}s'))
45+
46+
declarations.append(generate(f'{prim}Array', 'sum', get_sum_type(prim)))
47+
48+
for p2 in PRIMITIVES:
49+
declarations.append(generate(f'{prim}Array', 'sumOf', get_sum_type(p2), alt=f'sumOf{prim}sTo{p2}s', second_param=f'({prim}) -> {p2}'))
50+
51+
declarations.append(generate('CharArray', 'sumOf', get_sum_type(prim), alt=f'sumOfCharsTo{prim}s', second_param=f'(Char) -> {prim}'))
52+
53+
for typ in TYPED_COLLECTIONS:
54+
for prim in PRIMITIVES:
55+
declarations.append(generate(f'{typ}<T>', 'sumOf', get_sum_type(prim), generic=True, alt=f'sumTo{prim}s', second_param=f'(T) -> {prim}'))
56+
57+
output_file = [
58+
HEADER,
59+
*declarations,
60+
]
61+
62+
with open('src/main/kotlin/CollectionOverflowChecks.kt', 'wb') as file:
63+
file.write('\n\n'.join(output_file).encode())

0 commit comments

Comments
 (0)