Search in sources :

Example 1 with Fun2

use of primal.fp.Funs2.Fun2 in project suite by stupidsing.

the class Fractional method format.

public Node format(Fract<I> fract) {
    OpGroup add = ex.add;
    OpGroup mul = ex.mul;
    Fun2<I, I, Node> f = (n, d) -> {
        Node i0 = format_.apply(n);
        Node i1 = format_.apply(d);
        return mul.apply(i0, mul.inverse(i1));
    };
    I n_ = fract.t0;
    I d_ = fract.t1;
    I nn = neg_.apply(n_);
    if (0 <= sgn_.apply(n_))
        return f.apply(n_, d_);
    else
        return add.inverse(f.apply(nn, d_));
}
Also used : Ring(suite.math.sym.Sym.Ring) Pattern(suite.BindArrayUtil.Pattern) OpGroup(suite.math.sym.Express.OpGroup) Fun(suite.util.FunUtil.Fun) Node(suite.node.Node) Opt(suite.adt.Opt) Iterate(suite.util.FunUtil.Iterate) Pair(suite.adt.pair.Pair) Fun2(suite.util.FunUtil2.Fun2) Obj_Int(suite.primitive.IntPrimitives.Obj_Int) Field(suite.math.sym.Sym.Field) SwitchNode(suite.node.io.SwitchNode) Int(suite.node.Int) OpGroup(suite.math.sym.Express.OpGroup) Node(suite.node.Node) SwitchNode(suite.node.io.SwitchNode)

Example 2 with Fun2

use of primal.fp.Funs2.Fun2 in project suite by stupidsing.

the class HttpIo method readRequest.

public Request readRequest(InputStream is0) {
    var ls = ReadLine.from(is0).split(" ");
    var headers = readHeaders(is0);
    return FixieArray.of(ls).map((method, url, protocol) -> {
        Fun2<String, String, Request> requestFun = (host, pqs) -> Split.strl(pqs, "?").map((path0, query) -> {
            var is1 = getContentStream(is0, headers);
            var path1 = path0.startsWith("/") ? path0 : "/" + path0;
            var path2 = ex(() -> URLDecoder.decode(path1, Utf8.charset));
            return // 
            Equals.string(protocol, "HTTP/1.1") ? // 
            new Request(method, host, path2, query, headers, Pull.from_(is1)) : fail("only HTTP/1.1 is supported");
        });
        var pp = Split.string(url, "://");
        return pp != null ? Split.strl(pp.v, "/").map(requestFun) : requestFun.apply("", url);
    });
}
Also used : OutputStream(java.io.OutputStream) FixieArray(primal.adt.FixieArray) Copy(suite.util.Copy) Fail.fail(primal.statics.Fail.fail) URLDecoder(java.net.URLDecoder) ReadStream(primal.io.ReadStream) IOException(java.io.IOException) To(suite.util.To) Math.min(java.lang.Math.min) Header(suite.http.Http.Header) Bytes(primal.primitive.adt.Bytes) Response(suite.http.Http.Response) Rethrow.ex(primal.statics.Rethrow.ex) Utf8(primal.Nouns.Utf8) ReadLine(primal.Verbs.ReadLine) Request(suite.http.Http.Request) Split(primal.MoreVerbs.Split) Math.max(java.lang.Math.max) Pull(primal.MoreVerbs.Pull) Fun2(primal.fp.Funs2.Fun2) Equals(primal.Verbs.Equals) Puller(primal.puller.Puller) InputStream(java.io.InputStream) Request(suite.http.Http.Request)

Example 3 with Fun2

use of primal.fp.Funs2.Fun2 in project suite by stupidsing.

the class HttpNio method listen.

