Skip to content

Instantly share code, notes, and snippets.

@bo-tato
Created January 12, 2023 10:42
Show Gist options
  • Save bo-tato/6eab3374548754662345a42e7afcf410 to your computer and use it in GitHub Desktop.
Save bo-tato/6eab3374548754662345a42e7afcf410 to your computer and use it in GitHub Desktop.
(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