Skip to content

Commit 3ed8ab8

Browse files
committed
Better HTTPStatus code lookup
1 parent 6cc7a16 commit 3ed8ab8

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

src/main/java/dev/latvian/apps/tinyserver/http/response/HTTPStatus.java

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
import java.nio.ByteBuffer;
77
import java.nio.charset.StandardCharsets;
8+
import java.util.List;
89

910
public enum HTTPStatus implements HTTPResponse {
1011
// 1xx - Informational
@@ -64,28 +65,39 @@ public enum HTTPStatus implements HTTPResponse {
6465
;
6566

6667
private static final HTTPStatus[] VALUES = values();
68+
public static final List<HTTPStatus> ALL = List.of(VALUES);
69+
public static final List<HTTPStatus> INFORMATIONAL = List.copyOf(ALL.stream().filter(HTTPStatus::informational).toList());
70+
public static final List<HTTPStatus> SUCCESS = List.copyOf(ALL.stream().filter(HTTPStatus::success).toList());
71+
public static final List<HTTPStatus> REDIRECT = List.copyOf(ALL.stream().filter(HTTPStatus::redirect).toList());
72+
public static final List<HTTPStatus> CLIENT_ERROR = List.copyOf(ALL.stream().filter(HTTPStatus::clientError).toList());
73+
public static final List<HTTPStatus> SERVER_ERROR = List.copyOf(ALL.stream().filter(HTTPStatus::serverError).toList());
74+
public static final List<List<HTTPStatus>> LOOKUP = List.of(INFORMATIONAL, SUCCESS, REDIRECT, CLIENT_ERROR, SERVER_ERROR);
6775

6876
@Nullable
6977
public static HTTPStatus fromCode(int code) {
7078
if (code < 100 || code > 599) {
7179
return null;
7280
}
7381

74-
for (var status : VALUES) {
75-
if (status.statusCode.code() == code) {
82+
for (var status : LOOKUP.get(code / 100 - 1)) {
83+
if (status.code == code) {
7684
return status;
7785
}
7886
}
7987

8088
return null;
8189
}
8290

91+
private final int code;
8392
private final StatusCode statusCode;
8493
private final ByteBuffer responseBuffer;
94+
private final String string;
8595

8696
HTTPStatus(int code, String message) {
97+
this.code = code;
8798
this.statusCode = new StatusCode(code, message);
8899
this.responseBuffer = ByteBuffer.wrap(("HTTP/1.1 " + statusCode.code() + " " + statusCode.message() + "\r\n").getBytes(StandardCharsets.UTF_8));
100+
this.string = Integer.toString(code);
89101
}
90102

91103
@Override
@@ -128,4 +140,13 @@ public boolean serverError() {
128140
public boolean error() {
129141
return statusCode.code() >= 400;
130142
}
143+
144+
public int code() {
145+
return code;
146+
}
147+
148+
@Override
149+
public String toString() {
150+
return string;
151+
}
131152
}

0 commit comments

Comments
 (0)