private void listen(Reg reg) {
    var rw = new Object() {

        // 0 - read, 1 - write, 2 - close after all written
        private int stage = 0;

        private Bytes br = Bytes.empty;

        private Bytes bw = Bytes.empty;

        private Puller<Bytes> write;

        private Source<Boolean> eater = () -> parseLine(line -> handleRequest1stLine(line.trim(), response -> {
            var data = // 
            "HTTP/1.1 " + response.status + "\r\n" + response.headers.streamlet().map((k, v) -> k + ": " + v + "\r\n").toJoinedString() + "\r\n";
            stage = 1;
            if (response.body != null)
                write = Puller.concat(Pull.from(data), response.body);
            else {
                bw = Bytes.of(data.getBytes(Utf8.charset));
                response.write.f(bytes -> {
                    if (bytes != null)
                        bw = bw.append(bytes);
                    else
                        stage = 2;
                    listen();
                });
            }
        }));

        private void listen() {
            if (!bw.isEmpty())
                reg.listenWrite(() -> bw, this::written);
            else if (stage == 0)
                reg.listenRead(in -> {
                    read(in);
                    listen();
                });
            else if (stage == 1 && write != null)
                reg.listenWrite(() -> bw = write.pull(), this::written);
            else if (stage == 2)
                reg.listenWrite(() -> null, null);
            else if (stage == 3)
                reg.listen(0, null, null, null);
        }

        private void read(Bytes in) {
            if (in != null) {
                br = br.append(in);
                while (eater.g()) ;
            } else
                // closes connection
                write = Puller.empty();
        }

        private void written(int n) {
            if (0 <= n)
                bw = bw.range(n);
            else
                stage = 3;
            listen();
        }

        private void handleRequest1stLine(String line, Sink<Response> cb) {
            var hrhl = handleRequestHeaderLine(lines -> handleRequestBody(line, lines, cb));
            eater = () -> parseLine(hrhl);
        }

        private Sink<String> handleRequestHeaderLine(Sink<List<String>> cb) {
            var lines = new ArrayList<String>();
            return line0 -> {
                var line1 = line0.trim();
                if (!line1.isEmpty())
                    lines.add(line1);
                else
                    cb.f(lines);
            };
        }

        private void handleRequestBody(String line0, List<String> headerLines, Sink<Response> cb) {
            eater = () -> // 
            FixieArray.of(// 
            line0.split(" ")).map((method, url, proto) -> handleRequestBody(proto, method, url, headerLines, cb));
        }

        private // 
        boolean handleRequestBody(// 
        String proto, // 
        String method, // 
        String url, // 
        List<String> lines, Sink<Response> cb) {
            var headers = // 
            Read.from(// 
            lines).fold(new Header(), (headers_, line_) -> // 
            Split.strl(line_, // 
            ":").map((k, v) -> headers_.put(k, v)));
            var queue = new ArrayBlockingQueue<Bytes>(Buffer.size);
            Sink<Bytes> offer = queue::add;
            Source<Bytes> take = queue::poll;
            Fun2<String, String, Request> requestFun = (host, pqs) -> Split.strl(pqs, "?").map((path0, query) -> {
                var path1 = path0.startsWith("/") ? path0 : "/" + path0;
                var path2 = ex(() -> URLDecoder.decode(path1, Utf8.charset));
                return // 
                Equals.string(proto, "HTTP/1.1") ? // 
                new Request(method, host, path2, query, headers, Puller.of(take)) : fail("only HTTP/1.1 is supported");
            });
            var pp = Split.string(url, "://");
            var request = pp != null ? Split.strl(pp.v, "/").map(requestFun) : requestFun.apply("", url);
            var cl = request.headers.getOpt("Content-Length").map(Long::parseLong);
            var te = Equals.ab(request.headers.getOpt("Transfer-Encoding"), Opt.of("chunked"));
            Log_.info(request.getLogString());
            if (te)
                eater = handleChunkedRequestBody(request, offer, cb);
            else if (cl.hasValue())
                eater = handleRequestBody(request, offer, cl.g(), cb);
            else
                eater = handleRequestBody(request, offer, 0, cb);
            return true;
        }

        private // 
        Source<Boolean> handleRequestBody(// 
        Request request, // 
        Sink<Bytes> body, // 
        long contentLength, Sink<Response> cb) {
            return new Source<>() {

                private int n;

                public Boolean g() {
                    body.f(br);
                    var isOpen = br != null;
                    if (isOpen) {
                        n += br.size();
                        br = Bytes.empty;
                    }
                    if (!isOpen || contentLength <= n)
                        cb.f(handler.handle(request));
                    return false;
                }
            };
        }

        private Source<Boolean> handleChunkedRequestBody(Request request, Sink<Bytes> body, Sink<Response> cb) {
            return () -> {
                for (var i0 = 0; i0 < br.size(); i0++) if (br.get(i0) == 10) {
                    var line = new String(br.range(0, i0).toArray(), Utf8.charset);
                    var size = Integer.parseInt(line.trim(), 16);
                    for (var i1 = i0 + 1 + size; i1 < br.size(); i1++) if (br.get(i1) == 10) {
                        var chunk = br.range(i0 + 1, i1);
                        br = br.range(i1);
                        body.f(chunk);
                        return true;
                    }
                    if (size == 0)
                        cb.f(handler.handle(request));
                }
                return false;
            };
        }

        private boolean parseLine(Sink<String> handleLine) {
            for (var i = 0; i < br.size(); i++) if (br.get(i) == 10) {
                var line = new String(br.range(0, i).toArray(), Utf8.charset);
                br = br.range(i + 1);
                handleLine.f(line);
                return true;
            }
            return false;
        }
    };
    rw.listen();
}
Also used : FixieArray(primal.adt.FixieArray) Fail.fail(primal.statics.Fail.fail) URLDecoder(java.net.URLDecoder) Reg(suite.os.ListenNio.Reg) Sink(primal.fp.Funs.Sink) ArrayList(java.util.ArrayList) Response(suite.http.Http.Response) Utf8(primal.Nouns.Utf8) Request(suite.http.Http.Request) Split(primal.MoreVerbs.Split) Opt(primal.adt.Opt) Pull(primal.MoreVerbs.Pull) Handler(suite.http.Http.Handler) ListenNio(suite.os.ListenNio) Buffer(primal.Nouns.Buffer) Source(primal.fp.Funs.Source) Header(suite.http.Http.Header) Log_(primal.os.Log_) Read(primal.MoreVerbs.Read) Bytes(primal.primitive.adt.Bytes) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) List(java.util.List) Rethrow.ex(primal.statics.Rethrow.ex) Fun2(primal.fp.Funs2.Fun2) Equals(primal.Verbs.Equals) Puller(primal.puller.Puller) ArrayList(java.util.ArrayList) Request(suite.http.Http.Request) Source(primal.fp.Funs.Source) Bytes(primal.primitive.adt.Bytes) Sink(primal.fp.Funs.Sink) Header(suite.http.Http.Header) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) Puller(primal.puller.Puller) ArrayList(java.util.ArrayList) List(java.util.List)

