git.fiddlerwoaroof.com
Browse code

Encode strings and hash tables

Fernando Borretti authored on 31/01/2015 20:23:30
Showing 3 changed files
... ...
@@ -2,7 +2,8 @@
2 2
   :author "Fernando Borretti <eudoxiahp@gmail.com>"
3 3
   :license "MIT"
4 4
   :depends-on (:cl-yaml
5
-               :fiveam)
5
+               :fiveam
6
+               :alexandria)
6 7
   :components ((:module "t"
7 8
                 :serial t
8 9
                 :components
... ...
@@ -28,7 +28,12 @@
28 28
   "Encode a float."
29 29
   (princ float stream))
30 30
 
31
+(defmethod encode ((string string) stream)
32
+  "Encode a string."
33
+  (write-string string stream))
34
+
31 35
 (defmethod encode ((list list) stream)
36
+  "Encode a list."
32 37
   (write-string "[" stream)
33 38
   (loop for sublist on list do
34 39
     (encode (first sublist) stream)
... ...
@@ -37,13 +42,28 @@
37 42
   (write-string "]" stream))
38 43
 
39 44
 (defmethod encode ((vector vector) stream)
45
+  "Encode a vector."
40 46
   (encode (loop for elem across vector collecting elem) stream))
41 47
 
48
+(defmethod encode ((table hash-table) stream)
49
+  "Encode a hash table."
50
+  (write-string "{ " stream)
51
+  (loop for sublist on (alexandria:hash-table-keys table) do
52
+    (let ((key (first sublist)))
53
+      (encode key stream)
54
+      (write-string ": " stream)
55
+      (encode (gethash key table) stream)
56
+      (when (rest sublist)
57
+        (write-string ", " stream))))
58
+  (write-string " }" stream))
59
+
42 60
 ;;; Interface
43 61
 
44 62
 (defun emit (value stream)
63
+  "Emit a value to a stream."
45 64
   (encode value stream))
46 65
 
47 66
 (defun emit-to-string (value)
67
+  "Emit a value to string."
48 68
   (with-output-to-string (stream)
49 69
     (emit value stream)))
... ...
@@ -1,6 +1,8 @@
1 1
 (in-package :cl-user)
2 2
 (defpackage cl-yaml-test.emitter
3 3
   (:use :cl :fiveam)
4
+  (:import-from :alexandria
5
+                :alist-hash-table)
4 6
   (:export :emitter))
5 7
 (in-package :cl-yaml-test.emitter)
6 8