Permalink
Browse files

Create the websocket-to-bytes function, to encode a number in a

certain amount of bytes.
  • Loading branch information...
1 parent 8fd1f74 commit 2148c5afee6e8e2631ae0c826eeb9b04495959f7 @ahyatt committed May 22, 2012
Showing with 30 additions and 0 deletions.
  1. +10 −0 websocket-test.el
  2. +20 −0 websocket.el
View
@@ -158,3 +158,13 @@
(websocket-process-frame websocket
(make-websocket-frame :opcode 'close))
deleted)))))
+
+(ert-deftest websocket-to-bytes ()
+ ;; We've tested websocket-get-bytes by itself, now we can use it to
+ ;; help test websocket-to-bytes.
+ (should (equal 30 (websocket-get-bytes (websocket-to-bytes 30 1) 1)))
+ (should (equal 300 (websocket-get-bytes (websocket-to-bytes 300 2) 2)))
+ (should (equal 70000 (websocket-get-bytes (websocket-to-bytes 70000 8) 8)))
+ (should-error (websocket-to-bytes 30 3))
+ (should-error (websocket-to-bytes 300 1)))
+
View
@@ -91,6 +91,26 @@ power of 2, up to 8."
"websocket-get-bytes: Unknown N: %s" n)))))
s) :val)))
+(defun websocket-to-bytes (val nbytes)
+ "Encode the integer VAL in NBYTES of data.
+NBYTES much be a power of 2, up to 8."
+ (unless (or (and (< nbytes 8)
+ (< val (expt 2 (* 8 nbytes))))
+ (and (= nbytes 8)
+ (calc-eval "% < 2^(8 * %%)" 'pred val nbytes)))
+ (error "websocket-to-bytes: Value %d could not be expressed in %d bytes"
+ val nbytes))
+ (if (= nbytes 8)
+ (bindat-pack `((:val vec 2 u32))
+ `((:val . [,(/ val 4294967296)
+ ,(mod val 4294967296)])))
+ (bindat-pack
+ `((:val ,(cond ((= nbytes 1) 'u8)
+ ((= nbytes 2) 'u16)
+ ((= nbytes 4) 'u32)
+ (t (error "websocket-to-bytes: Unknown NBYTES: %s" nbytes)))))
+ `((:val . ,val)))))
+
(defun websocket-get-opcode (s)
"Retrieve the opcode from the dword at the start of the frame
given by string."

0 comments on commit 2148c5a

Please sign in to comment.