Example 4 with Fun2

use of primal.fp.Funs2.Fun2 in project suite by stupidsing.

the class P4DecomposeOperand method decomposeOpMem.

public OpMem decomposeOpMem(int fd, Funp n0, int disp0, int size) {
    class Decompose {

        private Operator operator;

        private List<Funp> nodes = new ArrayList<>();

        private Decompose(Operator operator) {
            this.operator = operator;
        }

        private void decompose(Funp n_) {
            FunpTree tree;
            if (n_ instanceof FunpTree && (tree = (FunpTree) n_).operator == operator) {
                decompose(tree.left);
                decompose(tree.right);
            } else
                nodes.add(n_);
        }
    }
    Fun2<Operator, Funp, List<Funp>> decompose = (operator, n_) -> {
        Decompose dec = new Decompose(operator);
        dec.decompose(n_);
        return dec.nodes;
    };
    class DecomposeMult {

        private long scale = 1;

        private OpReg reg;

        private List<Funp> mults = new ArrayList<>();

        private void decompose(Funp n0) {
            FunpTree2 tree;
            Funp r;
            for (Funp n1 : decompose.apply(TermOp.MULT__, n0)) if (n1 instanceof FunpFramePointer && isUseEbp && reg == null)
                reg = amd64.ebp;
            else if (n1 instanceof FunpNumber)
                scale *= ((FunpNumber) n1).i.get();
            else if (// 
            n1 instanceof FunpTree2 && // 
            (tree = (FunpTree2) n1).operator == TreeUtil.SHL && (r = tree.right) instanceof FunpNumber) {
                decompose(tree.left);
                scale <<= ((FunpNumber) r).i.get();
            } else
                mults.add(n1);
        }
    }
    class DecomposePlus {

        private OpReg baseReg = null, indexReg = null;

        private int scale = 1, disp = disp0;

        private boolean ok = is124(size);

        private DecomposePlus(Funp n0) {
            for (Funp n1 : decompose.apply(TermOp.PLUS__, n0)) if (n1 instanceof FunpFramePointer && !isUseEbp) {
                addReg(amd64.esp, 1);
                disp -= fd;
            } else {
                DecomposeMult dec = new DecomposeMult();
                dec.decompose(n1);
                if (dec.mults.isEmpty()) {
                    OpReg reg_ = dec.reg;
                    long scale_ = dec.scale;
                    if (reg_ != null)
                        addReg(reg_, scale_);
                    else
                        disp += scale_;
                } else
                    ok = false;
            }
        }

        private void addReg(OpReg reg_, long scale_) {
            if (scale_ == 1 && baseReg == null)
                baseReg = reg_;
            else if (is1248(scale_) && indexReg == null) {
                indexReg = reg_;
                scale = (int) scale_;
            } else
                ok = false;
        }

        private OpMem op() {
            return ok ? amd64.mem(baseReg, indexReg, scale, disp, size) : null;
        }
    }
    return new DecomposePlus(n0).op();
}
Also used : Operator(suite.node.io.Operator) OpMem(suite.assembler.Amd64.OpMem) FunpTree(suite.funp.P0.FunpTree) Amd64(suite.assembler.Amd64) TermOp(suite.node.io.TermOp) OpReg(suite.assembler.Amd64.OpReg) ArrayList(java.util.ArrayList) FunpTree2(suite.funp.P0.FunpTree2) Funp(suite.funp.Funp_.Funp) List(java.util.List) FunpFramePointer(suite.funp.P2.FunpFramePointer) Fun2(suite.util.FunUtil2.Fun2) FunpNumber(suite.funp.P0.FunpNumber) Operand(suite.assembler.Amd64.Operand) FunpMemory(suite.funp.P2.FunpMemory) Operator(suite.node.io.Operator) TreeUtil(suite.node.util.TreeUtil) FunpDontCare(suite.funp.P0.FunpDontCare) FunpTree2(suite.funp.P0.FunpTree2) FunpNumber(suite.funp.P0.FunpNumber) Funp(suite.funp.Funp_.Funp) ArrayList(java.util.ArrayList) List(java.util.List) FunpFramePointer(suite.funp.P2.FunpFramePointer) FunpTree(suite.funp.P0.FunpTree) OpReg(suite.assembler.Amd64.OpReg)

