# Subtask: Base62 Encoding/Decoding **Parent Task**: Decomp/001 **Subtask ID**: Decomp/001-02 **Dependencies**: None ## Description Implement Base62 encoding/decoding utility for converting numeric IDs to short codes and vice versa. This is a standalone utility with no external dependencies. ## Requirements - Convert integer ID → Base62 string (0-9, a-z, A-Z) - Convert Base62 string → integer ID - Support IDs up to 10M (fits within 6 characters) - No external libraries for core logic - Deterministic output (same input → same output) ## Technical Specifications **Algorithm**: Base62 encoding with custom alphabet ```python ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" BASE = 62 def encode(num: int) -> str: """Convert integer to Base62 string.""" if num == 0: return ALPHABET[0] result = [] while num > 0: num, remainder = divmod(num, BASE) result.append(ALPHABET[remainder]) return ''.join(reversed(result)) def decode(short_code: str) -> int: """Convert Base62 string to integer.""" num = 0 for char in short_code: num = num * BASE + ALPHABET.index(char) return num ``` **Data structures**: - String lookup for alphabet (O(1) char → value mapping) - Precomputed dictionary for reverse lookup optimization **API signatures**: ```python def encode_id(id: int) -> str: ... def decode_id(short_code: str) -> int: ... ``` **Error handling**: - `ValueError` for negative IDs - `ValueError` for invalid characters in short_code ## Acceptance Criteria - [ ] `encode_id(0)` returns `"0"` - [ ] `encode_id(12345)` returns deterministic 4-char string - [ ] `decode_id(encode_id(n)) == n` for 0 ≤ n ≤ 10M - [ ] 10M IDs encode to ≤6 characters (62^6 ≈ 56B > 10M) - [ ] Invalid characters raise `ValueError` - [ ] 100% test coverage for encode/decode roundtrip ## Notes **Trade-offs**: - Alphabet order (0-9, a-z, A-Z): optimized for URL readability - No leading zero removal: preserves exact ID mapping **Edge cases**: - ID = 0: return "0" (single character) - Very large IDs: test up to 62^8 for future-proofing **Alternatives considered**: - Base58 (Bitcoin-style): rejected, Base62 gives shorter codes for same ID - Base64: rejected, includes special chars (+/) not URL-friendly