Skip to content

Commit

Permalink
Merge pull request #209 from Dragon-Seeker/1.20.3-EdmMap
Browse files Browse the repository at this point in the history
[1.20.3/4] Implement EdmMap
  • Loading branch information
gliscowo authored Feb 16, 2024
2 parents e3b8e70 + f2eb997 commit 7c174ff
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@
import java.util.Optional;
import java.util.stream.Collectors;

public final class EdmElement<T> {
public sealed class EdmElement<T> permits EdmMap {

private final T value;
private final Type type;

private EdmElement(T value, Type type) {
EdmElement(T value, Type type) {
this.value = value;
this.type = type;
}
Expand Down Expand Up @@ -40,6 +40,14 @@ public Object unwrap() {
}
}

public EdmMap asMap() {
if(this.type != Type.MAP) {
throw new IllegalStateException("Cannot cast EDM element of type " + this.type + " to MAP");
}

return new EdmMap(this.cast());
}

@Override
public String toString() {
return "E(" + this.type.name() + ", " + this.value + ")";
Expand All @@ -48,10 +56,7 @@ public String toString() {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;

EdmElement<?> that = (EdmElement<?>) o;

if (!(o instanceof EdmElement<?> that)) return false;
if (!this.value.equals(that.value)) return false;
return this.type == that.type;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ public class EdmEndec implements Endec<EdmElement<?>> {

public static final EdmEndec INSTANCE = new EdmEndec();

public static final Endec<EdmMap> MAP = INSTANCE.xmap(EdmElement::asMap, edmMap -> edmMap);

private EdmEndec() {}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package io.wispforest.owo.serialization.format.edm;

import io.wispforest.owo.serialization.endec.KeyedEndec;
import io.wispforest.owo.serialization.util.MapCarrier;
import org.jetbrains.annotations.NotNull;

import java.util.Map;

public final class EdmMap extends EdmElement<Map<String, EdmElement<?>>> implements MapCarrier {

EdmMap(EdmElement<Map<String, EdmElement<?>>> mapElement) {
super(mapElement.value(), mapElement.type());
}

@Override
public <T> T getWithErrors(@NotNull KeyedEndec<T> key) {
if (!this.has(key)) return key.defaultValue();
return key.endec().decodeFully(EdmDeserializer::of, this.value().get(key.key()));
}

@Override
public <T> void put(@NotNull KeyedEndec<T> key, @NotNull T value) {
this.value().put(key.key(), key.endec().encodeFully(EdmSerializer::of, value));
}

@Override
public <T> void delete(@NotNull KeyedEndec<T> key) {
this.value().remove(key.key());
}

@Override
public <T> boolean has(@NotNull KeyedEndec<T> key) {
return this.value().containsKey(key.key());
}
}

0 comments on commit 7c174ff

Please sign in to comment.