Example 5 with Fun2

use of primal.fp.Funs2.Fun2 in project suite by stupidsing.

the class ServerMain method handler.

private Handler handler() {
    BiPredicate<String, String> authenticate = (username, password) -> // 
    Defaults.secrets().prove(Suite.substitute("auth .0 .1", new Str(username), new Str(password)));
    Fun2<String, String, List<String>> authenticateRoles = (username, password) -> {
        return authenticate.test(username, password) ? List.of("role") : null;
    };
    var sseHeaders = new Header(// 
    PerMap.<String, PerList<String>>empty().put("Cache-Control", // 
    PerList.of("no-cache")).put("Content-Type", PerList.of("text/event-stream")));
    Handler handlerDump = request -> Response.of(Pull.from(// 
    "" + // 
    "<html>" + "<br/>method = " + // 
    request.method + "<br/>server = " + // 
    request.server + "<br/>paths = " + // 
    request.paths + "<br/>attrs = " + // 
    HttpHeaderUtil.getAttrs(request.query) + "<br/>headers = " + // 
    request.headers + "</html>"));
    Handler handlerSse = request -> Response.ofWriter(Http.S200, sseHeaders, write -> {
        new Object() {

            private int i = 8;

            private void dispatch() {
                sleep.sink2(1000l, () -> {
                    if (0 < i--) {
                        var event = "event: number\ndata: { \"i\": " + i + " }\n\n";
                        write.f(Bytes.of(event.getBytes(Utf8.charset)));
                        dispatch();
                    } else
                        write.f(null);
                });
            }
        }.dispatch();
    });
    Handler handlerStatus = request -> {
        var cfg = new TradeCfgImpl();
        var summarize = Summarize.of(cfg);
        var sbs = summarize.summarize(trade -> trade.strategy);
        return Response.of(Pull.from("<pre>" + sbs.log + new TreeMap<>(sbs.pnlByKey) + "</pre>"));
    };
    var hh = new HttpHandle();
    var hhsa = new HttpHandleSessionAuth();
    var hhta = new HttpHandleTokenAuth();
    return hh.routeByPath(// 
    PerMap.<String, Handler>empty().put("api", // 
    hhta.applyFilter("role", hh.serveText("in good shape"))).put("hello", // 
    hh.serveText("hello world")).put("html", // 
    hh.serveDir(Paths.get(FileUtil.suiteDir() + "/src/main/html"))).put("path", // 
    hh.serveDir(Tmp.root)).put("site", // 
    hhsa.getHandler(authenticate, handlerDump)).put("sse", // 
    handlerSse).put("status", // 
    handlerStatus).put("token", hh.routeByMethod(// 
    PerMap.<String, Handler>empty().put("PATCH", // 
    hhta.refreshToken(authenticateRoles)).put("POST", hhta.getToken(authenticateRoles)))));
}
Also used : Schedule(suite.os.Schedule) Sink2(primal.fp.Funs2.Sink2) LocalDateTime(java.time.LocalDateTime) Scheduler(suite.os.Scheduler) RunUtil(suite.util.RunUtil) ArrayList(java.util.ArrayList) Defaults(suite.cfg.Defaults) BiPredicate(java.util.function.BiPredicate) Http(suite.http.Http) Response(suite.http.Http.Response) SmtpServer(suite.smtp.SmtpServer) Utf8(primal.Nouns.Utf8) LocalTime(java.time.LocalTime) FileUtil(suite.os.FileUtil) Pull(primal.MoreVerbs.Pull) HttpServe(suite.http.HttpServe) Sleep(primal.Verbs.Sleep) Handler(suite.http.Http.Handler) TelegramBotMain(suite.sample.TelegramBotMain) PerMap(primal.persistent.PerMap) TradeCfgImpl(suite.trade.data.TradeCfgImpl) Files(java.nio.file.Files) HttpNio(suite.http.HttpNio) HttpHandleSessionAuth(suite.http.HttpHandleSessionAuth) Summarize(suite.trade.analysis.Summarize) HttpHandle(suite.http.HttpHandle) Start(primal.Verbs.Start) HttpHeaderUtil(suite.http.HttpHeaderUtil) Header(suite.http.Http.Header) Bytes(primal.primitive.adt.Bytes) List(java.util.List) TreeMap(java.util.TreeMap) Paths(java.nio.file.Paths) HttpHandleTokenAuth(suite.http.HttpHandleTokenAuth) Fun2(primal.fp.Funs2.Fun2) PerList(primal.persistent.PerList) Str(suite.node.Str) Tmp(primal.Nouns.Tmp) HttpHandle(suite.http.HttpHandle) TradeCfgImpl(suite.trade.data.TradeCfgImpl) Handler(suite.http.Http.Handler) Str(suite.node.Str) HttpHandleSessionAuth(suite.http.HttpHandleSessionAuth) Header(suite.http.Http.Header) ArrayList(java.util.ArrayList) List(java.util.List) PerList(primal.persistent.PerList) HttpHandleTokenAuth(suite.http.HttpHandleTokenAuth)

Aggregations

ArrayList (java.util.ArrayList)3 List (java.util.List)3 Pull (primal.MoreVerbs.Pull)3 Utf8 (primal.Nouns.Utf8)3 Fun2 (primal.fp.Funs2.Fun2)3 Bytes (primal.primitive.adt.Bytes)3 Header (suite.http.Http.Header)3 Response (suite.http.Http.Response)3 URLDecoder (java.net.URLDecoder)2 Split (primal.MoreVerbs.Split)2 Equals (primal.Verbs.Equals)2 FixieArray (primal.adt.FixieArray)2 Puller (primal.puller.Puller)2 Fail.fail (primal.statics.Fail.fail)2 Rethrow.ex (primal.statics.Rethrow.ex)2 Handler (suite.http.Http.Handler)2 Request (suite.http.Http.Request)2 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1