|
| 1 | +package com.hubspot.jinjava.interpret; |
| 2 | + |
| 3 | +import com.hubspot.jinjava.interpret.AutoCloseableSupplier.AutoCloseableImpl; |
| 4 | +import java.util.function.Consumer; |
| 5 | +import java.util.function.Supplier; |
| 6 | + |
| 7 | +public class AutoCloseableSupplier<T> implements Supplier<AutoCloseableImpl<T>> { |
| 8 | + |
| 9 | + public interface GenericThrowingFunction<T, R, E extends Exception> { |
| 10 | + R apply(T t) throws E; |
| 11 | + } |
| 12 | + |
| 13 | + public static <T> AutoCloseableSupplier<T> of(T t) { |
| 14 | + return new AutoCloseableSupplier<>(new AutoCloseableImpl<>(t, ignored -> {})); |
| 15 | + } |
| 16 | + |
| 17 | + public static <T> AutoCloseableSupplier<T> of(T t, Consumer<T> closeConsumer) { |
| 18 | + return new AutoCloseableSupplier<>(new AutoCloseableImpl<>(t, closeConsumer)); |
| 19 | + } |
| 20 | + |
| 21 | + private final AutoCloseableImpl<T> autoCloseableImplWrapper; |
| 22 | + |
| 23 | + private AutoCloseableSupplier(AutoCloseableImpl<T> autoCloseableImplWrapper) { |
| 24 | + this.autoCloseableImplWrapper = autoCloseableImplWrapper; |
| 25 | + } |
| 26 | + |
| 27 | + @Override |
| 28 | + public AutoCloseableImpl<T> get() { |
| 29 | + return autoCloseableImplWrapper; |
| 30 | + } |
| 31 | + |
| 32 | + public T dangerouslyGetWithoutClosing() { |
| 33 | + return autoCloseableImplWrapper.value(); |
| 34 | + } |
| 35 | + |
| 36 | + public <R, E extends Exception> AutoCloseableSupplier<R> map( |
| 37 | + GenericThrowingFunction<T, R, E> mapper |
| 38 | + ) throws E { |
| 39 | + T t = autoCloseableImplWrapper.value(); |
| 40 | + return new AutoCloseableSupplier<>( |
| 41 | + new AutoCloseableImpl<>( |
| 42 | + mapper.apply(t), |
| 43 | + r -> autoCloseableImplWrapper.closeConsumer.accept(t) |
| 44 | + ) |
| 45 | + ); |
| 46 | + } |
| 47 | + |
| 48 | + public static class AutoCloseableImpl<T> implements java.lang.AutoCloseable { |
| 49 | + |
| 50 | + private final T t; |
| 51 | + private final Consumer<T> closeConsumer; |
| 52 | + |
| 53 | + protected AutoCloseableImpl(T t, Consumer<T> closeConsumer) { |
| 54 | + this.t = t; |
| 55 | + this.closeConsumer = closeConsumer; |
| 56 | + } |
| 57 | + |
| 58 | + public T value() { |
| 59 | + return t; |
| 60 | + } |
| 61 | + |
| 62 | + @Override |
| 63 | + public void close() { |
| 64 | + closeConsumer.accept(t); |
| 65 | + } |
| 66 | + } |
| 67 | +} |
0 commit comments