Skip to content

Commit

Permalink
Add additional type guarantees
Browse files Browse the repository at this point in the history
Create new type conversions for user-defined functions to allow consuming:

- dictionaries
- JSON data
  • Loading branch information
apmasell authored and avarsava committed Jan 26, 2024
1 parent 345a339 commit 8f8a554
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
1 change: 1 addition & 0 deletions changes/add_tyguar.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* Add new type conversion for dictionaries and JSON values in the Java API
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import ca.on.oicr.gsi.Pair;
import ca.on.oicr.gsi.shesmu.plugin.AlgebraicValue;
import ca.on.oicr.gsi.shesmu.plugin.Tuple;
import com.fasterxml.jackson.databind.JsonNode;
import java.nio.file.Path;
import java.time.Instant;
import java.util.List;
Expand Down Expand Up @@ -64,6 +65,33 @@ public static <E extends Enum<E>> TypeGuarantee<E> algebraicForEnum(Class<E> cla
Stream.of(clazz.getEnumConstants())
.map(e -> AlgebraicGuarantee.empty(e.name().toUpperCase(), e)));
}
/**
* Provides an argument mapping from a Shesmu dictionary/map into a Java map
*
* @param key the type guarantee for the keys; note that the conversion should preserve equality
* of the original values (<em>i.e.</em>, if two keys are not equal in Shesmu, then <code>K
* </code> should also be not equal) or collisions could occur
* @param value the type guarantee for the values
* @return a guarantee for a map
*/
public static <K, V> TypeGuarantee<Map<K, V>> dictionary(
TypeGuarantee<K> key, TypeGuarantee<V> value) {
final var dictionaryType = Imyhat.dictionary(key.type(), value.type());
return new TypeGuarantee<>() {
@Override
public Imyhat type() {
return dictionaryType;
}

@Override
public Map<K, V> unpack(Object object) {
return ((Map<?, ?>) object)
.entrySet().stream()
.collect(
Collectors.toMap(e -> key.unpack(e.getKey()), e -> value.unpack(e.getValue())));
}
};
}

public static <T> TypeGuarantee<List<T>> list(TypeGuarantee<T> inner) {
final var listType = inner.type().asList();
Expand Down Expand Up @@ -354,6 +382,25 @@ public Double unpack(Object object) {
return (Double) object;
}
};
/**
* Convert a Shesmu JSON value into a Jackson structure
*
* <p>Note that the converted JSON object must <em>not</em> be mutated by the recipient or the
* olive might break as olives assume all values are immutable.
*/
public static final TypeGuarantee<JsonNode> JSON =
new TypeGuarantee<>() {
@Override
public Imyhat type() {
return Imyhat.JSON;
}

@Override
public JsonNode unpack(Object object) {
return (JsonNode) object;
}
};

public static final TypeGuarantee<Long> LONG =
new TypeGuarantee<>() {
@Override
Expand Down

0 comments on commit 8f8a554

Please sign in to comment.