Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a common lisp (SBCL) vector of a particular type for usage in a usocket?

I'm very new to Common Lisp and I am trying to learn how to program using network sockets. In the common lisp usocket api it specifies that the functions socket-send and socket-receive take a simple-array (unsigned-byte 8) buffer.

I'm too new to lisp to understand how to achieve this in sbcl common lisp. It appears I can use the functions vector and make-array but not simple-array, nor how to specify the type as unsigned-byte 8.

Is something like the following reasonable and typesafe?:

  (let ((buffer (make-array (list-length input))) (input-length (list-length input)) )
    (loop 
      for i upto input-length collect i do
      (setf (nth i buffer) (parse-integer (nth i input))))
    (usocket::socket-send socket buffer input-length)))

If not, how do I accomplish making the kind of buffer I need?

like image 502
durandaltheta Avatar asked Dec 23 '22 15:12

durandaltheta


1 Answers

CL-USER 25 > (make-array 10
                         :element-type '(unsigned-byte 8)
                         :initial-element 0)
#(0 0 0 0 0 0 0 0 0 0)

CL-USER 26 > (describe *)

#(0 0 0 0 0 0 0 0 0 0) is a (SIMPLE-ARRAY (UNSIGNED-BYTE 8) (10))
0      0
1      0
2      0
3      0
4      0
5      0
6      0
7      0
8      0
9      0

Mapping:

CL-USER 32 > (map '(simple-array (unsigned-byte 8) (*)) #'char-code "foobarbaz")
#(102 111 111 98 97 114 98 97 122)

or simpler

CL-USER 33 > (map '(vector (unsigned-byte 8)) #'char-code "foobarbaz")
#(102 111 111 98 97 114 98 97 122)

back:

CL-USER 34 > (map 'string #'code-char #(102 111 111 98 97 114 98 97 122))
"foobarbaz"
like image 158
Rainer Joswig Avatar answered May 30 '23 10:05

Rainer Joswig