-
Notifications
You must be signed in to change notification settings - Fork 2
/
example.cljc
120 lines (70 loc) · 2.22 KB
/
example.cljc
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
;; This Source Code Form is subject to the terms of the Mozilla Public
;; License, v. 2.0. If a copy of the MPL was not distributed with this
;; file, You can obtain one at https://mozilla.org/MPL/2.0/.
(ns helins.binf.example
"Basic example of creating a view over a buffer and writing a date."
(:require [helins.binf :as binf]
[helins.binf.buffer :as binf.buffer]))
;;;;;;;;;; Functions for writing a date and reading it back
(defn wr-date
[view year month day]
(-> view
(binf/wr-b16 year)
(binf/wr-b8 month)
(binf/wr-b8 day)))
(defn rr-date
[view]
[(binf/rr-u16 view)
(binf/rr-u8 view)
(binf/rr-u8 view)])
;;;;;;;;;; Allocating a buffer and creating a view
(def my-buffer
"A buffer of 1024 bytes. Size depends on use case."
(binf.buffer/alloc 1024))
(def my-view
"One view created over our buffer.
Several views can be created over one buffer, whole or parts of it."
(binf/view my-buffer))
;;;;;;;;;; Eval interactively - Writing and reading a date
(comment
;; From the current position (0 for a new view), write date and read it back after coming
;; back to that position
;;
(= [2021 3 16]
(let [position-date (binf/position my-view)]
(-> my-view
(wr-date 2021
3
16)
(binf/seek position-date)
rr-date))))
;;;;;;;;;; Eval interactively - Buffers, subviews, and growing
(comment
;; When a view wraps a buffer, it can always be extracted.
;;
(= my-buffer
(binf/backing-buffer my-view))
;; Creating a subview of our view.
;; They both work on the same buffer but independantly.
;;
;; An offset of a 100 bytes with a window of 200 bytes.
;;
(def sub-view
(binf/view my-view
100
200))
;; The position of that sub-view starts transparently at 0
;;
(= 0
(binf/position sub-view))
(= 200
(binf/limit sub-view))
;; Creating a new view which copies the original and add 256 additional bytes.
;; Position is preserved and copied as well.
;;
(def my-bigger-view
(binf/grow my-view
256))
(= (+ 1024
256)
(binf/limit my-bigger-view)))