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

com.github.tonivade.purefun.effect.util.ZConsole Maven / Gradle / Ivy

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

import com.github.tonivade.purefun.Unit;
import com.github.tonivade.purefun.effect.ZIO;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Queue;

public interface ZConsole {

   ZConsole.Service console();

  static  ZIO readln() {
    return ZIO.accessM(env -> env.console().readln());
  }

  static  ZIO println(String text) {
    return ZIO.accessM(env -> env.console().println(text));
  }

  interface Service {
    ZIO readln();

    ZIO println(String text);
  }

  static ZConsole test(final Queue input, final Queue output) {
    return new ZConsole() {

      @Override
      public  Service console() {
        return new ZConsole.Service() {

          @Override
          public ZIO readln() {
            return ZIO.task(input::poll);
          }

          @Override
          public ZIO println(String text) {
            return ZIO.exec(() -> output.offer(text));
          }
        };
      }
    };
  }

  static ZConsole live() {
    return new ZConsole() {

      @Override
      public  Service console() {
        return new ZConsole.Service() {

          @Override
          public ZIO readln() {
            return ZIO.task(() -> reader().readLine());
          }

          @Override
          public ZIO println(String text) {
            return ZIO.exec(() -> writer().println(text));
          }

          private BufferedReader reader() {
            return new BufferedReader(new InputStreamReader(System.in));
          }

          private PrintWriter writer() {
            return new PrintWriter(System.out, true);
          }
        };
      }
    };
  }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy