All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.tonivade.purefun.runtimes.ConsoleExecutor Maven / Gradle / Ivy

/*
 * Copyright (c) 2018-2022, Antonio Gabriel Muñoz Conejo 
 * Distributed under the terms of the MIT License
 */
package com.github.tonivade.purefun.runtimes;

import static java.nio.charset.StandardCharsets.UTF_8;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.PrintStream;

import com.github.tonivade.purefun.Function1;
import com.github.tonivade.purefun.Producer;
import com.github.tonivade.purefun.effect.RIO;
import com.github.tonivade.purefun.effect.Task;
import com.github.tonivade.purefun.effect.UIO;
import com.github.tonivade.purefun.effect.URIO;
import com.github.tonivade.purefun.effect.PureIO;
import com.github.tonivade.purefun.monad.IO;
import com.github.tonivade.purefun.type.Either;
import com.github.tonivade.purefun.type.Try;

public final class ConsoleExecutor {

  private final StringBuilder input = new StringBuilder();
  private final ByteArrayOutputStream output = new ByteArrayOutputStream();
  
  public ConsoleExecutor read(String string) {
    input.append(string).append('\n');
    return this;
  }
  
  public String getOutput() {
    return new String(output.toByteArray(), UTF_8);
  }
  
  public  Function1> run(PureIO program) {
    return env -> run(() -> program.provide(env));
  }
  
  public  Function1> run(RIO program) {
    return env -> run(() -> program.safeRunSync(env));
  }
  
  public  Function1 run(URIO program) {
    return env -> run(() -> program.unsafeRunSync(env));
  }
  
  public  T run(IO program) {
    return run(program::unsafeRunSync);
  }
  
  public  T run(UIO program) {
    return run(program::unsafeRunSync);
  }
  
  public  Try run(Task program) {
    return run(program::safeRunSync);
  }

  public  T run(Producer program) {
    InputStream savedInput = System.in;
    PrintStream savedOutput = System.out;
    try {
      System.setIn(mockInput());
      System.setOut(mockOutput());
      return program.get();
    } finally {
      System.setIn(savedInput);
      System.setOut(savedOutput);
    }
  }

  private PrintStream mockOutput() {
    return new PrintStream(output);
  }

  private ByteArrayInputStream mockInput() {
    return new ByteArrayInputStream(input.toString().getBytes(UTF_8));
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy