i spent the last year just spinning

This commit is contained in:
Relism
2026-04-17 18:56:06 +02:00
parent 9efbe38c0c
commit e161497f2c
77 changed files with 2545 additions and 877 deletions
@@ -11,6 +11,8 @@ import java.nio.charset.StandardCharsets;
@Getter
public enum ContentType {
NONE (""),
// Text
TEXT_PLAIN ("text/plain"),
TEXT_HTML ("text/html"),
@@ -51,18 +51,22 @@ public enum HttpStatus {
private static final int MAX_STATUS_CODE = 504;
private static final byte[][] INDEX = new byte[MAX_STATUS_CODE + 1][];
private static final String[] REASONS = new String[MAX_STATUS_CODE + 1];
static {
for (HttpStatus s : values()) {
INDEX[s.code] = s.bytes;
REASONS[s.code] = s.reason;
}
}
private final int code;
private final String reason;
private final byte[] bytes;
HttpStatus(int code, String reason) {
this.code = code;
this.reason = reason;
this.bytes = (code + " " + reason).getBytes(StandardCharsets.UTF_8);
}
@@ -72,6 +76,9 @@ public enum HttpStatus {
/** Pre-encoded {@code "200 OK"} bytes — zero allocation on the write path. */
public byte[] bytes() { return bytes; }
/** Reason phrase (e.g. {@code "OK"}). */
public String reason() { return reason; }
/**
* Returns pre-compiled status bytes for the given code.
* Access is O(1) and generates zero garbage.
@@ -82,4 +89,12 @@ public enum HttpStatus {
}
return null;
}
}
/** Returns reason phrase for the given code, or null if unknown. */
public static String reasonForCode(int code) {
if (code >= 0 && code <= MAX_STATUS_CODE) {
return REASONS[code];
}
return null;
}
}
@@ -106,7 +106,7 @@ public abstract class RequestHandler {
/**
* Looks up an optional service from the {@link FlashContext}.
* Identical to {@link #find} — prefer this name for expressive call sites
* ({@code optional(ViewEngine.class).ifPresent(...)}).
* ({@code optional(MyService.class).ifPresent(...)}).
*
* @param type the service class
* @param <T> the service type
@@ -21,7 +21,11 @@ class ContentTypeTest {
void getBytes_instancesAreNotNull() {
for (ContentType ct : ContentType.values()) {
assertNotNull(ct.getBytes());
assertTrue(ct.getBytes().length > 0);
if (ct == ContentType.NONE) {
assertEquals(0, ct.getBytes().length);
} else {
assertTrue(ct.getBytes().length > 0);
}
}
}
}
@@ -31,4 +31,13 @@ class HttpStatusTest {
assertArrayEquals("301 Moved Permanently".getBytes(StandardCharsets.UTF_8), HttpStatus.bytesForCode(301));
assertArrayEquals("400 Bad Request".getBytes(StandardCharsets.UTF_8), HttpStatus.bytesForCode(400));
}
@Test
void reasonForCode_validAndUnknownCodes() {
assertEquals("OK", HttpStatus.reasonForCode(200));
assertEquals("Not Found", HttpStatus.reasonForCode(404));
assertEquals("Internal Server Error", HttpStatus.reasonForCode(500));
assertNull(HttpStatus.reasonForCode(999));
assertNull(HttpStatus.reasonForCode(0));
}
}