cybersecurity · beginner · ~20 min
Per-byte allow-list encoding — the RFC 3986 unreserved set.
Implement int url_encode(const char *in, char *out, int cap).
For each byte of in:
[A-Za-z0-9-._~] (the RFC 3986 'unreserved' set), copy as-is.%XX where XX is the byte's value in
uppercase hex.NUL-terminate out. Return the bytes written (excluding NUL), or -1 if
the result wouldn't fit in cap.
Every byte that crosses an HTTP URL boundary must be %XX-encoded if it's not in the safe set. Doing it correctly is the most basic step in any URL builder.
String + output buffer + cap.
Encoded length or -1.
Uppercase hex; the unreserved set ONLY.
int url_encode(const char *in, char *out, int cap) { /* TODO */ (void)in; (void)out; (void)cap; return -1; }
Encoding ~ (it's in the safe set). Lowercase hex (some validators reject).
Empty input. All-safe input. All-unsafe input. cap=0.
O(n).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.