added
[rrq/newlisp/misc.git] / misc.lsp
1 ;; This module provides some utility functions.
2
3 (define (prog1 X) X)
4 (global 'prog1)
5
6 (define (die N)
7   (when (args) (write-line 2 (join (map string (args)) " ")))
8   (and (number? N) (exit N)))
9 (global 'die)
10
11 ;; Prepend with C onto S so as to fill width W, if it's a number.
12 (define (pre-fill C S W)
13   (while (and (number? W) (< (length S) W))
14     (setf S (string C S)))
15   S)
16 (global 'pre-fill)
17
18 ;; Make a hex string from a data block pad with "0" to W if non-nil
19 (define (char2hex STR W)
20   (pre-fill "0" (join (map (curry format "%2x") (map char (explode STR)))) W))
21 (global 'char2hex)
22
23 ;; Print binary byte as octal or as ASCII character [32-126]
24 (define (octal-byte x)
25   (if (and (> x 31) (< x 127)) (char x) (format "\\%o" x)))
26 (global 'octal-byte)
27
28 ;; Print string as binary octals
29 (define (octals-string S)
30   (join (map octal-byte (unpack (dup "b" (length S)) S))))
31 (global 'octals-string)
32
33 ;; Return byte code as printable or as decimal number.
34 (define (human-byte B)
35   (if (and (> B 32) (< B 127)) (char B) B))
36 (global 'human-byte)
37
38 ;; Return a packed encoding of a list of bytes, joining its string elements
39 (define (human-bytes BL)
40   (let ((OUT '()) (X nil))
41     (dolist (B (map human-byte BL))
42       (if (string? B) (if X (extend X B) (setf X B))
43         (begin (when (string? X) (push X OUT -1))
44              (push B OUT -1)
45              (setf X nil))))
46     (when (string? X) (push X OUT -1))
47     OUT))
48 (global 'human-bytes)
49
50 "misc.lsp"