slovo/benchmarks/json-quote-loop/python/json_quote_loop.py

54 lines
1.0 KiB
Python

import sys
LOOP_COUNT = 1_000_000
EXPECTED_CHECKSUM = 15_000_001
def configured_loop_count() -> int:
try:
value = int(input().strip())
except (EOFError, ValueError):
return LOOP_COUNT
return value if value > 0 else LOOP_COUNT
def configured_target() -> str:
return sys.argv[1] if len(sys.argv) > 1 else 'slo"vo\\path'
def quote_json_string(value: str) -> str:
return (
'"'
+ value.replace("\\", "\\\\")
.replace('"', '\\"')
.replace("\n", "\\n")
.replace("\t", "\\t")
.replace("\r", "\\r")
.replace("\b", "\\b")
.replace("\f", "\\f")
+ '"'
)
def json_quote_loop(limit: int, target: str) -> int:
i = 0
acc = 1
while i < limit:
acc += len(quote_json_string(target))
i += 1
return acc
def main() -> int:
result = json_quote_loop(configured_loop_count(), configured_target())
print(result)
return 0 if result == EXPECTED_CHECKSUM else 1
if __name__ == "__main__":
raise SystemExit(main())