aboutsummaryrefslogtreecommitdiff
path: root/src/cljs/gnunet_web/message.cljs
blob: 275517f88d8836df8643cd6c275c7bc3875b9e77 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
;; message.cljs - message parser for gnunet-web website
;; Copyright (C) 2013,2014  David Barksdale <amatus@amatus.name>
;;
;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;;
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.
;;
;; You should have received a copy of the GNU General Public License
;; along with this program.  If not, see <http://www.gnu.org/licenses/>.

(ns gnunet-web.message
  (:require [gnunet-web.encoder :refer [encode-uint16]]
            [gnunet-web.parser :refer [items parser parse-uint16]]
            [monads.core :refer [set-state]])
  (:require-macros [monads.macros :as monadic]))

(def parse-header
  (monadic/do parser
              [size parse-uint16
               message-type parse-uint16]
              {:size size
               :message-type message-type}))

(defn parse-message-types
  "Produces a parser for the specific set of message parsers given.
   The parser does not fail if the message-type specific parser does not
   consume the entire input."
  [parser-set]
  (monadic/do parser
              [{message-type :message-type size :size} parse-header
               :let [p (first (filter #(= message-type (:message-type (meta %)))
                                      parser-set))]
               :when p
               new-state (items (- size 4))
               old-state (set-state new-state)
               message p
               _ (set-state old-state)]
              {:message-type message-type :message message}))

(defn encode-message
  [{message-type :message-type message :message}]
  (concat
    (encode-uint16 (+ 4 (count message)))
    (encode-uint16 message-type)
    message))

(def parse-peer-identity
  (monadic/do parser
              [peer-identity (items 32)]
              (vec (.apply js/Array nil peer-identity))))