solve/length.rs
1//! Code length measurement and its logarithmic score.
2
3use crate::score::Score;
4
5/// Divisor applied before the base-2 logarithm, per the specification.
6const PIVOT: f64 = 500.0;
7
8/// How much code the solver has to read, in the specification's units.
9///
10/// Non-assembly source is counted in `cl100k_base` tokens; assembly is counted in lines of
11/// disassembly plus lines of `.rodata`. Token counting is left to the caller so the crate
12/// stays dependency-free — produce it with `tiktoken` and pass [`CodeLength::Tokens`].
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
15#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
16pub enum CodeLength {
17 /// `len(tiktoken.get_encoding("cl100k_base").encode(file_data))`, summed over relevant files.
18 Tokens(u64),
19 /// `objdump -d | wc -l` plus `objdump -s -j .rodata | wc -l`.
20 Assembly {
21 /// Lines of disassembled instructions.
22 instructions: u64,
23 /// Lines of the `.rodata` dump.
24 rodata_lines: u64,
25 },
26 /// A pre-summed unit count, for mixing source and binary across a challenge.
27 Units(u64),
28}
29
30impl CodeLength {
31 /// The total unit count this measurement represents.
32 #[must_use]
33 pub const fn units(self) -> u64 {
34 match self {
35 Self::Tokens(n) | Self::Units(n) => n,
36 Self::Assembly {
37 instructions,
38 rodata_lines,
39 } => instructions + rodata_lines,
40 }
41 }
42
43 /// `round1(clamp(log2(units / 500), 0, 10))`.
44 ///
45 /// Anything at or below 500 units scores zero; the scale saturates at `512_000` units.
46 #[must_use]
47 pub fn score(self) -> Score {
48 let units = self.units();
49 if units == 0 {
50 return Score::ZERO;
51 }
52 #[allow(clippy::cast_precision_loss)]
53 let ratio = units as f64 / PIVOT;
54 Score::clamped(ratio.log2()).rounded()
55 }
56}