diff --git a/base/src/main/java/de/staropensource/sosengine/base/exceptions/TristateConversionException.java b/base/src/main/java/de/staropensource/sosengine/base/exceptions/TristateConversionException.java new file mode 100644 index 00000000..4bf1d8ee --- /dev/null +++ b/base/src/main/java/de/staropensource/sosengine/base/exceptions/TristateConversionException.java @@ -0,0 +1,36 @@ +/* + * STAROPENSOURCE ENGINE SOURCE FILE + * Copyright (c) 2024 The StarOpenSource Engine Contributors + * Licensed under the GNU Affero General Public License v3 + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +package de.staropensource.sosengine.base.exceptions; + +import de.staropensource.sosengine.base.types.Tristate; + +/** + * Thrown when converting a {@link Tristate} into a boolean fails. + *

+ * This exception inherits {@link RuntimeException} on purpose, as sometimes + * you expect or have already validated the {@link Tristate} not being {@link Tristate#UNSET}. + * + * @since v1-alpha2 + */ +public class TristateConversionException extends RuntimeException { + public TristateConversionException() { + super("Can't convert Tristate.UNSET into a boolean"); + } +} diff --git a/base/src/main/java/de/staropensource/sosengine/base/types/Tristate.java b/base/src/main/java/de/staropensource/sosengine/base/types/Tristate.java index 5c6dd91b..867603ce 100644 --- a/base/src/main/java/de/staropensource/sosengine/base/types/Tristate.java +++ b/base/src/main/java/de/staropensource/sosengine/base/types/Tristate.java @@ -19,6 +19,9 @@ package de.staropensource.sosengine.base.types; +import de.staropensource.sosengine.base.exceptions.TristateConversionException; +import org.jetbrains.annotations.NotNull; + /** * tl;dr just a boolean but it can be UNSET too. * @@ -45,5 +48,20 @@ public enum Tristate { * * @since v1-alpha1 */ - FALSE + FALSE; + + /** + * Converts a {@link Tristate} into a boolean. + * + * @return booleanized {@link Tristate} + * @throws TristateConversionException when encountering {@link #UNSET}. + * @since v1-alpha2 + */ + public static boolean toBoolean(@NotNull Tristate tristate) { + return switch (tristate) { + case UNSET -> throw new TristateConversionException(); + case TRUE -> true; + case FALSE -> false; + }; + } }