aboutsummaryrefslogtreecommitdiff
path: root/src/cljs/gnunet_web/util.cljs
blob: b58f62973290635020d1344567759c2f414db29e (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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
;; util.cljs - utility routines for gnunet-web website
;; Copyright (C) 2014,2015  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.util
  (:require [client-lib]))

(defn now
  []
  (-> (js/Date.) (.valueOf) (* 1000)))

(def objects (atom {:next 0}))

(defn register-object
  [object]
  (swap! objects
         (fn [{:keys [next] :as objects}]
           (conj objects
                 {next object
                  :next (inc next)})))
  ;; This would normally be cheating
  (dec (:next @objects)))

(defn unregister-object
  [object-key]
  (swap! objects dissoc object-key))

(defn get-object
  [object-key]
  (get @objects object-key))

(defn real-to-i64
  [x]
  [(unsigned-bit-shift-right x 0)
   (Math/min 4294967295 (Math/floor (/ x 4294967296)))])

(defn i64-to-real
  [[lw hw]]
  (+ lw (* 4294967296 hw)))

(defn read-memory
  [pointer length]
  (.call js/Array.prototype.slice
         (.subarray js/HEAPU8 pointer (+ pointer length))))

(defn data->string
  [data]
  (let [data-array (to-array data)
        data-len (count data)
        strlen (quot (+ (* 8 data-len) 4) 5)
        string-pointer (js/_malloc strlen)]
    (js/ccallFunc
      js/_GNUNET_STRINGS_data_to_string
      "number"
      (array "array" "number" "number" "number")
      (array data-array data-len string-pointer strlen))
    (let [string (js/Pointer_stringify string-pointer strlen)]
      (js/_free string-pointer)
      string)))