Created
January 12, 2023 10:42
-
-
Save bo-tato/6eab3374548754662345a42e7afcf410 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns protohackers.challenge2-gloss | |
(:require | |
[aleph.tcp :as tcp] | |
[clojure.core.match :refer [match]] | |
[clojure.data.json :as json] | |
[clojure.math :as math] | |
[gloss.core :as gloss] | |
[gloss.io :as io] | |
[manifold.stream :as s])) | |
(def protocol | |
(gloss/string :utf-8 :delimiters ["\n"])) | |
(defn prime? [n] | |
(cond | |
(float? n) false | |
(<= n 1) false | |
(< n 4) true | |
:else (every? #(not= 0 (rem n %)) | |
(range 2 (inc (math/sqrt n)))))) | |
(defn close-malformed [s] | |
(s/put! s "malformed\n") | |
(s/close! s)) | |
(defn handler [s _info] | |
(letfn [(from-json [data] (try (json/read-str data) | |
(catch Exception _ (close-malformed s)))) | |
(handle-req [req] (match req | |
{"method" "isPrime" | |
"number" (n :guard number?)} | |
{:method "isPrime" | |
:prime (prime? n)} | |
:else (close-malformed s)))] | |
(s/connect | |
(s/map | |
#(->> % ; process each line | |
from-json | |
handle-req | |
json/write-str | |
(io/encode protocol)) | |
(io/decode-stream s protocol)) ; get input from stream and turn into lines | |
s))) ; write response back to stream | |
(defn run [] | |
(tcp/start-server #'handler {:port 8589})) | |
(comment | |
;; start server | |
(def server (run)) | |
;; stop server | |
(.close server)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment