id
int64
0
45.1k
file_name
stringlengths
4
68
file_path
stringlengths
14
193
content
stringlengths
32
9.62M
size
int64
32
9.62M
language
stringclasses
1 value
extension
stringclasses
6 values
total_lines
int64
1
136k
avg_line_length
float64
3
903k
max_line_length
int64
3
4.51M
alphanum_fraction
float64
0
1
repo_name
stringclasses
779 values
repo_stars
int64
0
882
repo_forks
int64
0
108
repo_open_issues
int64
0
90
repo_license
stringclasses
8 values
repo_extraction_date
stringclasses
146 values
sha
stringlengths
64
64
__index_level_0__
int64
0
45.1k
exdup_ids_cmlisp_stkv2
sequencelengths
1
47
42,145
seven.lisp
drvdputt_aoc-2022/src/seven.lisp
(load "file.lisp") (load "string.lisp") (defvar lines (read-default-input "seven")) (defvar path "/") ;; use hash table compatible with strings as keys (need equal as the compare function) (defvar dutable (make-hash-table :test 'equal)) (defun dutable/print (dutable) (loop for k being each hash-key of dutable do (print (concatenate 'string k " : " (write-to-string (gethash k dutable)))))) (defun path/add (current-path name) (if (string= name "/") "/" (let ((ends-with-slash (char= (char current-path (- (length current-path) 1)) #\/))) (concatenate 'string (if ends-with-slash current-path (concatenate 'string current-path "/")) name "/")))) ;; needs trailing slash for directories! (defun path/up (path) (let ((result (subseq path 0 (+ 1 (car (last (index-of-all-matches path "/") 2)))))) (if (string= result "") "/" result))) ;; list of all parents of the path. I should add file size to each of these (defun path/all-parents (path) (loop for c across path for i = 0 then (+ 1 i) do (print c) if (char= c #\/) collect (subseq path 0 (+ 1 i)))) ;; add dir relative to given path and set dir size entry to 0 in the table (defun dutable/dir (dutable current-path dir) (setf (gethash (path/add current-path dir) dutable) 0)) ;; register file size in the current dir (defun dutable/file (dutable current-path fsize) ;; (print (list dutable current-path fsize)) (loop for p in (path/all-parents current-path) do (setf (gethash p dutable) (+ (gethash p dutable) fsize)))) (defun process-line (l) (cond ;; dir ((starts-with l "dir") (dutable/dir dutable path (subseq l 4))) ;; cd .. ((starts-with l "$ cd ..") (setq path (path/up path))) ;; cd other ((starts-with l "$ cd") (setq path (path/add path (subseq l 5)))) ;; ls (do nothing) ((starts-with l "$ ls") nil) ;; all the rest is files (should start with number) (t (dutable/file dutable path (first (find-all-int l)))))) ;; initialize manually with "/"! (dutable/dir dutable "/" "/") (loop for l in lines do (print (list l " -> " path)) do (process-line l)) ;; do (dutable/print dutable)) (dutable/print dutable) (print (loop for k being each hash-key of dutable for size = (gethash k dutable) when (<= size 100000) do (print (list k size)) and sum size)) ;; part 2 (defvar total 70000000) (defvar required 30000000) (defvar used (gethash "/" dutable)) (defvar free (- total used)) (defvar to_delete (- required free)) (print (loop for k being each hash-key of dutable for size = (gethash k dutable) when (> size to_delete) minimize size))
2,734
Common Lisp
.lisp
85
28.341176
90
0.645849
drvdputt/aoc-2022
0
0
0
GPL-3.0
9/19/2024, 11:51:06 AM (Europe/Amsterdam)
f95b6a081041720c522a1ce5c0688fedc86c0d443418e67e286e579c834a48c7
42,145
[ -1 ]
42,146
string.lisp
drvdputt_aoc-2022/src/string.lisp
;; find the first character of string 1, that also appears in string 2 (load "~/quicklisp/setup.lisp") (ql:quickload :cl-ppcre) (defun starts-with (s1 s2) (and (>= (length s1) (length s2)) (string= (subseq s1 0 (length s2)) s2))) (defun string-contains-char (s c) (not (null (find c s)))) (defun count-character-dict (s) (let ((hist nil)) (loop for c across s for entry = (assoc c hist) ;; do (print hist) if (not entry) do (setq hist (acons c 1 hist)) else do (rplacd entry (incf (cdr entry)))) hist)) (defun has-duplicate-character (s) (let ((hist nil)) (loop for c across s for entry = (assoc c hist) ;; do (print hist) if (not entry) do (setq hist (acons c 1 hist)) else return t finally (return nil)))) (defun alltrue (values) (print values) (every #'identity values)) (defun strings-contain-char (strings c) (alltrue (mapcar (lambda (s) (string-contains-char s c)) strings))) (defun common-character (s1 s2) (loop for c across s1 when (string-contains-char s2 c) return c)) (defun common-character-multi (strings) (loop for c across (first strings) when (strings-contain-char (subseq strings 1) c) return c)) (defun string-halves (s) (let ((halfway (/ (length s) 2))) (list (subseq s 0 halfway) (subseq s halfway)))) (defun s_to_int (s) (parse-integer s)) (defun find-all-int (s) (mapcar (function parse-integer) (cl-ppcre:all-matches-as-strings "[0-9]+" s))) (defun index-of-all-matches (s expr) ;; collect only even element (start of match, don't need end of match) (loop for i in (cl-ppcre:all-matches expr s) for j = 0 then (+ 1 j) if (evenp j) collect i)) (defun index-of-last-match (s expr) (let ((matches (cl-ppcre:all-matches expr s))) (nth (- (length matches) 2) matches)))
1,831
Common Lisp
.lisp
61
26.688525
72
0.660785
drvdputt/aoc-2022
0
0
0
GPL-3.0
9/19/2024, 11:51:06 AM (Europe/Amsterdam)
5ba99e6415200cf0d6284154b2ca85b96faff01a2ebe1d0037f324e16166baae
42,146
[ -1 ]
42,153
fifteen-example-input.txt
drvdputt_aoc-2022/src/fifteen-example-input.txt
Sensor at x=2, y=18: closest beacon is at x=-2, y=15 Sensor at x=9, y=16: closest beacon is at x=10, y=16 Sensor at x=13, y=2: closest beacon is at x=15, y=3 Sensor at x=12, y=14: closest beacon is at x=10, y=16 Sensor at x=10, y=20: closest beacon is at x=10, y=16 Sensor at x=14, y=17: closest beacon is at x=10, y=16 Sensor at x=8, y=7: closest beacon is at x=2, y=10 Sensor at x=2, y=0: closest beacon is at x=2, y=10 Sensor at x=0, y=11: closest beacon is at x=2, y=10 Sensor at x=20, y=14: closest beacon is at x=25, y=17 Sensor at x=17, y=20: closest beacon is at x=21, y=22 Sensor at x=16, y=7: closest beacon is at x=15, y=3 Sensor at x=14, y=3: closest beacon is at x=15, y=3 Sensor at x=20, y=1: closest beacon is at x=15, y=3
738
Common Lisp
.l
14
51.714286
53
0.689227
drvdputt/aoc-2022
0
0
0
GPL-3.0
9/19/2024, 11:51:06 AM (Europe/Amsterdam)
48b80b1878aafb775d0239ea3483a8fa00ab68c4115d1fe8da7ad92464e69e18
42,153
[ -1 ]
42,155
ten-example-input.txt
drvdputt_aoc-2022/src/ten-example-input.txt
addx 15 addx -11 addx 6 addx -3 addx 5 addx -1 addx -8 addx 13 addx 4 noop addx -1 addx 5 addx -1 addx 5 addx -1 addx 5 addx -1 addx 5 addx -1 addx -35 addx 1 addx 24 addx -19 addx 1 addx 16 addx -11 noop noop addx 21 addx -15 noop noop addx -3 addx 9 addx 1 addx -3 addx 8 addx 1 addx 5 noop noop noop noop noop addx -36 noop addx 1 addx 7 noop noop noop addx 2 addx 6 noop noop noop noop noop addx 1 noop noop addx 7 addx 1 noop addx -13 addx 13 addx 7 noop addx 1 addx -33 noop noop noop addx 2 noop noop noop addx 8 noop addx -1 addx 2 addx 1 noop addx 17 addx -9 addx 1 addx 1 addx -3 addx 11 noop noop addx 1 noop addx 1 noop noop addx -13 addx -19 addx 1 addx 3 addx 26 addx -30 addx 12 addx -1 addx 3 addx 1 noop noop noop addx -9 addx 18 addx 1 addx 2 noop noop addx 9 noop noop noop addx -1 addx 2 addx -37 addx 1 addx 3 noop addx 15 addx -21 addx 22 addx -6 addx 1 noop addx 2 addx 1 noop addx -10 noop noop addx 20 addx 1 addx 2 addx 2 addx -6 addx -11 noop noop noop
980
Common Lisp
.l
146
5.712329
8
0.847722
drvdputt/aoc-2022
0
0
0
GPL-3.0
9/19/2024, 11:51:06 AM (Europe/Amsterdam)
77bf5e4abbac5ee5998eb102707d43ff695833db3513364d8acd441f5e28a4eb
42,155
[ -1 ]
42,158
twentytwo-example-input.txt
drvdputt_aoc-2022/src/twentytwo-example-input.txt
...# .#.. #... .... ...#.......# ........#... ..#....#.... ..........#. ...#.... .....#.. .#...... ......#. 10R5L5R10L4R5L5
189
Common Lisp
.l
13
8.538462
16
0.085714
drvdputt/aoc-2022
0
0
0
GPL-3.0
9/19/2024, 11:51:06 AM (Europe/Amsterdam)
5d8e450f7f336b55956bf5d14fc8579fe528a38cf57f85ab9fbc7444dd5ad1dc
42,158
[ -1 ]
42,161
five-example-input.txt
drvdputt_aoc-2022/src/five-example-input.txt
[D] [N] [C] [Z] [M] [P] 1 2 3 move 1 from 2 to 1 move 3 from 1 to 3 move 2 from 2 to 1 move 1 from 1 to 2
125
Common Lisp
.l
8
12.75
18
0.525862
drvdputt/aoc-2022
0
0
0
GPL-3.0
9/19/2024, 11:51:06 AM (Europe/Amsterdam)
f6d997c55b65110d52426f142ed20ea65c1b62c115f4032aed9aace56044e61e
42,161
[ -1 ]
42,164
twelve-input.txt
drvdputt_aoc-2022/src/twelve-input.txt
abaaacccccccccaaaaaaccccccccccccccccaacccccccccccaacaaaaaaaaaaaaaaaaaccaaaaacccaaaaccccccccccccccccccccccccccccccccccccccccccccccccccccccccaaaaa abaaacccccccccaaaaaacccccccccccccccaaaaccccccccccaaaaaaaacaaaaaaaaaaaccaaaaaaccaaaacccccccccccccccccccccccccccccccccccccccccccccccccccccccaaaaaa abaaaccccccccccaaaaacccccccccccccccaaaacccccccccccaaaaacccaaaaaaaaaacccaaaaaacccaaccccccccccccccaaaaacccccccccccccccccccccccccccccccccccccaaaaaa abccccaaccccccaaaaacccccccccaaaaaccaaaaccccccccccccaaaaacaaaaaaaaacccccaaaaaccccccccccccccccccccaaaaacccccccccccccccccaaaccccaaaccccccccccaaacaa abcccaaaacccccaaaaacccccccccaaaaacccccccccccccccccaaacaaaaaaaaaacccccccaaaaacccccccccccccccccccaaaaaacccccccccccccccccaaaaccaaaaccccccccccccccaa abcccaaaaacacccccccccccccccaaaaaaccccccccccccccccccaaccaaaaacaaaaccccccccccccccccccccccccccccccaaaaaaccccccccccccccccccaaaaaaaacccccccccccccccaa abaaaaaaaaaacccccccccccccccaaaaaaccccccccccccccccccccccaaaacccaaaccccccccccccccccccccccccccccccaaaaaacccccccccccccccciiiiijaaaaccccccccccccccccc abaaaaaaaaaacccccccccccccccaaaaaacccccccccccccccccccccccccccccaaacccccccccccccccccccccccccccccccaaaccccccccccccccccciiiiiijjjaccccccccaaaccccccc abccaaaaaaccccccccccccccccccaaaccccccccccccccccccccccccccccccccacccccccccccaacccccccccccccccccccccccccccccccccccccciiiiioijjjjaaccccccaaaaaacccc abccaaaaaacccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccaaaaaacccccccccccccccccccccccccccccccccccciiinnooojjjjjaaccaaaaaaaacccc abccaaaaaacccccccccccccccccccccccccccccccccccccaacccccaacccccccccccccccccaaaaaacccccccccccccccccccccccccccaaaccccciiinnnoooojjjjjjkkkaaaaaaacccc abcaaaaaaaaccccccccccccccccccccccccccccccccccccaaaccaaaaaaccccaaacccccccccaaaacccccccccccccccccccccccccccccaaaaccciiinnnouooojjjjkkkkkaaaaaccccc abccaccccccccccccccccccaaccccccaccccccccccccaaaaaaaaaaaaaacccaaaacccccccccaaaacccccccccccccccccccccccccccaaaaaacchhinnnttuuooooookkkkkkkaaaccccc abccccccccccccccccccaacaaaccccaaaaaaaaccccccaaaaaaaacaaaaacccaaaacccccccccaccacccccccccccccccccccccccccccaaaaacchhhhnntttuuuooooppppkkkkcaaacccc abccccccccaaacccccccaaaaaccccccaaaaaaccccccccaaaaaacaaaaaccccaaaaccccccccccccccccccccccccccccaccccccccccccaaaaahhhhnnntttxuuuooppppppkkkcccccccc abccccccccaaaacccccccaaaaaaccccaaaaaaccaaacccaaaaaacaaaaaccccccccccccccaaccccccccccccccaaaaaaaacccccccccccaachhhhhnnnntttxxuuuuuuuupppkkkccccccc abccccccccaaaacccccaaaaaaaacccaaaaaaaacaaacacaaaaaaccccccccccccccccccccaacccccccccccccccaaaaaacccccccccccccchhhhmnnnntttxxxxuuuuuuupppkkcccccccc abacccccccaaaacccccaaaaacaaccaaaaaaaaaaaaaaaaaaccaacccccccccccccccccaaaaaaaaccccccccccccaaaaaaccccccccccccchhhhmmmntttttxxxxuyyyuvvpppklcccccccc abacccccccccccccccccacaaaccaaaaaaaaaaaaaaaaaaaccccccccccccccccccccccaaaaaaaacccccccccccaaaaaaaaccccccccccccgghmmmtttttxxxxxxyyyyvvvpplllcccccccc abaccccccccaacccccccccaaaccaaaaaaaacaaaaaaaaaaccccccccccccccccccccccccaaaaccccccccccccaaaaaaaaaaccccccaccccgggmmmtttxxxxxxxyyyyyvvppplllcccccccc SbaaaccccccaaacaaaccccccccaaaaaaaaacaaaaaaaaacccccccccccccccccccccccccaaaaacccccccccccaaaaaaaaaaaaacaaaccaagggmmmtttxxxEzzzzyyyvvppplllccccccccc abaacccccccaaaaaaacccccccaaaaaaacaaccaaaaaaaccccccccccccccaaaccccccccaaaaaacccccccccccacacaaacccaaaaaaacaaagggmmmsssxxxxxyyyyyvvvqqqlllccccccccc abaccccccccaaaaaaccacccaaaaaaaaacccccccaaaaaaccccccccccccaaaaccccccccaaccaacccccccccccccccaaaccccaaaaaaccaagggmmmssssxxwwyyyyyyvvqqqlllccccccccc abaccccccaaaaaaaaccaacaaaccaaaaaacccccaaaaaaaccccccccccccaaaaccccccccccaacccccccccccccccccaacccccaaaaaaaaaaggggmmmssssswwyywyyyyvvqqlllccccccccc abaccccccaaaaaaaaacaaaaacccaaaaaacccccaaacaaaccccccccccccaaaaccccccccaaaaaaccccccccccccaacccccccaaaaaaaaaaaaggggmmmossswwyywwyyvvvqqqllccccccccc abcccccccaaaaaaaaaacaaaaaacaaccccccccaaacccccccccccccccccccccccccccccaaaaaaccccccccccccaaaaacccaaaaaaaaaaaaaaggggoooosswwywwwwvvvvqqqmlccccccccc abccccccccccaaacaaaaaaaaaacccccccccccaaacaccccccccccccccccccccccccccccaaaaccccccccccccaaaaaccccaaacaaacccaaacagggfooosswwwwwrvvvvqqqqmmccccccccc abccccccccccaaacccaaaaaaaacccccccccaacaaaaacccccccccccccccccccccccccccaaaaccccccccccccaaaaaacccccccaaacccaaccccfffooosswwwwrrrrrqqqqqmmccccccccc abccccccccccaacccccccaaccccccccccccaaaaaaaacccccccccccccaaccccccccccccaccaccccccccccccccaaaacccccccaacccccccccccfffoossrwrrrrrrrqqqqmmmccccccccc abccaaaccccccccccccccaacccccccccccccaaaaaccccccccccccaacaacccccccaaaaacccccccccccccccccaacccccccccccccccccccccccfffoossrrrrrnnnmqqmmmmmccccccccc abcaaaaccccccccccccccccccccccccccccccaaaaacccccccccccaaaaacccccccaaaaacccaaaccccccccccccccccccccccccccccccccccccfffooorrrrrnnnnmmmmmmmccccaacccc abcaaaacccccccccccccccccccccccccccccaaacaaccccacccccccaaaaaaccccaaaaaaccccaaaccacccccccccccccccccccccccccccccccccffoooonnnnnnnnmmmmmmccccaaacccc abccaaacccccccccccccccccccccaaaaaccccaaccccaaaacccccaaaaaaaaccccaaaaaaccccaaaaaaaccccccccccccccccaccaccccccccccccfffooonnnnnnddddddddcccaaaccccc abccccccccccccccccccccccccccaaaaaccccccccccaaaaaacccaaaaacaacccaaaaaaaccaaaaaaaacccccccccccccccccaaaaccccccccccccfffeonnnnneddddddddddcaaacccccc abccccccccccaaaccccccccccccaaaaaacccccccccccaaaacccccacaaacccccaacaacccaaaaaaaaacccccccccccccccccaaaacccccccccccccffeeeeeeeeddddddddcccaaacccccc abcccccccccaaaaccccacccccccaaaaaaccccccccccaaaaacccccccaaaacccaaacaccccaaaaaaaaaccccccccccccccccaaaaaaccccccccccccceeeeeeeeedacccccccccccccccccc abaccccccccaaaaccccaaacaaacaaaaaaccccccccccaacaaccccccccaaaacaaaacaaacaaaaaaaaaacccccccccccccaacaaaaaacccccccccccccceeeeeeeaaacccccccccccccccaaa abaaacccccccaaaccccaaaaaaaccaaaccccccccaaacccccccccccccccaaaaaaaacaaaaaaaaaaaaaaacacaaccaaacaaacccaacccccccccccccccccaacccaaaacccccccccccccccaaa abaaaccccccccccccccaaaaaaccccccccccccccaaacccccccccccccccaaaaaaaccaaaaaaccaacccaccaaaaccaaaaaaaccccccccaaccccccccccccccccccaaacccccccccccccccaaa abaaccccccccccccccaaaaaaacccccccccccaaaaaaaaccccccccccccccaaaaaaaaaaaaaacaaaccccccaaaaaccaaaaaaccccccaaaaccccccccccccccccccaaaccccccccccccaaaaaa abaaaccccccccccccaaaaaaaaaacccccccccaaaaaaaacccccccccccaaaaaaaaaaaaaaaaaaacccccccaaaaaacaaaaaaaaaccccaaaaaacccccccccccccccccccccccccccccccaaaaaa
5,945
Common Lisp
.l
41
144
144
1
drvdputt/aoc-2022
0
0
0
GPL-3.0
9/19/2024, 11:51:06 AM (Europe/Amsterdam)
5e4dedbf2a7e98335af138061a26fb9d7906856254d53807551e3de5c408d30b
42,164
[ -1 ]
42,165
eleven-input.txt
drvdputt_aoc-2022/src/eleven-input.txt
Monkey 0: Starting items: 89, 73, 66, 57, 64, 80 Operation: new = old * 3 Test: divisible by 13 If true: throw to monkey 6 If false: throw to monkey 2 Monkey 1: Starting items: 83, 78, 81, 55, 81, 59, 69 Operation: new = old + 1 Test: divisible by 3 If true: throw to monkey 7 If false: throw to monkey 4 Monkey 2: Starting items: 76, 91, 58, 85 Operation: new = old * 13 Test: divisible by 7 If true: throw to monkey 1 If false: throw to monkey 4 Monkey 3: Starting items: 71, 72, 74, 76, 68 Operation: new = old * old Test: divisible by 2 If true: throw to monkey 6 If false: throw to monkey 0 Monkey 4: Starting items: 98, 85, 84 Operation: new = old + 7 Test: divisible by 19 If true: throw to monkey 5 If false: throw to monkey 7 Monkey 5: Starting items: 78 Operation: new = old + 8 Test: divisible by 5 If true: throw to monkey 3 If false: throw to monkey 0 Monkey 6: Starting items: 86, 70, 60, 88, 88, 78, 74, 83 Operation: new = old + 4 Test: divisible by 11 If true: throw to monkey 1 If false: throw to monkey 2 Monkey 7: Starting items: 81, 58 Operation: new = old + 5 Test: divisible by 17 If true: throw to monkey 3 If false: throw to monkey 5
1,278
Common Lisp
.l
48
23.145833
48
0.672935
drvdputt/aoc-2022
0
0
0
GPL-3.0
9/19/2024, 11:51:06 AM (Europe/Amsterdam)
5c645578b7972b4ba030ec6d77a9ce783a7359bb521106f03e52519276afe434
42,165
[ -1 ]
42,167
twentyone-example-input.txt
drvdputt_aoc-2022/src/twentyone-example-input.txt
root: pppw + sjmn dbpl: 5 cczh: sllz + lgvd zczc: 2 ptdq: humn - dvpt dvpt: 3 lfqf: 4 humn: 5 ljgn: 2 sjmn: drzm * dbpl sllz: 4 pppw: cczh / lfqf lgvd: ljgn * ptdq drzm: hmdt - zczc hmdt: 32
191
Common Lisp
.l
15
11.733333
17
0.710227
drvdputt/aoc-2022
0
0
0
GPL-3.0
9/19/2024, 11:51:06 AM (Europe/Amsterdam)
bd2b7a5ad2426297b514430ad36e312fe73312fbc63b58ba60ce85bc5a43f551
42,167
[ -1 ]
42,172
eighteen-example-input.txt
drvdputt_aoc-2022/src/eighteen-example-input.txt
2,2,2 1,2,2 3,2,2 2,1,2 2,3,2 2,2,1 2,2,3 2,2,4 2,2,6 1,2,5 3,2,5 2,1,5 2,3,5
78
Common Lisp
.l
13
5
5
0.6
drvdputt/aoc-2022
0
0
0
GPL-3.0
9/19/2024, 11:51:06 AM (Europe/Amsterdam)
39b466721f296c742094589b84bcf0ca46e739614d547d43b1092395392c6c0d
42,172
[ -1 ]
42,174
sixteen-example-input.txt
drvdputt_aoc-2022/src/sixteen-example-input.txt
Valve AA has flow rate=0; tunnels lead to valves DD, II, BB Valve BB has flow rate=13; tunnels lead to valves CC, AA Valve CC has flow rate=2; tunnels lead to valves DD, BB Valve DD has flow rate=20; tunnels lead to valves CC, AA, EE Valve EE has flow rate=3; tunnels lead to valves FF, DD Valve FF has flow rate=0; tunnels lead to valves EE, GG Valve GG has flow rate=0; tunnels lead to valves FF, HH Valve HH has flow rate=22; tunnel leads to valve GG Valve II has flow rate=0; tunnels lead to valves AA, JJ Valve JJ has flow rate=21; tunnel leads to valve II
562
Common Lisp
.l
10
55.2
60
0.764493
drvdputt/aoc-2022
0
0
0
GPL-3.0
9/19/2024, 11:51:06 AM (Europe/Amsterdam)
845384aa7c3d1c2df8e4e1dd57de2b7b30e7a4db743d7f31c8d7c4f29d90ba58
42,174
[ -1 ]
42,178
eleven-example-input.txt
drvdputt_aoc-2022/src/eleven-example-input.txt
Monkey 0: Starting items: 79, 98 Operation: new = old * 19 Test: divisible by 23 If true: throw to monkey 2 If false: throw to monkey 3 Monkey 1: Starting items: 54, 65, 75, 74 Operation: new = old + 6 Test: divisible by 19 If true: throw to monkey 2 If false: throw to monkey 0 Monkey 2: Starting items: 79, 60, 97 Operation: new = old * old Test: divisible by 13 If true: throw to monkey 1 If false: throw to monkey 3 Monkey 3: Starting items: 74 Operation: new = old + 3 Test: divisible by 17 If true: throw to monkey 0 If false: throw to monkey 1
610
Common Lisp
.l
24
21.958333
32
0.684391
drvdputt/aoc-2022
0
0
0
GPL-3.0
9/19/2024, 11:51:06 AM (Europe/Amsterdam)
db28afb84c7ee2f0b4f26dd9feed58084687fd0ab215e7a625cfc3748d079366
42,178
[ -1 ]
42,182
nine-example-input.txt
drvdputt_aoc-2022/src/nine-example-input.txt
R 4 U 4 L 3 D 1 R 4 D 1 L 5 R 2
32
Common Lisp
.l
8
3
3
0.666667
drvdputt/aoc-2022
0
0
0
GPL-3.0
9/19/2024, 11:51:06 AM (Europe/Amsterdam)
19bfe6b1f8c6def3cc643dc5f2f7e62f7f8a4d656e41d15594e3e0ccea4b6f91
42,182
[ -1 ]
42,183
twentythree-larger-input.txt
drvdputt_aoc-2022/src/twentythree-larger-input.txt
.............. .............. .......#...... .....###.#.... ...#...#.#.... ....#...##.... ...#.###...... ...##.#.##.... ....#..#...... .............. .............. ..............
180
Common Lisp
.l
12
14
14
0
drvdputt/aoc-2022
0
0
0
GPL-3.0
9/19/2024, 11:51:06 AM (Europe/Amsterdam)
ada95017568c51bbb0251460b6babf5cc066a7954ee0e0ea251b56f4d7938fe4
42,183
[ -1 ]
42,186
thirteen-example-input.txt
drvdputt_aoc-2022/src/thirteen-example-input.txt
[1,1,3,1,1] [1,1,5,1,1] [[1],[2,3,4]] [[1],4] [9] [[8,7,6]] [[4,4],4,4] [[4,4],4,4,4] [7,7,7,7] [7,7,7] [] [3] [[[]]] [[]] [1,[2,[3,[4,[5,6,7]]]],8,9] [1,[2,[3,[4,[5,6,0]]]],8,9]
186
Common Lisp
.l
16
10.1875
27
0.337423
drvdputt/aoc-2022
0
0
0
GPL-3.0
9/19/2024, 11:51:06 AM (Europe/Amsterdam)
9bf0149b593d7372700ed4f50d4d1fdd552c5c99774ddcd16b633f5ae83dc539
42,186
[ -1 ]
42,206
day12.lisp
kodmkr_aoc22/day12.lisp
(in-package :day12) (defun read-input (&optional (input-path "./example/day12")) (with-open-file (s input-path) (loop for line = (read-line s nil nil) while line collect line))) (defparameter *start* nil) (defparameter *end* nil) (defparameter *grid* nil) (defparameter *preds* nil) (defun process (ll) (let* ((nrows (length ll)) (ncols (length (first ll))) (grid (make-array `(,nrows ,ncols)))) (loop for l in ll for i from 0 do (loop for c across l for j from 0 if (char= c #\S) do (setf *start* (list i j) (aref grid i j) #\a) else if (char= c #\E) do (setf *end* (list i j) (aref grid i j) #\z) else do (setf (aref grid i j) c))) (setf *grid* grid) grid)) (defun neighbours (grid i j) (destructuring-bind (m n) (array-dimensions grid) (let* ((posns (list (list (1- i) j) (list i (1+ j)) (list (1+ i) j) (list i (1- j)))) (in-bounds-posns (remove-if (lambda (p) (or (or (< (first p) 0) (< (1- m) (first p))) (or (< (second p) 0) (< (1- n) (second p))))) posns))) in-bounds-posns))) (defun hdiff (curr-pos next-pos) (let ((curr-pos-height-val (- (char-code (apply #'aref *grid* curr-pos)) (char-code #\a))) (next-pos-height-val (- (char-code (apply #'aref *grid* next-pos)) (char-code #\a)))) (- next-pos-height-val curr-pos-height-val))) (defun manh (p q) (destructuring-bind ((px py) (qx qy)) (list p q) (+ (abs (- px qx)) (abs (- py qy))))) (defun est (p) (manh p *end*)) (defun remove-high-posns (curr-posn posns) (remove-if (lambda (pos) (< 1 (hdiff curr-posn pos))) posns)) (defun find-path (start grid) (let ((dists (make-hash-table :test #'equal :size 3000)) (preds (make-hash-table :test #'equal :size 3000))) (macrolet ((p (pos) `(gethash ,pos preds)) (d (pos) `(gethash ,pos dists most-positive-fixnum))) (loop initially (setf (d start) 0) (push start q) for q = (sort q #'lt) while q for curr = (pop q) for nbrs = (remove-high-posns curr (neighbours grid (first curr) (second curr))) do (loop for nbr in nbrs if (< (+ (d curr) 1) (d nbr)) do (setf (d nbr) (+ (d curr) 1) (p nbr) curr q (append q (list nbr)))))) (setf *preds* preds) preds)) (defun befs (start grid) (let ((dists (make-hash-table :test #'equal :size 3000)) (seens (make-hash-table :test #'equal :size 3000)) (predecs (make-hash-table :test #'equal :size 3000))) (macrolet ((p (pos) `(gethash ,pos predecs)) (s (pos) `(gethash ,pos seens)) (d (pos) `(gethash ,pos dists most-positive-fixnum))) (loop initially (push start q) (setf (d start) 0 (s start) t) for q = (sort q (lambda (u v) (< (+ (d u) (est u)) (+ (d v) (est v))))) while q for curr = (pop q) for nbrs = (remove-high-posns curr (neighbours grid (first curr) (second curr))) if (equal curr *end*) do (setf *preds* predecs) (return-from befs predecs) else do (loop for nbr in nbrs if (< (+ (d curr) 1) (d nbr)) do (setf (p nbr) curr (d nbr) (+ (d curr) 1)) (when (not (s nbr)) (push nbr q) (setf (s nbr) t))))))) (defun recon-path (start preds &optional (path (list *end*))) (let ((next (gethash (first path) preds))) (if (equal next start) (return-from recon-path path) (recon-path start preds (cons next path))))) ;; 462 (defun sol1 (&optional (input-path "./input/day12")) (-<> (read-input input-path) (process <>) (find-path *start* <>) (recon-path *start* <>) (length <>))) (defun height-map (file grid) (with-canvas (:width 1500 :height 700) (destructuring-bind (m n) (array-dimensions grid) (set-rgb-fill 0.2 0.4 1.0) (set-line-width 0.5) (loop for i below m do (loop for j below n for x = (* j 5) for y = (- 500 (* i 10)) for v = (- (char-code (aref *grid* i j)) (char-code #\a)) do (set-rgba-fill 0.1 (* (/ 1.0 26) v) 0.7 0.7) (rectangle x y 5 10) (fill-path))) (save-png file)))) ;; After inspection of the map, it seems that only the first column ;; needs to be checked: the `b's in the second column are the only ;; ones in the whole map. ;; To get to the goal, we must necessarily pass `b' (from the left). (defun check-as-in-col (col grid) (destructuring-bind (m n) (array-dimensions grid) (declare (ignorable n)) (let ((paths nil)) (loop for i from 0 below m for pos = (list i col) do (let ((preds (befs pos grid))) (push (recon-path pos preds) paths))) paths))) (defun min-path (paths) (loop for path in paths minimize (length path))) ;; takes long ;; 451 (defun sol2 (&optional (input-path "./input/day12")) (-<> (read-input input-path) (process <>) (check-as-in-col 0 <>) (min-path <>)))
5,597
Common Lisp
.lisp
145
28.993103
93
0.508646
kodmkr/aoc22
0
0
0
GPL-3.0
9/19/2024, 11:51:06 AM (Europe/Amsterdam)
7ed5b2bb755c310e8a23d7353816d300dbe23861e7c5eb105a42d96e612ca6ee
42,206
[ -1 ]
42,207
package.lisp
kodmkr_aoc22/package.lisp
;;;; package.lisp (defpackage #:aoc22 (:use #:cl)) (defpackage :day01 (:use :cl :arrow-macros)) (defpackage :day02 (:use :cl :arrow-macros)) (defpackage :day03 (:use :cl :arrow-macros)) (defpackage :day04 (:use :cl :arrow-macros)) (defpackage :day05 (:use :cl :arrow-macros)) (defpackage :day06 (:use :cl :arrow-macros)) (defpackage :day07 (:use :cl :arrow-macros)) (defpackage :day08 (:use :cl :arrow-macros)) (defpackage :day09 (:use :cl :arrow-macros)) (defpackage :day10 (:use :cl :arrow-macros)) (defpackage :day11 (:use :cl :arrow-macros)) (defpackage :day12 (:use :cl :arrow-macros :vecto)) (defpackage :day13 (:use :cl :arrow-macros :1am)) (defpackage :day14 (:use :cl :arrow-macros)) (defpackage :day15 (:use :cl :arrow-macros) (:local-nicknames (:ax :alexandria))) (defpackage :day16 (:use :cl :arrow-macros)) (defpackage :day17 (:use :cl :arrow-macros)) (defpackage :day18 (:use :cl :arrow-macros)) (defpackage :day19 (:use :cl :arrow-macros)) (defpackage :day20 (:use :cl :arrow-macros)) (defpackage :day21 (:use :cl :arrow-macros)) (defpackage :day22 (:use :cl :arrow-macros)) (defpackage :day23 (:use :cl :arrow-macros)) (defpackage :day24 (:use :cl :arrow-macros)) (defpackage :day25 (:use :cl :arrow-macros))
1,306
Common Lisp
.lisp
54
21.685185
39
0.685714
kodmkr/aoc22
0
0
0
GPL-3.0
9/19/2024, 11:51:06 AM (Europe/Amsterdam)
6d80f4421db291c97b0dbfaf31736bfbae3d008f6c5f478e9de9db6790fc6bc0
42,207
[ -1 ]
42,208
day21.lisp
kodmkr_aoc22/day21.lisp
(in-package :day21) (defun processed (line) (let* ((colon-pos (position #\: line)) (monkey-name (subseq line 0 colon-pos)) (opd1-start (+ colon-pos 2))) (cond ((digit-char-p (char line opd1-start)) (list monkey-name (parse-integer (subseq line opd1-start)))) (t (let* ((op-pos (position-if (lambda (c) (or (char= c #\+) (char= c #\-) (char= c #\*) (char= c #\/))) line :start opd1-start)) (opd2-start (+ op-pos 2))) (list monkey-name (subseq line opd1-start (1- op-pos)) (char line op-pos) (subseq line opd2-start))))))) (defun read-input (&optional (input-path "./example/day21")) (with-open-file (s input-path) (loop for line = (read-line s nil nil) while line collect (processed line)))) (defstruct (nd (:print-function (lambda (m stream depth) (declare (ignorable depth)) (format stream "~a (~a)" (nd-name m) (nd-value m))))) (name "" :type string) (value nil) (parent nil) (left nil) (op #'identity) (right nil)) (defun func-from-char (c) (case c (#\+ #'+) (#\- #'-) (#\* #'*) (#\/ #'/) ;; for pt 2 (#\= #'=))) (defun build-tree (nodes) (labels ((aux (name nodes) (alexandria:if-let (l (find name nodes :test #'string= :key #'first)) (case (length (rest l)) (1 (make-nd :name name :value (second l))) (otherwise (let ((n (make-nd :name name :op (third l) :left (aux (second l) nodes) :right (aux (fourth l) nodes)))) (setf (nd-value n) nil (nd-parent (nd-left n)) n (nd-parent (nd-right n)) n) n)))))) (aux "root" nodes))) (defun leafp (node) (and (null (nd-left node)) (null (nd-right node)))) (defun eval-tree (node) (cond ((leafp node) (nd-value node)) (t (let ((lval (eval-tree (nd-left node))) (rval (eval-tree (nd-right node)))) (funcall (func-from-char (nd-op node)) lval rval))))) ;; assumption: all non-leaves have two children and an op ;; 169525884255464 (defun sol1 (&optional (input-path "./input/day21")) (-<> (read-input input-path) (build-tree <>) (eval-tree <>))) (defun modify-tree-base (tree-base) (loop for node in tree-base if (string= (first node) "root") collect (list (first node) (second node) #\= (fourth node)) else if (string= (first node) "humn") collect (list (first node) :xxx) else collect node)) (defun normalize (tree) (cond ((leafp tree) (nd-value tree)) (t (let ((val-left (normalize (nd-left tree))) (val-right (normalize (nd-right tree)))) (when (and (integerp val-left) (integerp val-right)) (let ((nd-val (funcall (func-from-char (nd-op tree)) val-left val-right))) (setf (nd-left tree) nil (nd-right tree) nil (nd-value tree) nd-val) nd-val)))))) (defun build-expression (tree) (cond ((leafp tree) (nd-value tree)) (t (let ((val-left (build-expression (nd-left tree))) (val-right (build-expression (nd-right tree))) (op (if (functionp (nd-op tree)) #\? (nd-op tree)))) (list op val-left val-right))))) (defun inv (op) (case op (#\* #\/) (#\/ #\*) (#\+ #\-) (#\- #\+) (#\= #\=))) (defun solve (eqn) (destructuring-bind (value expr) (if (integerp (second eqn)) (list (second eqn) (third eqn)) (list (third eqn) (second eqn))) (labels ((aux (v e) (when (eql e :XXX) (return-from aux v)) (let ((op (first e))) (if (integerp (third e)) (aux (funcall (func-from-char (inv op)) v (third e)) (second e)) (if (or (char= op #\+) (char= op #\*)) (aux (funcall (func-from-char (inv op)) v (second e)) (third e)) (let ((f (func-from-char op))) (aux (funcall f (funcall f v (second e))) (third e)))))))) (aux value expr)))) ;; 3247317268284 (defun sol2 (&optional (input-path "./input/day21")) (let ((tr (-<> (read-input input-path) (modify-tree-base <>) (build-tree <>)))) (normalize tr) (-<> (build-expression tr) (solve <>))))
4,972
Common Lisp
.lisp
127
27.070866
124
0.463051
kodmkr/aoc22
0
0
0
GPL-3.0
9/19/2024, 11:51:06 AM (Europe/Amsterdam)
5c47839336a7c99c16c967d83232d7a5fa86c77c70902b68e3c9041663d2d7c4
42,208
[ -1 ]
42,209
day05.lisp
kodmkr_aoc22/day05.lisp
(in-package :day05) (defun read-input (&optional (input-path "./example/day05")) (with-open-file (s input-path) (let ((config (loop for line = (read-line s nil nil) while (not (string= "" line)) collect line)) (instructions (loop for line = (read-line s nil nil) while line collect line))) (list (nreverse config) instructions)))) (defun index-positions (index-str) (loop for c across index-str for i from 0 if (alphanumericp c) collect i)) (defun sections-from-indices (indices) (loop for i in indices collect (list (1- i) (+ i 2)))) (defun process-input (config-n-instructions) (destructuring-bind (config instructions) config-n-instructions (let* ((index-positions (index-positions (first config))) (ary (make-array (length index-positions) :element-type 'list :initial-element nil)) (instrs (loop for instr in instructions collect (ppcre:register-groups-bind ((#'parse-integer qty from to)) ("move (\\d+) from (\\d+) to (\\d+)" instr) ;; decrement `from' and `to' right now ;; to avoid dealing with adjustments later (list qty (1- from) (1- to)))))) (symbol-macrolet ((a (aref ary i))) ;; abbreviation (loop for cts in (rest config) do (loop for idx in index-positions for i from 0 for c = (subseq cts idx (1+ idx)) if (null a) do (setf a (list c)) else if (not (string= "" (string-trim " " c))) do (setf a (append a (list c)))))) (list ary instrs)))) (defun split-at (list n) (values (subseq list 0 n) (subseq list n))) (defun execute (state-n-instructions &key keep-order) (destructuring-bind (state instructions) state-n-instructions (symbol-macrolet ((st (aref state to)) (sf (aref state from))) (loop for (qty from to) in instructions for len = (length sf) do (multiple-value-bind (init tail) (split-at sf (- len qty)) (setf sf init st (append st (if keep-order tail (reverse tail))))))) state)) (defun read-tops (state) (loop for s across state for last-index = (1- (length s)) collect (nth last-index s))) ;; WSFTMRHPP (defun sol1 (&optional (input-path "./input/day05")) (-<> (read-input input-path) (process-input <>) (execute <>) (read-tops <>) (apply #'concatenate 'string <>))) ;; GSLCMFBRP (defun sol2 (&optional (input-path "./input/day05")) (-<> (read-input input-path) (process-input <>) (execute <> :keep-order t) (read-tops <>) (apply #'concatenate 'string <>)))
2,961
Common Lisp
.lisp
69
32.115942
95
0.544225
kodmkr/aoc22
0
0
0
GPL-3.0
9/19/2024, 11:51:06 AM (Europe/Amsterdam)
e739e492eb402918e76b457f152b79f67aad7576af3194376819fcf156847c1a
42,209
[ -1 ]
42,210
day03.lisp
kodmkr_aoc22/day03.lisp
(in-package :day03) (defun read-input (&optional (input-path "./example/day03")) (with-open-file (s input-path) (loop for line = (read-line s nil nil) while line collect line))) (defun compartments (rucksack) (let* ((l (length rucksack)) (compartment-size (floor l 2))) (list (subseq rucksack 0 compartment-size) (subseq rucksack compartment-size)))) (defun shared-item (compartments) (let ((c1 (coerce (first compartments) 'list)) (c2 (coerce (second compartments) 'list))) (intersection c1 c2 ))) (defun priority (item) (+ (- (char-code item) (if (lower-case-p item) 96 64)) (if (lower-case-p item) 0 26))) (defun sol1 (&optional (input-path "./input/day03")) (-<> (read-input input-path) (loop for rucksack in <> for compartments = (compartments rucksack) for shared-item = (first (shared-item compartments)) sum (priority shared-item)))) (defun find-badge (rucksacks) (loop for (u v w) on rucksacks by #'cdddr for items-u = (coerce u 'list) for items-v = (coerce v 'list) for items-w = (coerce w 'list) collect (first (remove-duplicates (intersection (intersection items-u items-v) items-w))))) (defun sol2 (&optional (input-path "./input/day03")) (-<> (read-input input-path) (find-badge <>) (mapcar #'priority <>) (apply #'+ <>)))
1,408
Common Lisp
.lisp
35
34.342857
81
0.626647
kodmkr/aoc22
0
0
0
GPL-3.0
9/19/2024, 11:51:06 AM (Europe/Amsterdam)
f5f46be740010eb4f03fdde3a5e2ec16ad6282eb5d384d33f3261d55afc4e194
42,210
[ -1 ]
42,211
day13.lisp
kodmkr_aoc22/day13.lisp
(in-package :day13) (defun read-input (&optional (input-path "./example/day13")) (with-open-file (s input-path) (loop with pairs with curr for line = (read-line s nil nil) while line if (string= "" line) do (push (nreverse curr) pairs) (setf curr nil) else do (push line curr) finally (push (nreverse curr) pairs) (return (nreverse pairs))))) (defun process (lls) (loop for (l1 l2) in lls for n-l1 = (-<> l1 (substitute #\Space #\, <>) (substitute #\( #\[ <>) (substitute #\) #\] <>)) for n-l2 = (-<> l2 (substitute #\Space #\, <>) (substitute #\( #\[ <>) (substitute #\) #\] <>)) collect (list (with-input-from-string (stream n-l1) (read stream nil nil)) (with-input-from-string (stream n-l2) (read stream nil nil))))) ;; = tests ====================== (test regular-lists-of-same-length (is (eq t (apply #'p< '((1 1 3 1 1) (1 1 5 1 1))))) (is (eq nil (apply #'p< '((1 1 3 1 1) (1 1 3 1 1))))) (is (eq t (apply #'p< '(((4 4) 4 4) ((4 4) 4 4 4))))) (is (eq nil (apply #'p< '((7 7 7 7) (7 7 7))))) (is (eq t (apply #'p< '((7 7 7) (7 7 7 7)))))) (test list-length-tie-break (is (eq t (apply #'p< '(((1) (2 3 4)) ((1) 4))))) (is (eq t (apply #'p< '(NIL (3)))))) (test type-mismatch-ensure-list (is (eq nil (apply #'p< '((9) ((8 7 6))))))) (test nesting (is (eq nil (apply #'p< '(((NIL)) (NIL))))) (is (eq nil (apply #'p< '((1 (2 (3 (4 (5 6 7)))) 8 9) (1 (2 (3 (4 (5 6 0)))) 8 9))))) (is (eq t (apply #'p< '((1 (2 (3 (4 (5 6)))) 8 9) (1 (2 (3 (4 (5 6 0)))) 8 9))))) (is (eq nil (apply #'p< '((1 (2 (3 (4 (5 6 0)))) 8 9) (1 (2 (3 (4 (5 6 0)))) 8 8)))))) ;; ============================== (defun p< (a b) (cond ((and (integerp a) (integerp b)) (cond ((< a b) -1) ((= a b) 0) ((> a b) 1))) ((and (integerp a) (consp b)) (p< (list a) b)) ((and (consp a) (integerp b)) (p< a (list b))) ((and (null a) (null b)) 0) ((and (null a) (not (null b))) -1) ((and (not (null a)) (null b)) 1) ((and (consp a) (consp b)) (let ((res (p< (car a) (car b)))) (cond ((minusp res) -1) ((plusp res) 1) ((zerop res) (p< (cdr a) (cdr b)))))))) (defun indices-in-order (lls) (loop for (a b) in lls for i from 1 if (minusp (p< a b)) collect i)) ;; 5393 (defun sol1 (&optional (input-path "./input/day13")) (-<> (read-input input-path) (process <>) (indices-in-order <>) (reduce #'+ <>))) (defun concat (pairs) (loop for pair in pairs nconc pair)) ;; 26712 (defun sol2 (&optional (input-path "./input/day13")) (-<> (read-input input-path) (append <> (list (list "[[2]]" "[[6]]"))) (process <>) (concat <>) (sort <> (lambda (x y) (case (p< x y) ((-1 0) t) (otherwise nil)))) (let ((two-pos (1+ (position '((2)) <> :test #'equal))) (six-pos (1+ (position '((6)) <> :test #'equal)))) (* two-pos six-pos))))
3,347
Common Lisp
.lisp
87
30.011494
88
0.431825
kodmkr/aoc22
0
0
0
GPL-3.0
9/19/2024, 11:51:06 AM (Europe/Amsterdam)
39932a5ac3bb9037f2b9568ed317d7f1540eae047f9474a5c575a8f16729a3d5
42,211
[ -1 ]
42,212
day04.lisp
kodmkr_aoc22/day04.lisp
(in-package :day04) (defun processed (line) (ppcre:register-groups-bind ((#'parse-integer r1s r1e r2s r2e)) ("(\\d+)-(\\d+),(\\d+)-(\\d+)" line) (list (list r1s r1e) (list r2s r2e)))) (defun read-input (&optional (input-path "./example/day04")) (with-open-file (s input-path) (loop for line = (read-line s nil nil) while line collect (processed line)))) (defun contained (r1 r2) (destructuring-bind ((r1s r1e) (r2s r2e)) (list r1 r2) (and (<= r1s r2s r1e) (<= r1s r2e r1e)))) ;; 562 (defun sol1 (&optional (input-path "./input/day04")) (-<> (read-input input-path) (loop for (r1 r2) in <> if (or (contained r1 r2) (contained r2 r1)) count 1))) (defun overlap-p (r1 r2) (destructuring-bind ((r1s r1e) (r2s r2e)) (list r1 r2) (declare (ignorable r2e)) (or (contained r1 r2) (<= r1s r2s r1e)))) ;; 924 (defun sol2 (&optional (input-path "./input/day04")) (-<> (read-input input-path) (loop for (r1 r2) in <> if (or (overlap-p r1 r2) (overlap-p r2 r1)) count 1)))
1,117
Common Lisp
.lisp
32
29
65
0.569045
kodmkr/aoc22
0
0
0
GPL-3.0
9/19/2024, 11:51:06 AM (Europe/Amsterdam)
4d3dda142aa9be7b71a27a69dcc26964725f0f9f4e29ddaecef07287c7aab966
42,212
[ -1 ]
42,213
day01.lisp
kodmkr_aoc22/day01.lisp
(in-package :day01) (defun read-input (input-string) (with-open-file (s input-string) (let ((res nil)) (loop with tmp for line = (read-line s nil nil) while line if (string= line "") do (push tmp res) (setf tmp nil) else do (push (parse-integer line) tmp)) res))) (defun sum-up (ll) (mapcar (lambda (l) (apply #'+ l)) ll)) (defun lmax (l) (loop for v in l maximize v)) ;; 70613 (defun sol1 (&optional (input-string "./input/day01")) (-<> (read-input input-string) (sum-up <>) (lmax <>))) (defun top-three (l) (let ((srtd (sort l #'>))) (+ (first srtd) (second srtd) (third srtd)))) ;; 205805 (defun sol2 (&optional (input-string "./input/day01")) (-<> (read-input input-string) (sum-up <>) (top-three <>)))
887
Common Lisp
.lisp
34
19.794118
54
0.526564
kodmkr/aoc22
0
0
0
GPL-3.0
9/19/2024, 11:51:06 AM (Europe/Amsterdam)
17673791719d0b97c6f6eb41f89f46240379958ca744399ecee6619f4ac2f815
42,213
[ -1 ]
42,214
day06.lisp
kodmkr_aoc22/day06.lisp
(in-package :day06) (defun read-input (&optional (input-path "./example/day0601")) (let ((s (alexandria:read-file-into-string input-path))) s)) (defun process (signal &key (view-width 4)) (let ((len (length signal))) (loop for i from 0 below (- len view-width) for view = (make-array view-width :displaced-to signal :displaced-index-offset i) for uniq = (remove-duplicates view :test #'char-equal) if (= view-width (length uniq)) do (return-from process (+ i view-width))))) ;; 1538 (defun sol1 (&optional (input-path "./input/day06")) (-<> (read-input input-path) (process <>))) ;; 2315 (defun sol2 (&optional (input-path "./input/day06")) (-<> (read-input input-path) (process <> :view-width 14)))
814
Common Lisp
.lisp
20
34
70
0.6
kodmkr/aoc22
0
0
0
GPL-3.0
9/19/2024, 11:51:06 AM (Europe/Amsterdam)
9be753b5124530f9d1d0587f88853a01c47dc6aa59eb21dd860d34989eb3fe4a
42,214
[ -1 ]
42,215
aoc22.lisp
kodmkr_aoc22/aoc22.lisp
;;;; aoc22.lisp (in-package #:aoc22) (defun run (&key day sol) "Runs the solution SOL{sol} in package DAY{day}, where `{day}` is a two digit number from 1 to 25 and `{sol}` is either the number 1 or the number 2. EXAMPLE. (run 1 1) ; => causes DAY01:SOL1 to be run" (funcall (find-symbol (format nil "SOL~d" sol) (format nil "DAY~2,'0,d" day))))
362
Common Lisp
.lisp
9
37.444444
81
0.661891
kodmkr/aoc22
0
0
0
GPL-3.0
9/19/2024, 11:51:06 AM (Europe/Amsterdam)
284cec542286602110a75a827b89d3f5de57770114c5ec553c7ada4e7b6f36a1
42,215
[ -1 ]
42,216
day08.lisp
kodmkr_aoc22/day08.lisp
(in-package :day08) (defun read-input (&optional (input-path "./example/day08")) (with-open-file (s input-path) (loop for line = (read-line s nil nil) while line collect (mapcar (lambda (c) (- (char-code c) (char-code #\0))) (coerce line 'list))))) (defun build-grid (ll) (let* ((m (length ll)) (n (length (first ll))) (grid (make-array (list m n) :element-type 'list :initial-element nil))) (loop for row in ll for i from 0 do (loop for e in row for j from 0 do (setf (aref grid i j) (list e 0)))) grid)) (defun check-visibilty (grid) (let ((cnt 0)) (destructuring-bind (m n) (array-dimensions grid) (macrolet ((h (i j) `(first (aref grid ,i ,j))) (v (i j) `(second (aref grid ,i ,j)))) (loop for i below m do (loop for j below n if (or (= i 0) (= i (1- m)) (= j 0) (= j (1- n))) do (setf (v i j) 1) (incf cnt))) (loop for i from 1 below (1- m) do (loop for j from 1 below (1- n) for curr-h = (h i j) if (or (loop for ii from 0 below i always (< (h ii j) curr-h)) ;; north (loop for ii from (1- m) downto (1+ i) always (< (h ii j) curr-h)) ;; south (loop for jj from (1- n) downto (1+ j) always (< (h i jj) curr-h)) ;; east (loop for jj from 0 below j always (< (h i jj) curr-h)));; west do (setf (v i j) 1) (incf cnt))) cnt)))) ;; 1708 (defun sol1 (&optional (input-path "./input/day08")) (-<> (read-input input-path) (build-grid <>) (check-visibilty <>))) (defun scenic-score (grid) (destructuring-bind (m n) (array-dimensions grid) (macrolet ((h (i j) `(first (aref grid ,i ,j))) (ss (i j) `(second (aref grid ,i ,j)))) (let ((max 0)) (loop for i from 0 below m do (loop for j from 0 below n do (let ((u (loop for ii from (1- i) downto 0 count 1 if (>= (h ii j) (h i j)) do (loop-finish))) (l (loop for jj from (1- j) downto 0 count 1 if (>= (h i jj) (h i j)) do (loop-finish))) (r (loop for jj from (1+ j) below n count 1 if (>= (h i jj) (h i j)) do (loop-finish))) (d (loop for ii from (1+ i) below m count 1 if (>= (h ii j) (h i j)) do (loop-finish)))) (setf (ss i j) (* u l r d) max (if (> max (ss i j)) max (ss i j)))))) (values max))))) ;; 504000 (defun sol2 (&optional (input-path "./input/day08")) (-<> (read-input input-path) (build-grid <>) (scenic-score <>)))
3,056
Common Lisp
.lisp
71
29.971831
98
0.437059
kodmkr/aoc22
0
0
0
GPL-3.0
9/19/2024, 11:51:06 AM (Europe/Amsterdam)
00686a2239a85852db033fba4c6601848b93d68cdb3e5b3997cb89addca4c1e8
42,216
[ -1 ]
42,217
day09.lisp
kodmkr_aoc22/day09.lisp
(in-package :day09) (defun map-dir (dir) (alexandria:switch (dir :test #'char=) (#\U #c(0 1)) (#\D #c(0 -1)) (#\L #c(-1 0)) (#\R #c(1 0)))) (defun extracted (line) (ppcre:register-groups-bind (dir (#'parse-integer amount)) ("(R|U|L|D) (\\d+)" line) (list (map-dir (char dir 0)) amount))) (defun read-input (&optional (input-path "./example/day09")) (with-open-file (s input-path) (loop for line = (read-line s nil nil) while line collect (extracted line)))) (defun touchingp (x y) (let ((r (- x y))) (or (= r #c(1 1)) (= r #c(1 0)) (= r #c(1 -1)) (= r #c(0 -1)) (= r #c(-1 -1)) (= r #c(-1 0)) (= r #c(-1 1)) (= r #c(0 1)) (= r #c(0 0))))) (defun same-row-or-col-p (x y) (or (zerop (- (realpart x) (realpart y))) (zerop (- (imagpart x) (imagpart y))))) (defun diag (z) (let ((r (realpart z)) (i (imagpart z))) (complex (* (signum r) (if (zerop r) 0 (floor r r))) (* (signum i) (if (zerop i) 0 (floor i i)))))) ;; after part 2 (defun execute (instrs &key (rope-length 10)) (let* ((rope (make-array rope-length :initial-element #c(0 0))) (rl (length rope)) (mi (1- rl)) (tposs nil)) (macrolet ((r (i) `(aref rope ,i))) (loop for (d amt) in instrs do (loop repeat amt do (incf (r 0) d) (loop for i from 0 below mi do (when (not (touchingp (r i) (r (1+ i)))) (incf (r (1+ i)) (diag (- (r i) (r (1+ i))))))) (pushnew (r mi) tposs :test #'=)))) tposs)) ;; 5902 (defun sol1 (&optional (input-path "./input/day09")) (-<> (read-input input-path) (execute <> :rope-length 2) (length <>))) ;; 2445 (defun sol2 (&optional (input-path "./input/day09")) (-<> (read-input input-path) (execute <> :rope-length 10) (length <>)))
1,908
Common Lisp
.lisp
60
25.85
65
0.500816
kodmkr/aoc22
0
0
0
GPL-3.0
9/19/2024, 11:51:06 AM (Europe/Amsterdam)
4bfedc1356cc3439be270e6d67443b34462ee335ea463cc1461fe5198f728c5c
42,217
[ -1 ]
42,218
day07.lisp
kodmkr_aoc22/day07.lisp
(in-package :day07) (defstruct node (name "" :type string) (size 0 :type integer) (parent nil) (children nil :type list)) (defun leaf-p (node) (null (node-children node))) (defun read-input (&optional (input-path "./example/day07")) (with-open-file (s input-path) (loop for line = (read-line s nil nil) while line collect line))) (defun build-tree (instrs) (let ((tree (make-node :name "-"))) (push (make-node :name "/" :parent tree) (node-children tree)) (loop for instr in instrs for expl = (ppcre:split #\Space instr) with current = tree do (alexandria:switch ((first expl) :test #'string=) ("$" (alexandria:switch ((second expl) :test #'string=) ("ls" #| do noting |# ) ("cd" (if (string= (third expl) "..") (setf current (node-parent current)) (let* ((dnam (third expl)) (next (find dnam (node-children current) :test #'string= :key #'node-name))) (setf current next)))))) ("dir" (let* ((dnam (second expl)) (nn (make-node :name dnam :parent current))) (push nn (node-children current)))) (t (let* ((dnam (second expl)) (nn (make-node :name dnam :parent current :size (parse-integer (first expl))))) (push nn (node-children current)))))) tree)) (defun walk-tree (tree &optional (action #'identity)) (if (leaf-p tree) (progn (funcall action tree) (node-size tree)) (let ((sz (loop for c in (node-children tree) sum (walk-tree c action)))) (setf (node-size tree) sz) (funcall action tree) sz))) ;; 1447046 (defun sol1 (&optional (input-path "./input/day07")) (let ((s 0) (tree (build-tree (read-input input-path)))) (walk-tree tree (lambda (n) (when (and (not (leaf-p n)) (< (node-size n) 100000)) (incf s (node-size n))))) s)) ;; 578710 (defun sol2 (&optional (input-path "./input/day07")) (let ((tree (build-tree (read-input input-path)))) (walk-tree tree) ;; to initially get sizes into all nodes (let* ((t-size (node-size tree)) (tgt-size (- 70000000 t-size)) (candidates nil)) (walk-tree tree (lambda (n) (when (and (not (leaf-p n)) (> (+ (node-size n) tgt-size) 30000000)) (push (node-size n) candidates)))) (first (sort candidates #'<)))))
2,725
Common Lisp
.lisp
61
32.786885
115
0.508845
kodmkr/aoc22
0
0
0
GPL-3.0
9/19/2024, 11:51:06 AM (Europe/Amsterdam)
1a2b11683369d3f3ffe294316187271b95e2ffd3537ec6f771b45ce7ccd80912
42,218
[ -1 ]
42,219
day02.lisp
kodmkr_aoc22/day02.lisp
(in-package :day02) (defun read-input (input-string) (with-open-file (s input-string) (loop for line = (read-line s nil nil) while line collect (ppcre:split " " line)))) (defun check-round (opp me) (alexandria:switch ((list opp me) :test #'equal) ('("A" "X") 3) ('("A" "Y") 6) ('("A" "Z") 0) ('("B" "X") 0) ('("B" "Y") 3) ('("B" "Z") 6) ('("C" "X") 6) ('("C" "Y") 0) ('("C" "Z") 3) ;; added after part 2 ('("A" "A") 3) ('("A" "B") 6) ('("A" "C") 0) ('("B" "A") 0) ('("B" "B") 3) ('("B" "C") 6) ('("C" "A") 6) ('("C" "B") 0) ('("C" "C") 3) )) (defun value-of (me) (alexandria:switch (me :test #'string=) ("X" 1) ("Y" 2) ("Z" 3) ;; added after part 2 ("A" 1) ("B" 2) ("C" 3) )) (defun collect-scores (rounds) (loop for round in rounds collect (+ (check-round (first round) (second round)) (value-of (second round))))) (defun score (scores) (apply #'+ scores)) (defun find-move-to-play (opp strategy) (alexandria:switch ((list opp strategy) :test #'equal) ('("A" "X") "C") ('("A" "Y") "A") ('("A" "Z") "B") ('("B" "X") "A") ('("B" "Y") "B") ('("B" "Z") "C") ('("C" "X") "B") ('("C" "Y") "C") ('("C" "Z") "A"))) (defun apply-strategy (rounds) (loop for (o s) in rounds collect (list o (find-move-to-play o s)))) ;; 14163 (defun sol1 (&optional (input-path "./input/day02")) (-<> (read-input input-path) (collect-scores <>) (score <>))) ;; 12091 (defun sol2 (&optional (input-path "./input/day02")) (-<> (read-input input-path) (apply-strategy <>) (collect-scores <>) (score <>)))
1,730
Common Lisp
.lisp
69
20.391304
61
0.466707
kodmkr/aoc22
0
0
0
GPL-3.0
9/19/2024, 11:51:06 AM (Europe/Amsterdam)
0da0b711a0f39fc7835aefcf6941428896f3b5249370036dda918c5448c9a602
42,219
[ -1 ]
42,220
day10.lisp
kodmkr_aoc22/day10.lisp
(in-package :day10) (defclass instr () ((name :initform "" :initarg :name :reader name) (cycles :initform 0 :initarg :cycles :accessor cycles) (operands :initform nil :initarg :operands :accessor operands))) (defclass noop (instr) ((name :initform "noop") (cycles :initform 1))) (defclass addx (instr) ((name :initform "addx") (cycles :initform 2))) (defmethod print-object ((o instr) stream) (format stream "#<~s ~s ~s>" (name o) (operands o) (cycles o))) ;; replaces `addx' taking two cycles with `noop' and `addx' that takes ;; one cycle (defun extract-instrs (line) (if (char= (char line 0) #\n) (list (make-instance 'noop)) (let* ((split-point (position-if (lambda (c) (char= c #\Space)) line)) (num-string (subseq line (1+ split-point))) (num (parse-integer num-string))) (list (make-instance 'noop) (make-instance 'addx :operands (list num)))))) (defun read-input (&optional (input-path "./example/day10")) (with-open-file (s input-path) (loop for line = (read-line s nil nil) while line nconc (extract-instrs line)))) (defclass context () ((cycle :initform 1 :initarg :cycle :accessor cycle) (reg :initform 1 :initarg reg :accessor reg))) (defmethod print-object ((o context) stream) (format stream "#<~s ~s ~s>" "ctx" (cycle o) (reg o))) (defmethod one-step ((instr noop) (ctx context)) (incf (cycle ctx))) (defmethod one-step ((instr addx) (ctx context)) (incf (reg ctx) (first (operands instr))) (incf (cycle ctx))) (defun exec (instrs) (let ((ctx (make-instance 'context)) (sample-times (list 20 60 100 140 180 220)) (signal-strengths nil)) (loop for instr in instrs do (when (and sample-times (= (cycle ctx) (first sample-times))) (pop sample-times) (push (* (cycle ctx) (reg ctx)) signal-strengths)) (one-step instr ctx)) signal-strengths)) ;; 13760 (defun sol1 (&optional (input-path "./input/day10")) (-<> (read-input input-path) (exec <>) (reduce #'+ <>))) (defun draw-pixels (instrs) (let* ((ctx (make-instance 'context)) (screen (make-array (* 6 40) :element-type 'character :initial-element #\.))) (loop for instr in instrs for cyc = (1- (cycle ctx)) for reg = (reg ctx) for sprite = (list (1- reg) reg (1+ reg)) do (when (member (mod cyc 40) sprite) (setf (aref screen cyc) #\#)) (one-step instr ctx)) screen)) (defun render (screen) (loop for i below 6 do (loop for j below 40 do (format t "~a" (aref screen (+ (* i 40) j)))) (terpri))) ;; RFKZCPEF (defun sol2 (&optional (input-path "./input/day10")) (-<> (read-input input-path) (draw-pixels <>) (render <>)))
2,800
Common Lisp
.lisp
73
33.260274
86
0.613201
kodmkr/aoc22
0
0
0
GPL-3.0
9/19/2024, 11:51:06 AM (Europe/Amsterdam)
967da870099e6483d38f0d2b1b94769441cf701b36d193b1a2debbda93e357e0
42,220
[ -1 ]
42,221
aoc22.asd
kodmkr_aoc22/aoc22.asd
;;;; aoc22.asd (asdf:defsystem #:aoc22 :description "???" :depends-on ("cl-ppcre" "arrow-macros" "alexandria" "serapeum" "anaphora" "1am" "vecto" "bit-smasher") :version "0.0.1" :serial t :components ((:file "package") (:file "day01") (:file "day02") (:file "day03") (:file "day04") (:file "day05") (:file "day06") (:file "day07") (:file "day08") (:file "day09") (:file "day10") (:file "day11") (:file "day12") (:file "day13") (:file "day14") (:file "day15") (:file "day16") (:file "day17") (:file "day18") (:file "day19") (:file "day20") (:file "day21") (:file "day22") (:file "day23") (:file "day24") (:file "day25") (:file "aoc22")))
1,145
Common Lisp
.asd
40
14.925
32
0.344828
kodmkr/aoc22
0
0
0
GPL-3.0
9/19/2024, 11:51:06 AM (Europe/Amsterdam)
309be8e720323b71a7bf58a2dc6f3327220892765e71f0ece4691bff4c3c0a52
42,221
[ -1 ]
42,252
main.lisp
hraban_leetcode-1657-cl-nix/main.lisp
;; Copyright © 2022 Hraban Luyat ;; ;; This program is free software: you can redistribute it and/or modify ;; it under the terms of the GNU Affero General Public License as published ;; by the Free Software Foundation, version 3 of the License. ;; ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU Affero General Public License for more details. ;; ;; You should have received a copy of the GNU Affero General Public License ;; along with this program. If not, see <https://www.gnu.org/licenses/>. (uiop:define-package #:leetcode-1657 (:nicknames #:leetcode-1657/main) (:use #:cl #:arrow-macros) (:import-from #:fset #:bag #:convert) (:export #:main)) (in-package #:leetcode-1657/main) (defun normalize (w) (cons (->> w (convert 'fset:set)) (->> w (convert 'bag) (convert 'fset:map) (convert 'list) (mapcar #'cdr) (convert 'bag)))) (defun main-aux (word1 word2) (let ((res (fset:equal? (normalize word1) (normalize word2)))) (format T "~:[false~;true~]~%" res))) (defun main () (apply #'main-aux (uiop:command-line-arguments)))
1,304
Common Lisp
.lisp
32
36.09375
75
0.664562
hraban/leetcode-1657-cl-nix
0
0
0
AGPL-3.0
9/19/2024, 11:51:06 AM (Europe/Amsterdam)
2819e4ea7420c202ad6ce2b26f938fdae58b42d2f3dc883ef76ad63ef7f510da
42,252
[ -1 ]
42,253
leetcode-1657.asd
hraban_leetcode-1657-cl-nix/leetcode-1657.asd
;; Copyright © 2022 Hraban Luyat ;; ;; This program is free software: you can redistribute it and/or modify ;; it under the terms of the GNU Affero General Public License as published ;; by the Free Software Foundation, version 3 of the License. ;; ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU Affero General Public License for more details. ;; ;; You should have received a copy of the GNU Affero General Public License ;; along with this program. If not, see <https://www.gnu.org/licenses/>. #-asdf3.3 (error "Needs ASDFv3.3") (asdf:defsystem "leetcode-1657" :class :package-inferred-system :version "0.1" :author "Hraban Luyat" :licence "AGPLv3" :build-operation "program-op" :build-pathname "bin/leetcode" :entry-point "leetcode-1657:main" :depends-on ("leetcode-1657/main"))
961
Common Lisp
.asd
23
40
75
0.754274
hraban/leetcode-1657-cl-nix
0
0
0
AGPL-3.0
9/19/2024, 11:51:06 AM (Europe/Amsterdam)
ed3f48de101bbe7a1a269320f091103f5a64219727321e075064ac424d87d50f
42,253
[ -1 ]
42,255
flake.lock
hraban_leetcode-1657-cl-nix/flake.lock
{ "nodes": { "cl-nix-lite": { "locked": { "lastModified": 1699028934, "narHash": "sha256-ISS78eMmKHpKqV5FlulK+XisNzKa9CGUMXIGQaYqZnY=", "owner": "hraban", "repo": "cl-nix-lite", "rev": "7850aef6947b80bdf3fbb3b79dad729f937ec869", "type": "github" }, "original": { "owner": "hraban", "repo": "cl-nix-lite", "type": "github" } }, "flake-utils": { "inputs": { "systems": "systems" }, "locked": { "lastModified": 1694529238, "narHash": "sha256-zsNZZGTGnMOf9YpHKJqMSsa0dXbfmxeoJ7xHlrt+xmY=", "owner": "numtide", "repo": "flake-utils", "rev": "ff7b65b44d01cf9ba6a71320833626af21126384", "type": "github" }, "original": { "owner": "numtide", "repo": "flake-utils", "type": "github" } }, "nixpkgs": { "locked": { "lastModified": 1699094435, "narHash": "sha256-YLZ5/KKZ1PyLrm2MO8UxRe4H3M0/oaYqNhSlq6FDeeA=", "owner": "NixOS", "repo": "nixpkgs", "rev": "9d5d25bbfe8c0297ebe85324addcb5020ed1a454", "type": "github" }, "original": { "id": "nixpkgs", "type": "indirect" } }, "root": { "inputs": { "cl-nix-lite": "cl-nix-lite", "flake-utils": "flake-utils", "nixpkgs": "nixpkgs" } }, "systems": { "locked": { "lastModified": 1681028828, "narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=", "owner": "nix-systems", "repo": "default", "rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e", "type": "github" }, "original": { "owner": "nix-systems", "repo": "default", "type": "github" } } }, "root": "root", "version": 7 }
1,894
Common Lisp
.l
75
17.853333
73
0.514568
hraban/leetcode-1657-cl-nix
0
0
0
AGPL-3.0
9/19/2024, 11:51:06 AM (Europe/Amsterdam)
961057b9a6aa51b9f0ca6029540525bb60e2d954ef72153aa005ade1cc3c0792
42,255
[ -1 ]
42,257
flake.nix
hraban_leetcode-1657-cl-nix/flake.nix
{ description = "leetcode-1657"; inputs = { flake-utils.url = "github:numtide/flake-utils"; cl-nix-lite.url = "github:hraban/cl-nix-lite"; }; outputs = { self, nixpkgs, cl-nix-lite, flake-utils }: flake-utils.lib.eachDefaultSystem (system: let pkgs = nixpkgs.legacyPackages.${system}.extend cl-nix-lite.overlays.default; in with pkgs.lispPackagesLite; { packages = { default = lispDerivation { # Trailing numbers in flake names are interpreted as version # numbers and stripped from the expected binary name. name = "leetcode"; lispSystem = "leetcode-1657"; lispDependencies = [ arrow-macros inferior-shell str fset ]; src = pkgs.lib.cleanSource ./.; dontStrip = true; meta = { license = pkgs.lib.licenses.agpl3Only; }; }; }; }); }
988
Common Lisp
.l
31
22.612903
84
0.556949
hraban/leetcode-1657-cl-nix
0
0
0
AGPL-3.0
9/19/2024, 11:51:06 AM (Europe/Amsterdam)
45bab57e1fb3e0670f2e5ecc58e18144551efdec163d45cced247aa9aaac473a
42,257
[ -1 ]
42,272
combinemultichannels.lisp
brandflake11_combine-multi-channels/combinemultichannels.lisp
;; combine-multi-audio-channels ;; This file Copyright (C) 2022 Brandon Hale ;; This program is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with this program. If not, see <https://www.gnu.org/licenses/>. ;; You need to have CM-INCUDINE installed. Normal CM just won't do. ;; Incudine is used for realtime and osc ;; This is my attempt to rewrite combineMultiChannels.py ;; into a lisp codebase (defpackage :combine-multi-channels (:use :common-lisp :py4cl) (:export #:python-path #:combine-audio)) (in-package :combine-multi-channels) ;; To import this file, the file needs to be in the python path (py4cl:import-module "combineMultiChannels" :as "combo") ;; To see what directories are in your current python path: (defun python-path () "Print out the directories in python's path." (py4cl:python-exec "import sys") (py4cl:python-eval "sys.path")) ;; Then copy the relevant file there. ;; Example after importing module ;; This will flip the channels from a test.wav to another.wav ;; (combo:combinemultfns '("/tmp/test.wav") '((1 0)) "/tmp/another.wav") (defun combine-audio (file-list channel-list new-file) "Combines multiple audio file channels into a new file based on channel-list. file-list: include a list of filenames channel-list: include a list of integers, these will be the channels wanted from each item of File-list. Each list refers to items of file-list. new-file: path of the new file. Example: Say we have three stereo audio files, *one*, *two*, and *three*: (combine-audio (list *one* *two* *three*) '(0 1 0) \"/tmp/output.wav\") The output file will include in order: Left Channel of *one* Right Channel of *two* Left Channel of *three* Creating a 3 channel audio file. You can also include multiple channels of a certain file, by putting a list in the channel-list: (combine-audio (list *one* *two* *three*) '((0 1) 0 (1 0)) \"/tmp/output2.wav\") The output file will include in order: Left Channel of *one* Right Channel of *one* Left Channel of *two* Right Channel of *three* Left Channel of *three* Creating a 4 channel file. One last thing to remember, if you get confused: COMBINE-AUDIO does not mix channels. It only combines channels into a multichannel file, never mixing channels together. It will only separate out discrete files and reconstruct them. " (labels ((listify (input) "Turns input into a list if input is not a list. If it is, return input unchanged." (if (not (listp input)) (list input) input))) (let ((the-file-list file-list) (the-channel-list (mapcar #'listify (listify channel-list)))) (combo:combinemultfns the-file-list the-channel-list new-file)))) ;; This is how you do it manually like in python ;; Only here for debugging: ;; (py4cl:python-eval "combo.combineMultFns(['/tmp/test.wav'],[[1,0]],'/tmp/another.wav')")
3,358
Common Lisp
.lisp
68
47.323529
232
0.746177
brandflake11/combine-multi-channels
0
0
0
GPL-3.0
9/19/2024, 11:51:06 AM (Europe/Amsterdam)
0ee1cd759b303e622976b834d8be7827e0f4cec403bdaeff7fe004d94eac357c
42,272
[ -1 ]
42,273
combine-multi-channels.asd
brandflake11_combine-multi-channels/combine-multi-channels.asd
;; combine-multi-audio-channels ;; This file Copyright (C) 2022 Brandon Hale ;; This program is free software: you can redistribute it and/or modify ;; it under the terms of the GNU General Public License as published by ;; the Free Software Foundation, either version 3 of the License, or ;; (at your option) any later version. ;; This program is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;; GNU General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with this program. If not, see <https://www.gnu.org/licenses/>. (ql:quickload :py4cl) (py4cl:import-module "combineMultiChannels" :as "combo") (asdf:defsystem :combine-multi-channels :description "Combine audio channels from multiple files into a big multichannel file." :version "1.0" :author "Brandon Hale <[email protected]>" :license "GNU General Public License v3" :depends-on (#:py4cl) :components ((:file "combinemultichannels")))
1,118
Common Lisp
.asd
21
51.47619
89
0.769442
brandflake11/combine-multi-channels
0
0
0
GPL-3.0
9/19/2024, 11:51:06 AM (Europe/Amsterdam)
23be3850f17d3b8f3111387aa1fec997f465cbf56e5b19dac28382ffb800da56
42,273
[ -1 ]
42,292
game.lsp
racciel_LispGameofLife/game.lsp
(setq *print-case* :capitalize) (defun createArray(rows cols) (make-array (list rows cols)) ) (defvar *numrows*) (defvar *numcolumns*) (defun start () (print "Enter the number of rows: ") (setf *numrows* (read)) ;;(setf *numrows* 50) (print "Enter the number of columns: ") ;;(setf *numcolumns* 50) (setf *numcolumns* (read)) (defparameter *grid* (createArray *numrows* *numcolumns*)) (dotimes (i *numrows*) (dotimes (j *numcolumns*) (if (= (round (/ (random 1.0) 1.8)) 1) (setf (aref *grid* i j) 'X) (setf (aref *grid* i j) '-) ) ) ) (defparameter *newGrid* (createArray *numrows* *numcolumns*)) (dotimes (x 9999999) ;;(print *grid*) (dotimes (i *numrows*) (dotimes (j *numcolumns*) (format t "~a" (aref *grid* i j)) ) (terpri) ) (format t " ") (nextGen *newGrid* *grid*) (setf *grid* *newGrid*) (sleep 0.2) (terpri) ) ) (defun nextGen(new old) (defvar current 0) (dotimes (i *numrows*) (dotimes (j *numcolumns*) (setf current (countNeighbors old i j)) (setf (aref new i j) (aref old i j)) (if (and (= current 3) (STRING= (aref old i j) '-)) (setf (aref new i j) 'X) ;;(continue ()) ) (if (and (STRING= (aref old i j) 'X) (or (< current 2) (> current 3))) (setf (aref new i j) '-) ;;(continue ()) ) #| (if (STRING= (aref old i j) 'X) ( (if (or (< current 2) (> current 3)) (setf (aref new i j) '-) ) ) ( (if (= current 3) (setf (aref new i j) 'X) ) ) ) |# ;;(print current) #| (if (and (STRING= (aref old i j) 'X) (or (= current 2) (= current 3))) (setf (aref new i j) 'X) (setf (aref new i j) '-) ) (if (and (STRING= (aref old i j) '-) (= current 3)) (setf (aref new i j) 'X) (setf (aref new i j) '-) ) |# ) ) ;;(terpri) ;;(print new) ) (defun countNeighbors (grid x y) (defvar count 0) (setf count 0) (loop for i from (- x 1) to (+ x 1) by 1 do (if (< i 0) (setq i (+ i 1)) (continue ()) ) (if (= i *numrows*) (return) ) (loop for j from (- y 1) to (+ y 1) by 1 do (if (or (< j 0) (and (= j 0) (= i 0))) (setq j (+ j 1)) (continue ()) ) (if (= j *numcolumns*) (return) ) (if (STRING= (aref grid i j) 'X) (setq count (+ count 1)) ) ) ) (if (STRING= (aref grid x y ) 'X) (setf count (- count 1)) ) (return-from countNeighbors count) ) (start)
3,218
Common Lisp
.l
108
19.175926
85
0.40695
racciel/LispGameofLife
0
0
0
GPL-3.0
9/19/2024, 11:51:15 AM (Europe/Amsterdam)
39af113bfbba288b4f86712914b087d7febb0caa49273800ba8ce46107b3e09d
42,292
[ -1 ]
42,308
Hello.lisp
pswaff1_Introductory_LISP_Practice/Hello.lisp
; Hello.lisp ; ; A LISP program that displays the message, "Hello, world!" to ; the command line ; ; NCU.edu ; School of Technology & Engineering ; TIM6110 ; ; Author: Patrick Swafford ; Date: 15 January 2023 (defun main() (setq message "Hello, world!") (princ message) ) (main)
288
Common Lisp
.lisp
16
16.4375
62
0.719557
pswaff1/Introductory_LISP_Practice
0
0
0
GPL-3.0
9/19/2024, 11:51:15 AM (Europe/Amsterdam)
56cb07877914643ca052232091d68a433646272410705b06c81f86eae410ed7f
42,308
[ -1 ]
42,309
Sentence_Reversinator.lisp
pswaff1_Introductory_LISP_Practice/Sentence_Reversinator.lisp
; Sentence_Reversinator.lisp ; ; A LISP program that prompts the user for a sentence ; then displays the words in reverse order ; ; NCU.edu ; School of Technology & Engineering ; TIM6110 ; ; Author: Patrick Swafford ; Date: 15 January 2023 (defun string-to-list (string) (let ((len (length string)) ; Get the length of the input string (i 0) ; Initialize counter variable i (start 0) ; Initialize starting index for current word (list '())) ; Initialize empty list (loop while (< i len) ; Loop through each character in the string do (if (not (char= (aref string i) #\Space)) ; Check if current character is not a space (progn (setq i (1+ i)) ) ; If not, increment i (progn (setq list (cons (subseq string start i) list)) ; If space, add word to list (setq start (1+ i)) ; set new starting index (setq i (1+ i)))) ; increment i finally (return (cons (subseq string start i) list))) ; return the list of words )) (defun main() (setq message "Enter a sentence: ") ; ask user to input a sentence (princ message) ; print the message (setq input (read-line)) ; read the input as a string (setq word-list (string-to-list input)) ; convert the input string to list of words (princ word-list) ; print the list of words ) (main) ; call the main function to start the program
1,583
Common Lisp
.lisp
32
43.59375
100
0.582041
pswaff1/Introductory_LISP_Practice
0
0
0
GPL-3.0
9/19/2024, 11:51:15 AM (Europe/Amsterdam)
87ecf6b2ed2cfe4c68e9ecd1e506edaaa742bd729282b71eb6fa262c431808ca
42,309
[ -1 ]
42,310
CFTC.lisp
pswaff1_Introductory_LISP_Practice/CFTC.lisp
; CFTC.lisp [convert_fahrenheit_to_celsius] ; ; A LISP program that prompts the user for a temperature in Fahrenheit, ; converts the temperature to Celsius, and displays the result to the ; screen. ; ; NCU.edu ; School of Technology & Engineering ; TIM6110 ; ; Author: Patrick Swafford ; Date: 15 January 2023 (defun main() (setq message "Enter the temperature in Fahrenheit: ") (princ message) (setq fahrenheit (read)) (princ (* (- fahrenheit 32) (/ 5 9.0))) (princ " degrees celsius") ) (main)
517
Common Lisp
.lisp
20
23.8
71
0.719758
pswaff1/Introductory_LISP_Practice
0
0
0
GPL-3.0
9/19/2024, 11:51:15 AM (Europe/Amsterdam)
f8df63e5c5db92537d94fb0b1820c29471dea9444ec3ce781b4bb6ea85eb276a
42,310
[ -1 ]
42,329
transport.lisp
ormf_cl-jack-transport/transport.lisp
;;; This file was automatically generated by SWIG (http://www.swig.org). ;;; Version 3.0.12 ;;; ;;; Do not make changes to this file unless you know what you are doing--modify ;;; the SWIG interface file instead. (in-package :jack-transport) ;;;SWIG wrapper code starts here (cl:defmacro defanonenum (cl:&body enums) "Converts anonymous enums to defconstants." `(cl:progn ,@(cl:loop for value in enums for index = 0 then (cl:1+ index) when (cl:listp value) do (cl:setf index (cl:second value) value (cl:first value)) collect `(cl:defconstant ,value ,index)))) (cl:eval-when (:compile-toplevel :load-toplevel) (cl:unless (cl:fboundp 'swig-lispify) (cl:defun swig-lispify (name flag cl:&optional (package cl:*package*)) (cl:labels ((helper (lst last rest cl:&aux (c (cl:car lst))) (cl:cond ((cl:null lst) rest) ((cl:upper-case-p c) (helper (cl:cdr lst) 'upper (cl:case last ((lower digit) (cl:list* c #\- rest)) (cl:t (cl:cons c rest))))) ((cl:lower-case-p c) (helper (cl:cdr lst) 'lower (cl:cons (cl:char-upcase c) rest))) ((cl:digit-char-p c) (helper (cl:cdr lst) 'digit (cl:case last ((upper lower) (cl:list* c #\- rest)) (cl:t (cl:cons c rest))))) ((cl:char-equal c #\_) (helper (cl:cdr lst) '_ (cl:cons #\- rest))) (cl:t (cl:error "Invalid character: ~A" c))))) (cl:let ((fix (cl:case flag ((constant enumvalue) "+") (variable "*") (cl:t "")))) (cl:intern (cl:concatenate 'cl:string fix (cl:nreverse (helper (cl:concatenate 'cl:list name) cl:nil cl:nil)) fix) package)))))) ;;;SWIG wrapper code ends here (cffi:defcfun ("jack_release_timebase" jack-release-timebase) :int (client :pointer)) (cffi:defcfun ("jack_set_sync_callback" jack-set-sync-callback) :int (client :pointer) (sync-callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_set_sync_timeout" jack-set-sync-timeout) :int (client :pointer) (timeout :pointer)) (cffi:defcfun ("jack_set_timebase_callback" jack-set-timebase-callback) :int (client :pointer) (conditional :int) (timebase-callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_transport_locate" jack-transport-locate) :int (client :pointer) (frame jack-nframes-t)) (cffi:defcfun ("jack_transport_query" jack-transport-query) jack-transport-state-t (client :pointer) (pos (:pointer (:struct jack-position)))) (cffi:defcfun ("jack_transport_query" jack-transport-query) :int (client :pointer) (pos (:pointer (:struct jack-position)))) (cffi:defcfun ("jack_get_current_transport_frame" jack-get-current-transport-frame) jack-nframes-t (client :pointer)) (cffi:defcfun ("jack_transport_reposition" jack-transport-reposition) :int (client :pointer) (pos :pointer)) (cffi:defcfun ("jack_transport_start" jack-transport-start) :void (client :pointer)) (cffi:defcfun ("jack_transport_stop" jack-transport-stop) :void (client :pointer)) (cffi:defcfun ("jack_get_transport_info" jack-get-transport-info) :void (client :pointer) (tinfo :pointer)) (cffi:defcfun ("jack_set_transport_info" jack-set-transport-info) :void (client :pointer) (tinfo :pointer))
3,838
Common Lisp
.lisp
87
33.183908
98
0.565567
ormf/cl-jack-transport
0
0
0
GPL-2.0
9/19/2024, 11:51:15 AM (Europe/Amsterdam)
33aef0a4e96624baca50bf87ca02fa5cd27b8a80971906a4695cec504d69f12c
42,329
[ -1 ]
42,330
package.lisp
ormf_cl-jack-transport/package.lisp
;;;; package.lisp (defpackage #:jack-transport (:use #:cl #:cffi) (:export #:CONNECT #:DISCONNECT #:RECONNECT #:LOCATE #:GET-POSITION #:START #:STOP #:TRANSPORT-STATE #:GET-FRAME-RATE #:SET-TRANSPORT-RESPONDER )) (in-package :jack-transport) (define-foreign-library libjack (:darwin (:or "libjack.0.dylib" "libjack.dylib")) (:unix (:or "libjack.so.0" "libjack.so")) (t (:default "libjack"))) (use-foreign-library libjack) ;;; (c-include "jack.h")
506
Common Lisp
.lisp
22
19.318182
53
0.647679
ormf/cl-jack-transport
0
0
0
GPL-2.0
9/19/2024, 11:51:15 AM (Europe/Amsterdam)
a4d89f08b4bf1ec180a36f68ecfd33a4c027bdfe5d97258fe2c7172fb14d10a6
42,330
[ -1 ]
42,331
callbacks.lisp
ormf_cl-jack-transport/callbacks.lisp
;;; ;;; callbacks.lisp ;;; ;;; callback mechanism for jack-transport. ;;; ;;; use #'set-transport-responder with the keywords :start, :stop or ;;; :sync to set responder functions of no arguments when the ;;; transport state is changed. These functions will be called in ;;; their own thread to avoid blocking of jack's rt-thread. ;;; ;;; ********************************************************************** ;;; Copyright (c) 2023 Orm Finnendahl <[email protected]> ;;; ;;; Revision history: See git repository. ;;; ;;; This program is free software; you can redistribute it and/or ;;; modify it under the terms of the Gnu Public License, version 2 or ;;; later. See https://www.gnu.org/licenses/gpl-2.0.html for the text ;;; of this agreement. ;;; ;;; This program is distributed in the hope that it will be useful, ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; ;;; ********************************************************************** (in-package :jack-transport) (defvar *transport-states* #(:stopped :rolling :looping :starting :net-starting)) (defvar *sync-signal* (bt:make-condition-variable)) (defvar *start-signal* (bt:make-condition-variable)) (defvar *stop-signal* (bt:make-condition-variable)) (defvar *transport-responder-fns* `(:sync ,(lambda ()) :start ,(lambda ()) :stop ,(lambda ()))) (defvar *sync-state* :idle) (defvar *sync-thread* nil) (defvar *transport-thread* nil) (defun set-transport-responder (responder fn) (setf (getf *transport-responder-fns* responder) fn)) (defun signal-sync () "signal the sync thread to call the sync responder." (bt:condition-notify *sync-signal*)) (defun signal-start () "signal the sync thread to call the start responder." (bt:condition-notify *start-signal*)) (defun signal-stop () "signal the sync thread to call the stop responder." (bt:condition-notify *stop-signal*)) (defun make-sync-thread () (let ((lock (bt:make-lock))) (setf *sync-thread* (bt:make-thread (lambda () (loop (bt:with-lock-held (lock) (bt:condition-wait *sync-signal* lock) (funcall (getf *transport-responder-fns* :sync)) (setf *sync-state* :synced)))))))) (defun make-transport-thread () (let ((lock (bt:make-lock))) (setf *transport-thread* (bt:make-thread (lambda () (loop (bt:with-lock-held (lock) (bt:condition-wait *start-signal* lock) (funcall (getf *transport-responder-fns* :start)) (bt:condition-wait *stop-signal* lock) (funcall (getf *transport-responder-fns* :stop))))))))) (defun destroy-all-threads () (when *sync-thread* (bt:destroy-thread *sync-thread*) (setf *sync-thread* nil)) (when *transport-thread* (bt:destroy-thread *transport-thread*) (setf *transport-thread* nil))) (defcallback jacktransport-shutdown-callback :void ((arg (:pointer :void))) (declare (ignore arg)) (disconnect)) (defcallback jacktransport-sync-callback :int ((state jack-transport-state-t) (pos (:pointer (:struct jack-position))) (arg (:pointer :void))) (declare (ignore state pos arg)) (case *sync-state* (:idle (setf *sync-state* :syncing) (signal-sync))) (if (eql *sync-state* :synced) (progn (setf *sync-state* :idle) 1) 0)) (let ((old-state -1)) (defcallback jacktransport-process-callback :int ((nframes jack-nframes-t) (arg (:pointer :void))) (declare (ignore nframes arg)) (let ((state (jack-transport-query *transport-client* *transport-position*))) (when (/= state old-state) (case (aref *transport-states* state) (:rolling (signal-start)) (:stopped (signal-stop)) (:otherwise (format t "~&~S" (aref *transport-states* state)))) (setf old-state state)) 0)))
4,096
Common Lisp
.lisp
104
34.144231
81
0.629369
ormf/cl-jack-transport
0
0
0
GPL-2.0
9/19/2024, 11:51:15 AM (Europe/Amsterdam)
fe6c0cf6eebaf5ed0671ad1b22fb38bdbff6bf08e7bb35e5170949e38c000404
42,331
[ -1 ]
42,332
types.lisp
ormf_cl-jack-transport/types.lisp
;;; This file was automatically generated by SWIG (http://www.swig.org). ;;; Version 3.0.12 ;;; ;;; Do not make changes to this file unless you know what you are doing--modify ;;; the SWIG interface file instead. (in-package :jack-transport) ;;;SWIG wrapper code starts here (cl:defmacro defanonenum (cl:&body enums) "Converts anonymous enums to defconstants." `(cl:progn ,@(cl:loop for value in enums for index = 0 then (cl:1+ index) when (cl:listp value) do (cl:setf index (cl:second value) value (cl:first value)) collect `(cl:defconstant ,value ,index)))) (cl:eval-when (:compile-toplevel :load-toplevel) (cl:unless (cl:fboundp 'swig-lispify) (cl:defun swig-lispify (name flag cl:&optional (package cl:*package*)) (cl:labels ((helper (lst last rest cl:&aux (c (cl:car lst))) (cl:cond ((cl:null lst) rest) ((cl:upper-case-p c) (helper (cl:cdr lst) 'upper (cl:case last ((lower digit) (cl:list* c #\- rest)) (cl:t (cl:cons c rest))))) ((cl:lower-case-p c) (helper (cl:cdr lst) 'lower (cl:cons (cl:char-upcase c) rest))) ((cl:digit-char-p c) (helper (cl:cdr lst) 'digit (cl:case last ((upper lower) (cl:list* c #\- rest)) (cl:t (cl:cons c rest))))) ((cl:char-equal c #\_) (helper (cl:cdr lst) '_ (cl:cons #\- rest))) (cl:t (cl:error "Invalid character: ~A" c))))) (cl:let ((fix (cl:case flag ((constant enumvalue) "+") (variable "*") (cl:t "")))) (cl:intern (cl:concatenate 'cl:string fix (cl:nreverse (helper (cl:concatenate 'cl:list name) cl:nil cl:nil)) fix) package)))))) ;;;SWIG wrapper code ends here (defctype jack-nframes-t :int32) (defctype jack-uuid-t :uint64) (defctype jack-shmsize-t :int32) (defctype jack-unique-t :uint64) (cl:defconstant JACK-MAX-FRAMES 4294967295) (defctype jack-time-t :uint64) (cl:defconstant JACK-LOAD-INIT-LIMIT 1024) (defctype jack-intclient-t :uint64) (defctype jack-port-id-t :uint32) (defctype jack-port-type-id-t :uint64) (cffi:defcenum JackOptions (:JackNullOption #.#x00) (:JackNoStartServer #.#x01) (:JackUseExactName #.#x02) (:JackServerName #.#x04) (:JackLoadName #.#x08) (:JackLoadInit #.#x10) (:JackSessionID #.#x20)) (cffi:defcenum JackStatus (:JackFailure #.#x01) (:JackInvalidOption #.#x02) (:JackNameNotUnique #.#x04) (:JackServerStarted #.#x08) (:JackServerFailed #.#x10) (:JackServerError #.#x20) (:JackNoSuchClient #.#x40) (:JackLoadFailure #.#x80) (:JackInitFailure #.#x100) (:JackShmFailure #.#x200) (:JackVersionError #.#x400) (:JackBackendError #.#x800) (:JackClientZombie #.#x1000)) (cffi:defcenum JackLatencyCallbackMode :JackCaptureLatency :JackPlaybackLatency) (cffi:defcstruct -jack-latency-range (min :pointer) (max :pointer)) (unless (boundp 'JACK-DEFAULT-AUDIO-TYPE) (cl:defconstant JACK-DEFAULT-AUDIO-TYPE "32 bit float mono audio")) (unless (boundp 'JACK-DEFAULT-AUDIO-TYPE) (cl:defconstant JACK-DEFAULT-MIDI-TYPE "8 bit raw midi")) (cffi:defcenum JackPortFlags (:JackPortIsInput #.#x1) (:JackPortIsOutput #.#x2) (:JackPortIsPhysical #.#x4) (:JackPortCanMonitor #.#x8) (:JackPortIsTerminal #.#x10)) (cffi:defcenum jack-transport-state-t (:JackTransportStopped #.0) (:JackTransportRolling #.1) (:JackTransportLooping #.2) (:JackTransportStarting #.3) (:JackTransportNetStarting #.4)) (cffi:defcenum jack-position-bits-t (:JackPositionBBT #.#x10) (:JackPositionTimecode #.#x20) (:JackBBTFrameOffset #.#x40) (:JackAudioVideoRatio #.#x80) (:JackVideoFrameOffset #.#x100) (:JackTickDouble #.#x200)) (cffi:defcstruct jack-position (unique-1 jack-unique-t) (usecs jack-time-t) (frame-rate jack-nframes-t) (frame jack-nframes-t) (valid jack-position-bits-t) (bar :int32) (beat :int32) (tick :int32) (bar-start-tick :double) (beats-per-bar :float) (beat-type :float) (ticks-per-beat :double) (beats-per-minute :double) (frame-time :double) (next-time :double) (bbt-offset jack-nframes-t) (audio-frames-per-video-frame :float) (video-offset jack-nframes-t) (tick-double :double) (padding :pointer :count 5) (unique-2 :pointer)) (defctype jack-position-t (:struct jack-position)) (cffi:defcenum jack-transport-bits-t (:JackTransportState #.#x1) (:JackTransportPosition #.#x2) (:JackTransportLoop #.#x4) (:JackTransportSMPTE #.#x8) (:JackTransportBBT #.#x10)) (cffi:defcstruct jack-transport-info-t (frame-rate :pointer) (usecs :pointer) (valid jack-transport-bits-t) (transport-state jack-transport-state-t) (frame :pointer) (loop-start :pointer) (loop-end :pointer) (smpte-offset :long) (smpte-frame-rate :float) (bar :int) (beat :int) (tick :int) (bar-start-tick :double) (beats-per-bar :float) (beat-type :float) (ticks-per-beat :double) (beats-per-minute :double))
5,437
Common Lisp
.lisp
157
27.847134
86
0.617098
ormf/cl-jack-transport
0
0
0
GPL-2.0
9/19/2024, 11:51:15 AM (Europe/Amsterdam)
41c7f76e2a4b123459ac062d24d195bfb88c3e5c57a58134d468d53a396280ce
42,332
[ -1 ]
42,333
jack.lisp
ormf_cl-jack-transport/jack.lisp
;;; This file was automatically generated by SWIG (http://www.swig.org). ;;; Version 3.0.12 ;;; ;;; Do not make changes to this file unless you know what you are doing--modify ;;; the SWIG interface file instead. (in-package :jack-transport) ;;;SWIG wrapper code starts here (cl:defmacro defanonenum (cl:&body enums) "Converts anonymous enums to defconstants." `(cl:progn ,@(cl:loop for value in enums for index = 0 then (cl:1+ index) when (cl:listp value) do (cl:setf index (cl:second value) value (cl:first value)) collect `(cl:defconstant ,value ,index)))) (cl:eval-when (:compile-toplevel :load-toplevel) (cl:unless (cl:fboundp 'swig-lispify) (cl:defun swig-lispify (name flag cl:&optional (package cl:*package*)) (cl:labels ((helper (lst last rest cl:&aux (c (cl:car lst))) (cl:cond ((cl:null lst) rest) ((cl:upper-case-p c) (helper (cl:cdr lst) 'upper (cl:case last ((lower digit) (cl:list* c #\- rest)) (cl:t (cl:cons c rest))))) ((cl:lower-case-p c) (helper (cl:cdr lst) 'lower (cl:cons (cl:char-upcase c) rest))) ((cl:digit-char-p c) (helper (cl:cdr lst) 'digit (cl:case last ((upper lower) (cl:list* c #\- rest)) (cl:t (cl:cons c rest))))) ((cl:char-equal c #\_) (helper (cl:cdr lst) '_ (cl:cons #\- rest))) (cl:t (cl:error "Invalid character: ~A" c))))) (cl:let ((fix (cl:case flag ((constant enumvalue) "+") (variable "*") (cl:t "")))) (cl:intern (cl:concatenate 'cl:string fix (cl:nreverse (helper (cl:concatenate 'cl:list name) cl:nil cl:nil)) fix) package)))))) ;;;SWIG wrapper code ends here (cffi:defcfun ("jack_get_version" jack-get-version) :void (major-ptr :pointer) (minor-ptr :pointer) (micro-ptr :pointer) (proto-ptr :pointer)) (cffi:defcfun ("jack_get_version_string" jack-get-version-string) :string) (cffi:defcfun ("jack_client_open" jack-client-open) :pointer (client-name :string) (options JackOptions) (status :pointer) &rest) (cffi:defcfun ("jack_client_new" jack_client_new) :pointer (client-name :string)) (cffi:defcfun ("jack_client_close" jack-client-close) :int (client :pointer)) (cffi:defcfun ("jack_client_name_size" jack-client-name-size) :int) (cffi:defcfun ("jack_get_client_name" jack-get-client-name) :string (client :pointer)) (cffi:defcfun ("jack_get_uuid_for_client_name" jack-get-uuid-for-client-name) :string (client :pointer) (client-name :string)) (cffi:defcfun ("jack_get_client_name_by_uuid" jack-get-client-name-by-uuid) :string (client :pointer) (client-uuid :string)) (cffi:defcfun ("jack_internal_client_new" jack-internal-client-new) :int (client-name :string) (load-name :string) (load-init :string)) (cffi:defcfun ("jack_internal_client_close" jack-internal-client-close) :void (client-name :string)) (cffi:defcfun ("jack_activate" jack-activate) :int (client :pointer)) (cffi:defcfun ("jack_deactivate" jack-deactivate) :int (client :pointer)) (cffi:defcfun ("jack_get_client_pid" jack-get-client-pid) :int (name :string)) (cffi:defcfun ("jack_client_thread_id" jack-client-thread-id) :pointer (client :pointer)) (cffi:defcfun ("jack_is_realtime" jack-is-realtime) :int (client :pointer)) (cffi:defcfun ("jack_thread_wait" jack-thread-wait) :pointer (client :pointer) (status :int)) (cffi:defcfun ("jack_cycle_wait" jack-cycle-wait) :pointer (client :pointer)) (cffi:defcfun ("jack_cycle_signal" jack-cycle-signal) :void (client :pointer) (status :int)) (cffi:defcfun ("jack_set_process_thread" jack-set-process-thread) :int (client :pointer) (thread-callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_set_thread_init_callback" jack-set-thread-init-callback) :int (client :pointer) (thread-init-callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_on_shutdown" jack-on-shutdown) :void (client :pointer) (shutdown-callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_on_info_shutdown" jack-on-info-shutdown) :void (client :pointer) (shutdown-callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_set_process_callback" jack-set-process-callback) :int (client :pointer) (process-callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_set_freewheel_callback" jack-set-freewheel-callback) :int (client :pointer) (freewheel-callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_set_buffer_size_callback" jack-set-buffer-size-callback) :int (client :pointer) (bufsize-callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_set_sample_rate_callback" jack-set-sample-rate-callback) :int (client :pointer) (srate-callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_set_client_registration_callback" jack-set-client-registration-callback) :int (client :pointer) (registration-callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_set_port_registration_callback" jack-set-port-registration-callback) :int (client :pointer) (registration-callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_set_port_connect_callback" jack-set-port-connect-callback) :int (client :pointer) (connect-callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_set_port_rename_callback" jack-set-port-rename-callback) :int (client :pointer) (rename-callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_set_graph_order_callback" jack-set-graph-order-callback) :int (client :pointer) (graph-callback :pointer) (arg2 :pointer)) (cffi:defcfun ("jack_set_xrun_callback" jack-set-xrun-callback) :int (client :pointer) (xrun-callback :pointer) (arg :pointer)) (cffi:defcfun ("jack_set_latency_callback" jack-set-latency-callback) :int (client :pointer) (latency-callback :pointer) (arg2 :pointer)) (cffi:defcfun ("jack_set_freewheel" jack-set-freewheel) :int (client :pointer) (onoff :int)) (cffi:defcfun ("jack_set_buffer_size" jack-set-buffer-size) :int (client :pointer) (nframes :pointer)) (cffi:defcfun ("jack_get_sample_rate" jack-get-sample-rate) :pointer (arg0 :pointer)) (cffi:defcfun ("jack_get_buffer_size" jack-get-buffer-size) :pointer (arg0 :pointer)) (cffi:defcfun ("jack_engine_takeover_timebase" jack-engine-takeover-timebase) :int (arg0 :pointer)) (cffi:defcfun ("jack_cpu_load" jack-cpu-load) :float (client :pointer)) (cffi:defcfun ("jack_port_register" jack-port-register) :pointer (client :pointer) (port-name :string) (port-type :string) (flags :unsigned-long) (buffer-size :unsigned-long)) (cffi:defcfun ("jack_port_unregister" jack-port-unregister) :int (client :pointer) (port :pointer)) (cffi:defcfun ("jack_port_get_buffer" jack-port-get-buffer) :pointer (port :pointer) (arg1 :pointer)) (cffi:defcfun ("jack_port_uuid" jack-port-uuid) :pointer (port :pointer)) (cffi:defcfun ("jack_port_name" jack-port-name) :string (port :pointer)) (cffi:defcfun ("jack_port_short_name" jack-port-short-name) :string (port :pointer)) (cffi:defcfun ("jack_port_flags" jack-port-flags) :int (port :pointer)) (cffi:defcfun ("jack_port_type" jack-port-type) :string (port :pointer)) (cffi:defcfun ("jack_port_type_id" jack-port-type-id) :pointer (port :pointer)) (cffi:defcfun ("jack_port_is_mine" jack-port-is-mine) :int (client :pointer) (port :pointer)) (cffi:defcfun ("jack_port_connected" jack-port-connected) :int (port :pointer)) (cffi:defcfun ("jack_port_connected_to" jack-port-connected-to) :int (port :pointer) (port-name :string)) (cffi:defcfun ("jack_port_get_connections" jack-port-get-connections) :pointer (port :pointer)) (cffi:defcfun ("jack_port_get_all_connections" jack-port-get-all-connections) :pointer (client :pointer) (port :pointer)) (cffi:defcfun ("jack_port_tie" jack-port-tie) :int (src :pointer) (dst :pointer)) (cffi:defcfun ("jack_port_untie" jack-port-untie) :int (port :pointer)) (cffi:defcfun ("jack_port_set_name" jack-port-set-name) :int (port :pointer) (port-name :string)) (cffi:defcfun ("jack_port_rename" jack-port-rename) :int (client :pointer) (port :pointer) (port-name :string)) (cffi:defcfun ("jack_port_set_alias" jack-port-set-alias) :int (port :pointer) (alias :string)) (cffi:defcfun ("jack_port_unset_alias" jack-port-unset-alias) :int (port :pointer) (alias :string)) (cffi:defcfun ("jack_port_get_aliases" jack-port-get-aliases) :int (port :pointer) (aliases :pointer)) (cffi:defcfun ("jack_port_request_monitor" jack-port-request-monitor) :int (port :pointer) (onoff :int)) (cffi:defcfun ("jack_port_request_monitor_by_name" jack-port-request-monitor-by-name) :int (client :pointer) (port-name :string) (onoff :int)) (cffi:defcfun ("jack_port_ensure_monitor" jack-port-ensure-monitor) :int (port :pointer) (onoff :int)) (cffi:defcfun ("jack_port_monitoring_input" jack-port-monitoring-input) :int (port :pointer)) (cffi:defcfun ("jack_connect" jack-connect) :int (client :pointer) (source-port :string) (destination-port :string)) (cffi:defcfun ("jack_disconnect" jack-disconnect) :int (client :pointer) (source-port :string) (destination-port :string)) (cffi:defcfun ("jack_port_disconnect" jack-port-disconnect) :int (client :pointer) (port :pointer)) (cffi:defcfun ("jack_port_name_size" jack-port-name-size) :int) (cffi:defcfun ("jack_port_type_size" jack-port-type-size) :int) (cffi:defcfun ("jack_port_type_get_buffer_size" jack-port-type-get-buffer-size) :pointer (client :pointer) (port-type :string)) (cffi:defcfun ("jack_port_set_latency" jack-port-set-latency) :void (port :pointer) (arg1 :pointer)) (cffi:defcfun ("jack_port_get_latency_range" jack-port-get-latency-range) :void (port :pointer) (mode :pointer) (range :pointer)) (cffi:defcfun ("jack_port_set_latency_range" jack-port-set-latency-range) :void (port :pointer) (mode :pointer) (range :pointer)) (cffi:defcfun ("jack_recompute_total_latencies" jack-recompute-total-latencies) :int (client :pointer)) (cffi:defcfun ("jack_port_get_latency" jack-port-get-latency) :pointer (port :pointer)) (cffi:defcfun ("jack_port_get_total_latency" jack-port-get-total-latency) :pointer (client :pointer) (port :pointer)) (cffi:defcfun ("jack_recompute_total_latency" jack-recompute-total-latency) :int (arg0 :pointer) (port :pointer)) (cffi:defcfun ("jack_get_ports" jack-get-ports) :pointer (client :pointer) (port-name-pattern :string) (type-name-pattern :string) (flags :unsigned-long)) (cffi:defcfun ("jack_port_by_name" jack-port-by-name) :pointer (client :pointer) (port-name :string)) (cffi:defcfun ("jack_port_by_id" jack-port-by-id) :pointer (client :pointer) (port-id :pointer)) (cffi:defcfun ("jack_frames_since_cycle_start" jack-frames-since-cycle-start) :pointer (arg0 :pointer)) (cffi:defcfun ("jack_frame_time" jack-frame-time) :pointer (arg0 :pointer)) (cffi:defcfun ("jack_last_frame_time" jack-last-frame-time) :pointer (client :pointer)) (cffi:defcfun ("jack_get_cycle_times" jack-get-cycle-times) :int (client :pointer) (current-frames :pointer) (current-usecs :pointer) (next-usecs :pointer) (period-usecs :pointer)) (cffi:defcfun ("jack_frames_to_time" jack-frames-to-time) :pointer (client :pointer) (arg1 :pointer)) (cffi:defcfun ("jack_time_to_frames" jack-time-to-frames) :pointer (client :pointer) (arg1 :pointer)) (cffi:defcfun ("jack_get_time" jack-get-time) :pointer) (cffi:defcvar ("jack_error_callback" jack-error-callback) :pointer) (cffi:defcfun ("jack_set_error_function" jack-set-error-function) :void (func :pointer)) (cffi:defcvar ("jack_info_callback" jack-info-callback) :pointer) (cffi:defcfun ("jack_set_info_function" jack-set-info-function) :void (func :pointer)) (cffi:defcfun ("jack_free" jack-free) :void (ptr :pointer))
12,482
Common Lisp
.lisp
318
34.342767
98
0.678272
ormf/cl-jack-transport
0
0
0
GPL-2.0
9/19/2024, 11:51:15 AM (Europe/Amsterdam)
f05cd63506774db5e079f65bfb2e1d2ad97a5f69af58994eb7cf401b0127c9b7
42,333
[ -1 ]
42,334
jack-transport.lisp
ormf_cl-jack-transport/jack-transport.lisp
;;; ;;; jack-transport.lisp ;;; ;;; ********************************************************************** ;;; Copyright (c) 2022 Orm Finnendahl <[email protected]> ;;; ;;; Revision history: See git repository. ;;; ;;; This program is free software; you can redistribute it and/or ;;; modify it under the terms of the Gnu Public License, version 2 or ;;; later. See https://www.gnu.org/licenses/gpl-2.0.html for the text ;;; of this agreement. ;;; ;;; This program is distributed in the hope that it will be useful, ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; ;;; ********************************************************************** (in-package :jack-transport) (setf *print-case* :downcase) (defvar *transport-client* nil) ;;; package global handle for the ;;; client. This should never be ;;; modified directly. (defvar *transport-position* nil) ;;; package global handle for the ;;; transport-position ;;; c-struct. This should never be ;;; modified directly. The c-struct ;;; gets created with ;;; jacktransport-connect and freed ;;; with jacktransport-disconnect. (defmacro ensure-jacktransport-connected (&body body) `(if *transport-client* (progn ,@body) (warn "jacktransport: not connected. Connect first with (jacktransport-connect)."))) (defmacro ensure-jacktransport-disconnected (&body body) `(if (not *transport-client*) (progn ,@body) (warn "jacktransport: already connected. Disconnect first with (jacktransport-disconnect)."))) (defun disconnect () "disconnect jacktransport from jack." (ensure-jacktransport-connected (format t "~&disconnecting jacktransport...") (jack-deactivate *transport-client*) (jack-client-close *transport-client*) (destroy-all-threads) (if *transport-position* (foreign-free *transport-position*)) (setf *transport-client* nil) (setf *transport-position* nil) (format t "done.") (values))) (defun get-frame-rate () "obtain jack's current sample-rate." (ensure-jacktransport-connected (jack-transport-query *transport-client* *transport-position*) (foreign-slot-value *transport-position* '(:struct jack-position) 'frame-rate))) (defun locate (time) "locate jacktransport to time in secs." (ensure-jacktransport-connected (jack-transport-locate *transport-client* (round (* time (get-frame-rate)))) time)) (defun get-position () "get jacktransport position in secs." (ensure-jacktransport-connected (jack-transport-query *transport-client* *transport-position*) (let* ((frame-rate (foreign-slot-value *transport-position* '(:struct jack-position) 'frame-rate))) (/ (jack-get-current-transport-frame *transport-client*) frame-rate)))) (defun start () "start jacktransport." (ensure-jacktransport-connected (jack-transport-start *transport-client*))) (defun stop () "stop jacktransport." (ensure-jacktransport-connected (jack-transport-stop *transport-client*))) (defun transport-state () "get the current transport state as a keyword." (aref *transport-states* (jack-transport-query *transport-client* *transport-position*))) (defun connect () "connect jacktransport to jack." (ensure-jacktransport-disconnected (format t "~&connecting jacktransport...") (cffi:with-foreign-pointer (status 1) (let ((result (jack-client-open "cl-transport" :JackNullOption status))) (if (zerop (mem-aref status :int)) (progn (setf *transport-position* (foreign-alloc '(:struct jack-position))) (setf *transport-client* result) (make-sync-thread) (make-transport-thread) (jack-set-process-callback *transport-client* (callback jacktransport-process-callback) (cffi:null-pointer)) (jack-set-sync-callback *transport-client* (callback jacktransport-sync-callback) (cffi:null-pointer)) ;;; could submit a foreign pointer here! ;; (jack-on-shutdown ;; *transport-client* ;; (callback jacktransport-shutdown-callback) ;; (cffi:null-pointer)) (jack-activate *transport-client*) (format t "done.") (values)) (warn "couldn't create a jack client (~d)!" (mem-aref status :int))))))) (defun reconnect () "connect jacktransport to jack." (disconnect) (connect))
4,878
Common Lisp
.lisp
108
37.351852
103
0.625315
ormf/cl-jack-transport
0
0
0
GPL-2.0
9/19/2024, 11:51:15 AM (Europe/Amsterdam)
ac0fe115dc786757c3145ead6592cde4f3f13e88553de99d99517c157779bfa3
42,334
[ -1 ]
42,335
examples.lisp
ormf_cl-jack-transport/examples.lisp
;;; ;;; examples.lisp ;;; ;;; ********************************************************************** ;;; Copyright (c) 2023 Orm Finnendahl <[email protected]> ;;; ;;; Revision history: See git repository. ;;; ;;; This program is free software; you can redistribute it and/or ;;; modify it under the terms of the Gnu Public License, version 2 or ;;; later. See https://www.gnu.org/licenses/gpl-2.0.html for the text ;;; of this agreement. ;;; ;;; This program is distributed in the hope that it will be useful, ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; ;;; ********************************************************************** (in-package :cl-user) ;;; usage examples ;;; connect to jack: (jack-transport:connect) ;;; set responders for the transport state change situations: (jack-transport:set-transport-responder :start (lambda () (format t "~&start!"))) (jack-transport:set-transport-responder :stop (lambda () (format t "~&stop!") )) ;;; sync is called whenever the transport position has been changed. ;;; Be aware that sync is not only called after relocation of ;;; jacktransport, but also every time when starting, so it might be a ;;; good idea to check for the internal position of the app and jack's ;;; position when starting to avoid unnecessary multiple relocations. (jack-transport:set-transport-responder :sync (lambda () (format t "~&syncing to ~,3fs ..." (jack-transport:get-position)) (sleep 0) ;;; do something to sync up (format t "done!"))) ;;; there are some utility functions: (jack-transport:locate 10) (jack-transport:get-position) (jack-transport:start) (jack-transport:stop) (jack-transport:transport-state) (jack-transport:get-frame-rate) ;;; any other function of the jack API can also be called directly ;;; using the cffi calling conventions (e.g. replace underscore ;;; characters with hyphens). The current jack client is stored in the ;;; var jack-transport::*transport-client*. ;;; Example setting the sync timeout: (let* ((timeout-ptr (cffi:foreign-alloc :uint64))) (setf (cffi:mem-aref timeout-ptr :uint64 0) 1) (let ((result (jack-transport::jack-set-sync-timeout jack-transport::*transport-client* timeout-ptr))) (cffi:foreign-free timeout-ptr) result))
2,448
Common Lisp
.lisp
64
35.875
79
0.6847
ormf/cl-jack-transport
0
0
0
GPL-2.0
9/19/2024, 11:51:15 AM (Europe/Amsterdam)
68d43b3c1dd0e4eb04ea00060ad204a1dccd9e0691622d407ede00bebe56a010
42,335
[ -1 ]
42,336
cl-jack-transport.asd
ormf_cl-jack-transport/cl-jack-transport.asd
;;;; cl-jack-transport.asd (asdf:defsystem #:cl-jack-transport :description "cffi bindings for jack_transport" :author "Orm Finnendahl <[email protected]>" :license "gpl 2.0 or later" :version "0.0.1" :depends-on (#:cffi #:bordeaux-threads #:orm-utils) :serial t :components ((:file "package") (:file "types") (:file "transport") (:file "jack") (:file "callbacks") (:file "jack-transport")))
505
Common Lisp
.asd
14
28.642857
68
0.593878
ormf/cl-jack-transport
0
0
0
GPL-2.0
9/19/2024, 11:51:15 AM (Europe/Amsterdam)
58626931dc37007faa2ada59dd93c41fb4e8899802e62a0b09dbc555308cd081
42,336
[ -1 ]
42,360
simple-test.lisp
m-e-leypold_cl-simple-test/simple-test.lisp
;;; * -- (C) 2022 M E Leypold ------------------------------------------------------------*- common-lisp -*-| ;;; ;;; de.m-e-leypold.cl-simple.test -- a simple testing framework for common lisp. ;;; Copyright (C) 2022 M E Leypold ;;; ;;; This program is free software: you can redistribute it and/or modify ;;; it under the terms of the GNU General Public License as published by ;;; the Free Software Foundation, either version 3 of the License, or ;;; (at your option) any later version. ;;; ;;; This program is distributed in the hope that it will be useful, ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; ;;; You should have received a copy of the GNU General Public License ;;; along with this program. If not, see <https://www.gnu.org/licenses/>. ;;; ;;; For altermative licensing options, see README.md ;;; ;;; For user and technical documentation start with the documentatin string of Symbol ;;; `de.m-e-leypold.cl-simple-test::DOC'. ;;; ;;; * -- Options --------------------------------------------------------------------------------------------| ;;; ;;; Will be changed to defaults when cl-simple-test has reached sufficient maturity. (declaim (optimize (speed 0) (debug 3) (safety 3))) ;;; * -- Package definition & documentation -----------------------------------------------------------------| (defpackage :de.m-e-leypold.cl-simple-test (:documentation " DE.M-E-LEYPOLD.CL-SIMPLE-TEST is a simple test framework working with variations of `ASSERT'. Note: You will have either to run the tests or execute (load-tests) before the symbols prefixed with 'TEST::' and their documentation become available in your lisp process. Defining Tests -------------- Define tests with `DEFTEST'. `*TESTS*' will contain the all defined tests as a list of symbols. Asserting expectations ---------------------- Assert expectations in the test bodies with - `CL:ASSERT': Given expression must evaluate to true. - `ASSERT-CONDITION': Body must signal given condition type. - `ASSERT-NO-CONDITION': Body must not signal any condition. - `ASSERT-AND-CAPTURE-CONDITION': Body must signal given condition type and the instance will be captured in a variable. Executing test -------------- Execute all defined tests with `RUN-TESTS'. Failing tests will be recorded in `*FAILED*', passing tests in `*PASSED*'. At test run-time `*CURRENT-TEST*' always contains the symbol of the test that is executed at the moment. `*TESTS*' contains the symbols of all currently defined tests which might prove useful for creating a test summary report. Parameters ---------- Two parameters influence test execution: - `*DROP-INTO-DEBUGGER*' (default: NIL) -- Drop into the debugger when a test fails. This is useful for stopping at once at the failing test and of course have a chance to debug what goes wrong. - `*SIGNAL-AFTER-RUN-TESTS*' (default: T) -- After all tests have run, signal if any test failed (if `*FAILED*' is not empty). This is useful in batch mode to get a process exit code that indicates that s.th. failed when `*DROP-INTO-DEBUGGER*' is NIL. The backtrace in turn is not very useful in this case. The default setup would be typical for a batch run where we want to run all tests and just fail or pass at the end, e.g. for running tests in a CI pipeline. The setup (SETF *DROP-INTO-DEBUGGER* T) would be typical for an interactive or batch test run where all we want is to stop at the first failing test. This often makes sense in cases where the tests check layers of functionality that build on each other and it does not make sense to continue with later tests if one of the layers fail. Restarts during `RUN-TEST' -------------------------- Mostly for interactive use, two restarts are established by `RUN-TESTS': - `NEXT-TEST' -- Continue with the next test in the list. - `ABORT-TESTS' -- Abort testing. Test resets ----------- The following two functions are mostly useful for testing the CL-SIMPLE-TESTS framework itself. - `RESET-TEST-DEFINITIONS' will clear `*TESTS*' with the result that the test definitions are \"forgotten\". - `RESET-TEST-RUN-STATE' resets the definitions (as above) and clears `*CURRENT-TEST*'. Tests defined with `DEFTEST' are just normal functions. They can be run by invoking them explicitely. When doing so, the signal handlers and restarts referenced above will not be be installed while the tests executes. This means any condition signal esacping from the test body will result in the debugger being invoked if `*DEBUGGER-HOOK*' is set. Further information ------------------- Please refer to the documentation of above symbols for further information. The tests in package DE.M-E-LEYPOLD.CL-SIMPLE-TEST/TESTS also serve as a more detailed specification. See `DE.M-E-LEYPOLD.CL-SIMPLE-TEST/TESTS::*REGISTRY*' for an overview. Note: You will have either to run the tests or execute (load-tests) before the test symbols and their documentation become available in your lisp process. ") (:use :common-lisp :cl-ppcre) (:import-from :de.m-e-leypold.cl-simple-utils :defpackage-doc :defrestart :with-gensyms ) (:export :assert-condition :assert-no-condition :assert-and-capture-condition ;; defining tests :deftest :*tests* :reset-test-definitions ;; running tests :*current-test* :run-tests :reset-run-state ;; test results :*failed* :*passed* ;; parameters :*signal-after-run-tests* :*drop-into-debugger* ;; restart :next-test :abort-tests )) (in-package :de.m-e-leypold.cl-simple-test) (defpackage-doc -doc-) ;; -doc- will contain package doc string ;;; * -- Development infrastructure -------------------------------------------------------------------------| (defun load-tests () (asdf:load-system "de.m-e-leypold.cl-simple-test/tests")) ;;; * -- Defining tests -------------------------------------------------------------------------------------| (defparameter *tests* '() " Contains the tests defined with `DEFTEST' (as symbols). Symbols of tests are `ADJOIN'ed to this variable when the DEFTEST forms are evaluated. The variable can be cleared by `RESET-TEST-DEFINITION', though this is only of limited usefulness and mostly for testing the framework itself. Specification: `TEST::DEFINING-TESTS'. See also: `-DOC-'. ") (defparameter *current-test* nil " Contains the currently running test as a a symbol, NIL if no test is running. Specification: `TEST::DEFINING-TESTS', `TEST::CURRENT-TEST-MAINTENANCE'. See also: `-DOC-'. ") (defmacro deftest (name () doc &body body) "Define a test. Defines a test procedure bound to the symbol NAME and registers it for later execution with `RUN-TESTS'. The syntax is pretty much that of a `DEFUN`, but the lambda-list needs to be empty. The rationale that it needs to be given regardless is that this increases the readability. A reader will register immediately that a DEFTEST form defines a function, something that can be called. Every test must have a docstring DOC that describes what is tested in the test and how. Specification: `TEST:DEFINING-TESTS', `TEST:FAILING-ASSERTIONS-IN-TESTS'. See also: `-DOC-'. " (assert (stringp doc) nil (format nil "No docstring in DEFTEST ~S. Docstrings are required." name)) `(progn (setf *tests* (adjoin (quote ,name) *tests*)) (defun ,name () ,doc (let ((*current-test* (quote ,name))) ,@body)))) ;;; * -- Running tests --------------------------------------------------------------------------------------| (defparameter *failed* '() "Contains the failed tests after executing tests with `RUN-TESTS'.") (defparameter *passed* '() "Contains the passed tests after executing tests with `RUN-TESTS'.") (defvar *drop-into-debugger* nil " If T, `RUN-TEST' will let a failing test drop into the debugger, otherwise the condition will be handled after printing the error message and the tests will continue. The default is NIL, i.e. not to drop into debugger. This mode is geared towards batch testing. ") (defvar *signal-after-run-tests* T " Whether to signal an `ERROR' at the end of `RUN-TEST' if any of the tests failed. The default is T (yes, signal). " ) (defun test-failed (c) "Registers `*CURRENT-TEST' as failed." (push *current-test* *failed*) (format t "~a~%" c) (format t "~&**** !FAILED: ~a~%" *current-test*) nil ) (defun test-passed () "Registers `*CURRENT-TEST' as passed." (push *current-test* *passed*) (format t "~& => PASSED ~a~%~%" *current-test*) t ) (defun first-docline (sym) "Extract the first line of the documentation as tagline for logging" (let ((docstring (documentation sym 'FUNCTION))) (if docstring (multiple-value-bind (prefix first-line?) (CL-PPCRE:scan-to-strings "^[\\n ]*([^ \\n].*)" docstring) (declare (ignorable prefix)) (if first-line? (aref first-line? 0)))))) (defrestart next-test () " Restart to continue with the next test in the list. Established by `RUN-TESTS'. ") (defrestart abort-tests () " Restart to abort testing. Established by `RUN-TESTS'. ") (defun run-tests () " Runs all tests from `*TESTS*' sorting them accordingly into `*FAILED*' and `*PASSED*'. Conditions of type `ERROR' (like as signalled by an `ASSERT') signalled in the tests result in immediate abortion of its execution and the symbol for the test being pushed to`*FAILED*'. The symbols for tests that execute without signalling an `ERROR' are pushed to `*PASSED*'. Parameters modifying behaviour: - `*DROP-INTO-DEBUGGER*' -- instead of just registering a test as failed when a condition is signalled, let the signal propagate upwards the stack, so that restarts NEXT-TEST or ABORT-TESTS can be selected. Default behaviour: Handle the signal in `RUN-TESTS' internally. - '*SIGNAL-AFTER-RUN-TESTS*' -- Signal an error at the end of `RUN-TESTS' if any tests failed. This is the default. Specification: `TEST:RUNNING-TESTS', `TEST:FAILING-ASSERTIONS-DURING-RUN-TESTS'. See also: `-DOC-', `TEST:FAILING-ASSERTIONS-IN-TESTS'. " (setf *failed* '()) (setf *passed* '()) (format t "~&------------------------------------------------~%~%") (format t "~&*tests*~8t = ~a~%~%" *tests*) (restart-case (dolist (test (reverse *tests*)) ;; We set *CURRENT-TEST*, so auxilliary functions like TEST-PASSED can access it during ;; loop iteration. Strictly speaking this is not necessary (we could pass TEST ;; explcicitely to the auxilliaries) but it make handling of "what test is currently ;; executing?" more uniform, also for a possible later integration of reporting hooks. (let ((*current-test* test)) (format t "---- ~a::~a ----~%" (package-name (symbol-package test)) test) (let ((tagline (first-docline test))) (if tagline (format t " ;; ~a~%" tagline))) (if *drop-into-debugger* (progn (restart-case (progn (handler-bind ((error #'test-failed)) (apply (symbol-function test) nil)) (test-passed)) (next-test () t))) (handler-case (progn (apply (symbol-function test) nil) (test-passed)) (simple-error (c) (test-failed c)))))) (abort-tests () t)) (format t "~&------------------------------------------------~%") (if *failed* (progn (format t "FAILED: ~a of ~a tests: ~a~%" (length *failed*) (length *tests*) (reverse *failed*)) (if *signal-after-run-tests* (error (format nil "~a of ~a tests failed: ~a." (length *failed*) (length *tests*) (reverse *failed*))))) (format t "ALL PASSED (~a tests)~%" (length *tests*))) (reverse *failed*)) ;;; * -- Assertions -----------------------------------------------------------------------------------------| (defmacro assert-no-condition (&body body) " Execute BODY, assert that BODY signals no condition. Specification: `TEST::ASSERTING-FOR-NO-CONDITION' See also: `-DOC-'. " `(handler-case (progn ,@body) (condition (c) (error "~s unexpectedly signaled ~s" (cons 'progn (quote ,body)) c)))) (defmacro assert-condition (condition &body body) " Execute BODY, assert that BODY signals condition CONDITION or one derived from CONDITION. - Signal `ERROR' if no condition has been raised. - Let `ASSERT' signal error if condition type is not as expected. Specification: `TEST::ASSERTING-FOR-CONDITIONS'. See also: `-DOC-'. " `(handler-case (progn ,@body) (condition (c) (assert (typep c ,condition))) (:no-error (&rest rest) (declare (ignorable rest)) (assert nil nil "~a did not signal a condition" (cons 'progn (quote ,body)))))) (defmacro assert-and-capture-condition ((var cond) &body form+body) " Execute a FORM, assert that a condition COND occurs and capture it in VAR, then execute BODY. Call as (assert-and-capture-condition (VAR COND) FORM &body BODY). Execute FORM, assert that it signals a condition COND or one derived from COND, capture the signalled condition, bind to VAR and execute BODY. This makes it possible to check further assertions (in BODY) that depend on the condition instance that has been signalled. Specification: `TEST::ASSERTING-AND-CAPTURING-CONDITIONS'. See also: `-DOC-'. " (destructuring-bind (form &body body) form+body (with-gensyms (signalled-condition) `(let ((,var nil)) (handler-case ,form (condition (,signalled-condition) (setf ,var ,signalled-condition) T) (:no-error (&rest rest) (declare (ignore rest)) (error "~a did not signal a condition" (cons 'progn (quote ,body))))) (assert (typep ,var ,cond)) ,@body)))) ;;; * -- Resetting state ------------------------------------------------------------------------------------| (defun reset-test-run-state () " Reset the dynamic state left over from `RUN-TEST'. This is only useful in some tests of the framework itself. " (setf *current-test* nil) (setf *failed* nil) (setf *passed* nil)) (defun reset-test-definitions () " Reset the test definitions. This is only useful in some tests of the framework itself. " (reset-test-run-state) (setf *tests* '()))
15,038
Common Lisp
.lisp
329
40.696049
110
0.642275
m-e-leypold/cl-simple-test
0
0
0
GPL-3.0
9/19/2024, 11:51:15 AM (Europe/Amsterdam)
9d1171fcfc2a2454f71277ba752c76648f9af0388f35fa36f2d0c4e7c891f852
42,360
[ -1 ]
42,361
tests.lisp
m-e-leypold_cl-simple-test/tests.lisp
;;; ------------------------------------------------------------------------*- common-lisp -*-| ;;; ;;; de.m-e-leypold.cl-simple-test -- a simple testing framework for common lisp. ;;; Copyright (C) 2022 M E Leypold ;;; ;;; This program is free software: you can redistribute it and/or modify ;;; it under the terms of the GNU General Public License as published by ;;; the Free Software Foundation, either version 3 of the License, or ;;; (at your option) any later version. ;;; ;;; This program is distributed in the hope that it will be useful, ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; ;;; You should have received a copy of the GNU General Public License ;;; along with this program. If not, see <https://www.gnu.org/licenses/>. ;;; ;;; For alternative licensing options, see README.md ;;; ;;; ;;; * Options -----------------------------------------------------------------------------------------------| (declaim (optimize (speed 0) (space 0) (compilation-speed 0) (debug 3) (safety 3))) ;;; * Define package ----------------------------------------------------------------------------------------| (defpackage :de.m-e-leypold.cl-simple-test/tests (:documentation "Testing cl-simple-test") (:use :common-lisp :de.m-e-leypold.cl-simple-test :de.m-e-leypold.cl-simple-utils :de.m-e-leypold.cl-simple-utils/wrapped-streams) (:import-from :de.m-e-leypold.cl-simple-utils/basic-test :assert! :run-tests! :deftest! :deftest-registry! :end-test-registry! :set-flag :clear-flags :*flags* :explain :trace-expr :test-failure) (:export :run-tests! :defining-tests :running-tests :failing-assertions-in-tests :failing-assertions-during-run-tests :current-test-maintenance :asserting-for-conditions :asserting-for-no-condition :asserting-and-capturing-conditions )) (in-package :de.m-e-leypold.cl-simple-test/tests) (inject-package-local-nickname "TEST" :de.m-e-leypold.cl-simple-test/tests :de.m-e-leypold.cl-simple-test) (deftest-registry!) (defun reset-all-state () (reset-test-definitions) (clear-flags)) (defun run-tests* () (with-maybe-indented-output (:prefix " | ") (run-tests))) ;;; * The tests themselves ----------------------------------------------------------------------------------| ;;; ** Defining Tests ---------------------------------------------------------------------------------------| (deftest! defining-tests () " Testing `DEFTEST'. `DEFTEST' defines tests. Specification: 1. (DEFTEST F () ...) will define a test of name F. Symbol F will be pushed to *TESTS* (to be available for use by `RUN-TEST'). 2. A function of the same name F will will be defined, containing the body given in DEFTEST and wrapped into a form, so that during execution of F, `*CURRENT-TEST*' is set to F. 3. The documentation string is obligatory and will be attached to the function. If there is no documentation string given, this will result in an error at macro expansion time. " (explain "Resetting cl-simple-test.") (reset-all-state) (explain "Defining tests T1, T2, which push *CURRENT-TEST* as flags.") (deftest t1 () "t1 doc" (format t "~& t1 here.~&") (set-flag *current-test*)) (deftest t2 () "t2 doc" (format t "~& t2 here.~&") (set-flag *current-test*)) (assert! (equal *tests* '(t2 t1))) (explain "Executing tests t2, t1.") (t2) (t1) (trace-expr *flags*) (assert! (equal *flags* '(t1 t2))) (explain "Checking docstrings.") (assert! (equal "t1 doc" (documentation 't1 'function))) (assert! (equal "t2 doc" (documentation 't2 'function))) (handler-case (macroexpand '(deftest t3 () t)) (error () ) ; that's what it the result should be. (condition (e) (test-failure :explanation (format nil "Expanding DEFTEST T3 should have signalled an `error' condition, instead it signalled ~S" e))) (:NO-ERROR (e1 e2) (declare (ignorable e1 e2)) (test-failure :explanation "No error signalled by DEFTEST T3 supposed to trigger a failing assertion")))) ;;; ** Running tests ----------------------------------------------------------------------------------------| (deftest! current-test-maintenance () " Testing the expected maintenace of `*CURRENT-TEST'. `*CURRENT-TEST*' is set to the symbol of the currently executing test during execution of a test. This is also true if the test is not executed under the control of `RUN-TEST' but instead invoked directly. " (explain "Resetting cl-simple-test.") (reset-all-state) (explain "Defining some tests (T1-3) that register their execution by pushing *CURRENT-TEST* to *FLAGS*.") (deftest t1 () "t1 executes without failure" (set-flag *current-test*)) (deftest t2 () "t2 executes without failure" (set-flag *current-test*)) (deftest t3 () "t3 executes without failure" (set-flag *current-test*)) (explain "Executing the tests under control of RUN-TESTS.") (run-tests*) (assert! (equal *flags* '(T3 T2 T1))) (explain "Now running T1, T3 by invoking them directly") (clear-flags) (assert! (not *flags*)) ;; sanity check (t1) (t2) (assert! (equal *flags* '(T2 T1)))) (deftest! running-tests () " Testing `RUN-TESTS'. `RUN-TESTS' runs tests in order of their definition; no signal means success. If no condition is signalled: 1.`RUN-TESTS' will run tests in the order of their definition and not signal. 2. No tests will be flagged as failed, i.e. `*FAILED*' will be empty. 3. All tests (as symbols) will be pushed into `*PASSED*'. " (explain "Resetting cl-simple-test.") (reset-all-state) (explain "Defining some tests (T1-3) that register their execution by setting flags. None fail.") (deftest t1 () "t1 executes without failure" (set-flag 't1)) (deftest t2 () "t2 executes without failure" (set-flag 't2)) (deftest t3 () "t3 executes without failure" (set-flag 't3)) (handler-case (run-tests*) (condition (c) (test-failure :explanation (format nil "RUN-TESTS signalled ~S, but should not have" (type-of c))))) (assert (equal *failed* '())) (assert (equal *flags* '(T3 T2 T1))) ; run order (assert (equal *passed* '(T3 T2 T1)))) ;;; ** Assertion handling ----------------------------------------------------------------------------------| ;;; *** Errors are not handled in the test procedures -------------------------------------------------------| (deftest! failing-assertions-in-tests () " Testing failing assertions in tests. Errors signaled by assertions in tests escape the test functions. Context: `ASSERT' signals a `CONDITION' of type `SIMPLE-ERROR' if the predicate given is not true. Specification: When invoking a test function directly, such a `SIMPLE-ERROR' will not be handled by the test function, but escape from the test function. " (explain "Resetting cl-simple-test.") (reset-all-state) (explain "Defining test T1, which has a failing assertion.") (deftest t1 () "" (assert (= 3 (+ 1 1)))) (explain "Invoking this test: An error is signalled.") (handler-case (t1) (error () ) ; that's what it the result should be. (condition (e) (test-failure :explanation (format nil "T1 should have signalled an `error' condition, instead it signalled ~S" e))) (:NO-ERROR (e1 e2) (declare (ignorable e1 e2)) (test-failure :explanation "No error signalled by test function T1 supposed to trigger a failing assertion")))) ;;; *** Error handling by `RUN-TESTS' -----------------------------------------------------------------------| (deftest! failing-assertions-during-run-tests () " Testing tracking and handling of failing assertions (resulting in failed tests) by `RUN-TESTS'. `RUN-TESTS' executes defined tests; signalled errors count as failed. `RUN-TESTS' executes tests. 1. In order of their definition. 2. Tests that execute without signalling will be counted as passed and registered in `*PASSED*' (as symbol). 3. Tests that signal an error (as from a failing assertion) are counted as failed and registered in `*FAILED*'. 4. Signalled conditions different from `ERROR' just escape the tests. 5. After running all tests, if any tests failed, `RUN-TESTS' will signal an error with a message like \"#<SIMPLE-ERROR \"2 of 4 tests failed: (T2 T4).\" {1004CC4EA3}>\" This is the default behaviour: To just continue running tests and signal an error at the end if any failed. Some variables allow to modify this behaviour: 6. If `*SIGNAL-AFTER-RUN-TESTS*' is NIL, no error according to (5) will be signalled at the end of `RUN-TESTS'. Instead `RUN-TESTS' will just return the list of failed tests (in order of their execution). 7. When setting *DROP-INTO-DEBUGGER*, `ERROR' signals escape `RUN-TEST' and are not handled internally. 8. When signalling, a restart `NEXT-TEST' is available to continue with the next test (either by a handler or interactively in the debugger. 9. When signalling, a restart `ABORT-TEST' is available to abort testing, but still evaluate whether tests failed and process failures according to (5). " (explain "Resetting cl-simple-test.") (reset-all-state) (explain "Defining some tests (T1-4) that register their execution by setting flags. Some fail (T2, T4).") (deftest t1 () "t1 executes without failure" (set-flag 't1)) (deftest t2 () "t2 has a failing assertion" (set-flag 't2) (assert nil) (set-flag 't2.not-aborted)) (deftest t3 () "t3 executes without failure" (set-flag 't3)) (deftest t4 () "t4 signals an error" (set-flag 't4) (error "t4 error signal") (set-flag 't4.not-aborted)) (explain "Running the defined tests.") (handler-case (run-tests*) (error (e) (let ((message (format nil "~S" e))) (trace-expr message) (explain "Resulting error message must be a test summary.") (assert! (cl-ppcre:scan "^#<SIMPLE-ERROR.*2 of 4 tests failed: [(]T2 T4[)][.].*[>]" message)))) (condition (e) (test-failure :explanation (format nil "RUN-TEST should have signalled an `error' condition, instead it signalled ~S." e))) (:NO-ERROR (e1 e2) (declare (ignorable e1 e2)) (test-failure :explanation "No error signalled by `RUN-TEST', but it should have."))) (assert! (equal *FAILED* '(T4 T2))) (assert! (equal *PASSED* '(T3 T1))) (explain "RUN-TESTS again with *SIGNAL-AFTER-RUN-TESTS* off") (let* ((*signal-after-run-tests* nil) (failed (run-tests*))) (trace-expr failed) (assert! (equal failed '(T2 T4)))) (explain "RUN-TESTS again with *DROP-into-debugger*, restarting with NEXT-TEST") (let ((handler-invocations 0) (failed '())) (handler-bind ((error #'(lambda (c) (declare (ignorable c)) (format t " error handler: ~S." c) (incf handler-invocations) (invoke-restart 'next-test))) (condition #'(lambda (c) (test-failure :explanation (format nil "run-tests signalled ~s but should have signalled an error." (type-of c)))))) (let ((*drop-into-debugger* t) (*signal-after-run-tests* nil)) (setf failed (run-tests*)))) (assert! (equal failed '(T2 T4))) (assert! (= 2 handler-invocations)) (assert! (equal *passed* '(T3 T1))) (assert! (equal *failed* '(T4 T2)))) (explain "RUN-TESTS again with *DROP-into-debugger*, restarting with ABORT-TESTS") (let ((handler-invocations 0) (failed '())) (handler-bind ((error #'(lambda (c) (declare (ignorable c)) (incf handler-invocations) (invoke-restart 'abort-tests))) (condition #'(lambda (c) (test-failure :explanation (format nil "run-tests signalled ~s but should have signalled an error." (type-of c)))))) (let ((*drop-into-debugger* t) (*signal-after-run-tests* nil)) (setf failed (run-tests*)))) (assert! (equal failed '(T2))) (assert! (= 1 handler-invocations)) (assert! (equal *passed* '(T1))) (assert! (equal *failed* '(T2))))) ;;; ** Special assertion macros -----------------------------------------------------------------------------| (define-condition C1 (condition) ()) (define-condition C2 (condition) ()) (define-condition C1+ (C1) ()) (deftest! asserting-for-conditions () " Testing `ASSERT-CONDITION'. `ASSERT-CONDITION' checks if a form signals a condition of a specific type. (assert-condition COND BODY) will 1. Signal `ERROR' if the execution of BODY doesn't signal any condition. 2. If it signals a condition, assert that signalled condition is of type COND or derived from COND. If it is not, the condition signalled by `ASSERT' will escape the form. " (explain "Trying with a body that does not signal") (handler-case (assert-condition 'C1 ) (error (c) (format t "OK, got: ~a~%" c)) ; that's what it the result should be. (condition (c) (test-failure :explanation (format nil (here-text* "ASSERT-CONDITION with non-signalling body should have" "signalled an `error' condition, instead it signalled ~S") c))) (:NO-ERROR (x) (declare (ignorable x)) (test-failure :explanation "No error signalled by ASSERT-CONDITION with non-signalling body"))) (explain "Trying with a body that signals a different condition") (handler-case (assert-condition 'C1 (signal 'C2)) (error (c) (format t "OK, got: ~5:i~a~%" c)) ; that's what it the result should be. (condition (c) (test-failure :explanation (format nil (here-text* "ASSERT-CONDITION with body signalling different condition than expected" "should have signalled an `error' condition, instead it signalled ~S") c))) (:NO-ERROR (x) (declare (ignorable x)) (test-failure :explanation (here-text* "No error signalled by ASSERT-CONDITION with" "body signalling different condition than expected")))) (explain "Trying with a body that signal a condition derived from the specified one") (handler-case (assert-condition 'C1 (signal 'C1+)) (condition (c) (test-failure :explanation (format nil (here-text* "ASSERT-CONDITION with body signalling a derived condition" "should not have signalled any condition, instead it signalled ~a~%") c))) (:NO-ERROR (x) (declare (ignorable x)) (format t "OK, no signal.~%"))) (explain "Trying with a body that signals the expected condition.") (handler-case (assert-condition 'C1 (signal 'C1)) (condition (c) (test-failure :explanation (format nil (here-text* "ASSERT-CONDITION with body signalling a the expected condition" "should not have signalled any condition, instead it signalled ~a~%") c))) (:NO-ERROR (x) (declare (ignorable x)) (format t "OK, no signal.~%")))) (deftest! asserting-for-no-condition () " Testing `ASSERT-NO-CONDITION'. `ASSERT-NO-CONDITION' checks if a form does not signal a condition. (assert-no-condition COND BODY) will 1. Signal `ERROR' if the execution of BODY does signal any condiotion. 2. If it does not signal a condition, the ASSERT-NO-CONDITION form will evaluate to the value of BODY. " (explain "Trying a body that does not signal.") (handler-case (assert-no-condition (progn )) (condition (c) (test-failure :explanation (format nil (here-text* "ASSERT-NO-CONDITION with non-signalling" "should not have signalled any condition, instead it signalled ~a~%") c))) (:NO-ERROR (x) (declare (ignorable x)) (format t "OK, no signal.~%"))) (explain "Trying a body that signals") (handler-case (assert-no-condition (signal 'C1)) (error (c) (format t "OK, got: ~5:i~a~%" c)) ; that's what it the result should be. (condition (c) (test-failure :explanation (format nil (here-text* "ASSERT-CONDITION with body signalling" "should have signalled an `error' condition, instead it signalled ~S") c))) (:NO-ERROR (x) (declare (ignorable x)) (test-failure :explanation (here-text* "No error signalled by ASSERT-CONDITION with body signalling")))) ) (deftest! asserting-and-capturing-conditions () " Testing `ASSERT-AND-CAPTURE-CONDITION'. `ASSERT-AND-CAPTURE-CONDITION' checks if a form signal a condition of a specific type, but also captures the condition in a variable for further checks. The form (assert-condition (VAR CONDITION-TYPE) FORM BODY) will 1. Create a new variable binding VAR. 2. Execute FORM. 3. Signal an `ERROR' if the execution of BODY doesn't signal any condition. 4. If it signals a condition, assert that signalled condition is of type CONDITION-TYPE or derived from CONDITION-TYPE. If it is not, the condition signalled by `ASSERT' will escape the form. 5. If it signals a condition this will be captured in VAR. 6. BODY will be executed, VAR is available in the scope of BODY. " (explain "Trying with a body that does not signal") (handler-case (assert-and-capture-condition (captured-condition 'C1) (progn )) (error (c) ; that's what it the result should be. (format t "OK, got: ~a~%" c)) (condition (c) (test-failure :explanation (format nil (here-text* "ASSERT-CONDITION with non-signalling body should have" "signalled an `error' condition, instead it signalled ~S") c))) (:NO-ERROR (x) (declare (ignorable x)) (test-failure :explanation "No error signalled by ASSERT-CONDITION with non-signalling body"))) (explain "Trying with a body that signals a different condition") (handler-case (assert-and-capture-condition (captured-condition 'C1) (signal 'C2)) (error (c) (format t "OK, got: ~5:i~a~%" c)) ; that's what it the result should be. (condition (c) (test-failure :explanation (format nil (here-text* "ASSERT-CONDITION with body signalling different condition than expected" "should have signalled an `error' condition, instead it signalled ~S") c))) (:NO-ERROR (x) (declare (ignorable x)) (test-failure :explanation (here-text* "No error signalled by ASSERT-CONDITION with" "body signalling different condition than expected")))) (explain "Trying with a body that signal a condition derived from the specified one") (handler-case (assert-and-capture-condition (captured 'C1) (signal 'C1+) (format t "Captured: ~S~%" captured) (assert (typep captured 'C1+))) (condition (c) (test-failure :explanation (format nil (here-text* "ASSERT-CONDITION with body signalling a derived condition" "should not have signalled any condition, instead it signalled ~a~%") c))) (:NO-ERROR (x) (declare (ignorable x)) (format t "OK, no signal.~%"))) (explain "Trying with a body that signals the expected condition") (handler-case (assert-and-capture-condition (captured 'C1) (signal 'C1)) (condition (c) (test-failure :explanation (format nil (here-text* "ASSERT-CONDITION with body signalling a the expected condition" "should not have signalled any condition, instead it signalled ~a~%") c))) (:NO-ERROR (x) (declare (ignorable x)) (format t "OK, no signal.~%")))) ;;; * Package epilog ----------------------------------------------------------------------------------------| (end-test-registry!) ;;; * -------------------------------------------------------------------------------------------------------| ;;; WRT the outline-* and comment-* variables, see the comment in test.lisp ;;; ;;; Local Variables: ;;; eval: (progn (outshine-mode 1) (column-enforce-mode 1) (toggle-truncate-lines 1)) ;;; fill-column: 110 ;;; column-enforce-column: 110 ;;; outline-regexp: ";;; [*]\\{1,8\\} " ;;; comment-add: 2 ;;; End:
20,765
Common Lisp
.lisp
528
34.191288
110
0.630705
m-e-leypold/cl-simple-test
0
0
0
GPL-3.0
9/19/2024, 11:51:15 AM (Europe/Amsterdam)
4c659629210eeeab06c68378202fce73b19bc2fd36a4e4086885fd72e25a04aa
42,361
[ -1 ]
42,362
load.lisp
m-e-leypold_cl-simple-test/load.lisp
;;; ------------------------------------------------------------------------*- common-lisp -*-| ;;; ;;; de.m-e-leypold.cl-simple.test -- a simple testing framework for common lisp. ;;; Copyright (C) 2022 M E Leypold ;;; ;;; This program is free software: you can redistribute it and/or modify ;;; it under the terms of the GNU General Public License as published by ;;; the Free Software Foundation, either version 3 of the License, or ;;; (at your option) any later version. ;;; ;;; This program is distributed in the hope that it will be useful, ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; ;;; You should have received a copy of the GNU General Public License ;;; along with this program. If not, see <https://www.gnu.org/licenses/>. ;;; ;;; For alternative licensing options, see README.md ;;; (declaim (optimize (speed 0) (space 0) (compilation-speed 0) (debug 3) (safety 3))) (asdf:load-system "de.m-e-leypold.cl-simple-test/load-all") ;;; * -------------------------------------------------------------------------------------------------------| ;;; WRT the outline-* and comment-* variables, see the comment in test.lisp ;;; Local Variables: ;;; eval: (progn (outshine-mode 1) (column-enforce-mode 1) (toggle-truncate-lines 1)) ;;; fill-column: 110 ;;; column-enforce-column: 110 ;;; outline-regexp: ";;; [*]\\{1,8\\} " ;;; comment-add: 2 ;;; End:
1,536
Common Lisp
.lisp
31
48.193548
110
0.608117
m-e-leypold/cl-simple-test
0
0
0
GPL-3.0
9/19/2024, 11:51:15 AM (Europe/Amsterdam)
9d031ca527de31a05e1a5fcdc0d93a329b4be6a54f525f2792c10b4bffcf3a25
42,362
[ -1 ]
42,363
test.lisp
m-e-leypold_cl-simple-test/test.lisp
;;; ------------------------------------------------------------------------*- common-lisp -*-| ;;; ;;; de.m-e-leypold.cl-simple.test -- a simple testing framework for common lisp. ;;; Copyright (C) 2022 M E Leypold ;;; ;;; This program is free software: you can redistribute it and/or modify ;;; it under the terms of the GNU General Public License as published by ;;; the Free Software Foundation, either version 3 of the License, or ;;; (at your option) any later version. ;;; ;;; This program is distributed in the hope that it will be useful, ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; ;;; You should have received a copy of the GNU General Public License ;;; along with this program. If not, see <https://www.gnu.org/licenses/>. ;;; ;;; For altermative licensing options, see README.md ;;; ;;; ;;; * Options -----------------------------------------------------------------------------------------------| (declaim (optimize (speed 0) (space 0) (compilation-speed 0) (debug 3) (safety 3))) ;;; * Load system to be tested & the tests ------------------------------------------------------------------| (asdf:load-system "de.m-e-leypold.cl-simple-test/tests") ;;; * Define sandbox for tests ------------------------------------------------------------------------------| (defpackage :de.m-e-leypold.cl-simple-test/run-tests (:documentation "Testing cl-simple-test") (:use :common-lisp :de.m-e-leypold.cl-simple-test/tests)) (in-package :de.m-e-leypold.cl-simple-test/run-tests) ;;; * Actually executing the tests --------------------------------------------------------------------------| (run-tests!) ;;; * -------------------------------------------------------------------------------------------------------| ;;; WRT the outline-* and comment-* variables, see the comment in test.lisp ;;; Local Variables: ;;; eval: (progn (outshine-mode 1) (column-enforce-mode 1) (toggle-truncate-lines 1)) ;;; fill-column: 110 ;;; column-enforce-column: 110 ;;; outline-regexp: ";;; [*]\\{1,8\\} " ;;; comment-add: 2 ;;; End:
2,210
Common Lisp
.lisp
43
49.930233
110
0.535466
m-e-leypold/cl-simple-test
0
0
0
GPL-3.0
9/19/2024, 11:51:15 AM (Europe/Amsterdam)
24bc902a2eb42e74b3a2eb4c415d6be3c0529cd831b5402121d612d364bc0ba8
42,363
[ -1 ]
42,364
de.m-e-leypold.cl-simple-test.asd
m-e-leypold_cl-simple-test/de.m-e-leypold.cl-simple-test.asd
;;; ------------------------------------------------------------------------*- common-lisp -*-| ;;; ;;; de.m-e-leypold.cl-simple-test -- a simple testing framework for common lisp. ;;; Copyright (C) 2022 M E Leypold ;;; ;;; This program is free software: you can redistribute it and/or modify ;;; it under the terms of the GNU General Public License as published by ;;; the Free Software Foundation, either version 3 of the License, or ;;; (at your option) any later version. ;;; ;;; This program is distributed in the hope that it will be useful, ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; ;;; You should have received a copy of the GNU General Public License ;;; along with this program. If not, see <https://www.gnu.org/licenses/>. ;;; ;;; For altermative licensing options, see README.md ;;; ;;; ---- System -----------------------------------------------------------------------------| (defsystem "de.m-e-leypold.cl-simple-test" :author "M E Leypold [elegant-weapons ( AT) m-e-leypold (DOT) de]" :licence "GPL3" :description "Simple assertion based testing" :depends-on ("cl-ppcre" "de.m-e-leypold.cl-simple-utils") :components ((:file "simple-test"))) (defsystem "de.m-e-leypold.cl-simple-test/tests" :author "M E Leypold [elegant-weapons ( AT) m-e-leypold (DOT) de]" :licence "GPL3" :depends-on ("cl-ppcre" "de.m-e-leypold.cl-simple-test" "de.m-e-leypold.cl-simple-utils" "de.m-e-leypold.cl-simple-utils/basic-test") :description "Tests and specifications for CL-SIMPLE-TEST" :components ((:file "tests"))) (defsystem "de.m-e-leypold.cl-simple-test/prerequisites" :author "M E Leypold [elegant-weapons ( AT) m-e-leypold (DOT) de]" :licence "GPL3" :depends-on ("cl-ppcre" "de.m-e-leypold.cl-simple-utils" "de.m-e-leypold.cl-simple-utils/basic-test") :description "Just all external prerequisites" :components ()) (defsystem "de.m-e-leypold.cl-simple-test/load-all" :author "M E Leypold [elegant-weapons ( AT) m-e-leypold (DOT) de]" :licence "GPL3" :description "Load all systems in CL-SIMPLE-TEST" :depends-on ("de.m-e-leypold.cl-simple-test" "de.m-e-leypold.cl-simple-test/tests"))
2,355
Common Lisp
.asd
49
45.122449
95
0.647955
m-e-leypold/cl-simple-test
0
0
0
GPL-3.0
9/19/2024, 11:51:15 AM (Europe/Amsterdam)
f91d1c4e91c607494d8f0860d9e736c1e31818e532a0af63b8a3812643da55d6
42,364
[ -1 ]
42,369
Makefile
m-e-leypold_cl-simple-test/Makefile
# # de.m-e-leypold.cl-simple-test - Simple test framework # Copyright (C) 2022 M E Leypold # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. # # For alternative licensing options, see README.md # all:: check-warnings ASD-FILE = $(wildcard *.asd) PRIMARY-SYSTEM = $(ASD-FILE:%.asd=%) SHORT-NAME = $(lastword $(subst ., ,$(PRIMARY-SYSTEM))) TEST-RUNNER = $(strip $(wildcard test.lisp)) AUTHOR-ID ?= m-e-leypold GITLAB ?= [email protected]:$(AUTHOR-ID)/$(SHORT-NAME).git GITHUB ?= [email protected]:$(AUTHOR-ID)/$(SHORT-NAME).git ORIGIN ?= LSD:projects/$(SHORT-NAME).git MAJOR-VERSIONS ?= 1 2 3 4 5 6 7 8 9 10 $(info PRIMARY-SYSTEM = $(PRIMARY-SYSTEM)) $(info SHORT-NAME = $(SHORT-NAME)) $(info TEST-RUNNER = $(SHORT-NAME)) clean:: rm -f *~ *.log *.fasl CHECK-PREP = sbcl --noinform --disable-debugger --eval '(asdf:load-system "$(PRIMARY-SYSTEM)/prerequisites")' --quit LOAD = sbcl --noinform --disable-debugger --eval '(asdf:load-system "$(PRIMARY-SYSTEM)/load-all")' --quit ifeq ($(TEST-RUNNER),) check:: # There are no checks here else CHECK = sbcl --noinform --disable-debugger --load $(TEST-RUNNER) --quit check:: $(CHECK) @echo endif # The procedures below are for the original author of this package. dev: git-setup Project git-setup: # This are the upstream repositories git remote rm GITLAB || true git remote rm GITHUB || true git remote add GITLAB $(GITLAB) git remote add GITHUB $(GITHUB) git fetch GITLAB git fetch GITHUB Project: git clone -b project --single-branch . Project cd Project && git remote add UPSTREAM $(ORIGIN) cd Project && git fetch UPSTREAM cd Project && git merge UPSTREAM/project cd Project && git push UPSTREAM project cd Project && git push origin project publish: publish-source publish-project publish-project: cd Project && git branch | grep '^[*] project$$' # We only release from project cd Project && \ if git status -s | grep -v '^??'; \ then git status -s ; false; \ else true; \ fi cd Project && git push origin project git push publish-source: check-all git branch | grep '^[*] main$$' # We only release from main if git status -s | grep -v '^??'; \ then git status -s ; false; \ else true; \ fi git push GITLAB main git push GITLAB $(MAJOR-VERSIONS:%=refs/tags/%.*) git push GITHUB main git push GITHUB $(MAJOR-VERSIONS:%=refs/tags/%.*) git push --tags origin main clean-fasl-cache: rm -rf $(HOME)/.cache/common-lisp check-warnings: $(CHECK-PREP) >CHECK-PREP.log 2>&1 $(LOAD) >CHECK.log 2>&1 ! grep -C8 -i "warn" CHECK.log # This could be smarter @echo @grep compiling CHECK.log @echo "No warnings detected." stricter-check: clean-fasl-cache check-warnings check-all: check stricter-check
3,445
Common Lisp
.l
92
35.23913
116
0.689655
m-e-leypold/cl-simple-test
0
0
0
GPL-3.0
9/19/2024, 11:51:15 AM (Europe/Amsterdam)
4ed403dc14c27e1ee18596634118b8c0e91ff1116ef9d262b4ff35f28fc34268
42,369
[ -1 ]
42,388
9.lisp
sarab97_euler/9.lisp
(defun find_prod (sum) (loop for a from 1 to (1- (truncate (/ sum 3))) do (loop for b from (1+ a) to (1- (/ (- sum a) 2)) do (let ((c (- sum a b))) (when (and (> c b) (= (* c c) (+ (* a a) (* b b)))) (return-from find_prod (* a b c))))))) (find_prod 1000)
276
Common Lisp
.lisp
7
35.571429
57
0.473881
sarab97/euler
0
0
0
GPL-3.0
9/19/2024, 11:51:15 AM (Europe/Amsterdam)
289c8325a3c6473ea8b2d3194c5f03c5fbc1518bb317ae04b751746058bebcb1
42,388
[ -1 ]
42,389
10.lisp
sarab97_euler/10.lisp
;; The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. ;; Find the sum of all the primes below two million. (defun sieve (maximum) (loop :with maxi = (ash (1- maximum) -1) :with stop = (ash (isqrt maximum) -1) :with sieve = (make-array (1+ maxi) :element-type 'bit :initial-element 0) :for i :from 1 :to maxi :for odd-number = (1+ (ash i 1)) :when (zerop (sbit sieve i)) :collect odd-number :into values :when (<= i stop) :do (loop :for j :from (* i (1+ i) 2) :to maxi :by odd-number :do (setf (sbit sieve j) 1)) :finally (return (cons 2 values)))) (reduce #'+ (sieve 2000000)) ;; Output
622
Common Lisp
.lisp
16
35.875
76
0.621891
sarab97/euler
0
0
0
GPL-3.0
9/19/2024, 11:51:15 AM (Europe/Amsterdam)
4f1fe0f0008eab922ca4008ac0d922fff65247a50201bd50b01004c56d95f029
42,389
[ -1 ]
42,390
8.lisp
sarab97_euler/8.lisp
;; The four adjacent digits in the 1000-digit number that have the greatest product are 9 × 9 × 8 × 9 = 5832. ;; 73167176531330624919225119674426574742355349194934 ;; 96983520312774506326239578318016984801869478851843 ;; 85861560789112949495459501737958331952853208805511 ;; 12540698747158523863050715693290963295227443043557 ;; 66896648950445244523161731856403098711121722383113 ;; 62229893423380308135336276614282806444486645238749 ;; 30358907296290491560440772390713810515859307960866 ;; 70172427121883998797908792274921901699720888093776 ;; 65727333001053367881220235421809751254540594752243 ;; 52584907711670556013604839586446706324415722155397 ;; 53697817977846174064955149290862569321978468622482 ;; 83972241375657056057490261407972968652414535100474 ;; 82166370484403199890008895243450658541227588666881 ;; 16427171479924442928230863465674813919123162824586 ;; 17866458359124566529476545682848912883142607690042 ;; 24219022671055626321111109370544217506941658960408 ;; 07198403850962455444362981230987879927244284909188 ;; 84580156166097919133875499200524063689912560717606 ;; 05886116467109405077541002256983155200055935729725 ;; 71636269561882670428252483600823257530420752963450 ;; Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product? (defconstant nums "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450") (defun calc_prod (string start end) (reduce '* (map 'list (lambda (x) (- (char-code x) 48)) (subseq string start end)))) (defun get_prod (string n) (let ((len (length string))) (loop for i from 0 below (- len n) maximizing (calc_prod string i (+ i n))))) (get_prod nums 13) ;; Output 23514624000
2,738
Common Lisp
.lisp
31
86.645161
1,021
0.886456
sarab97/euler
0
0
0
GPL-3.0
9/19/2024, 11:51:15 AM (Europe/Amsterdam)
5bf52d70ac61e9a255ae0189806f00de702812e54fd0c61c20d46911e3937189
42,390
[ -1 ]
42,391
6.lisp
sarab97_euler/6.lisp
;; The sum of the squares of the first ten natural numbers is, ;; $$1^2 + 2^2 + ... + 10^2 = 385$$ ;; The square of the sum of the first ten natural numbers is, ;; $$(1 + 2 + ... + 10)^2 = 55^2 = 3025$$ ;; Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is $3025 - 385 = 2640$. ;; Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. (defun sums_square (n) (expt (/ (* n (+ n 1)) 2) 2) ) (defun sq_sums (n) (/ (* n (+ n 1) (+ (* 2 n) 1)) 6) ) (- (sums_square 100) (sq_sums 100)) ;; Output 25164150
640
Common Lisp
.lisp
14
43.785714
137
0.634461
sarab97/euler
0
0
0
GPL-3.0
9/19/2024, 11:51:15 AM (Europe/Amsterdam)
8c6f1efe3cb61dd98b42f90cb71da732f14cf25d8bf5a24eae6fd2e2ba47e5ad
42,391
[ -1 ]
42,392
5.lisp
sarab97_euler/5.lisp
;; 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. ;; What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? (defun get_gcd (x y) (if (= y 0) x (get_gcd y (mod x y)))) (defun get_lcm (x y) (/ (* x y) (get_gcd x y))) (reduce #'getlcm (loop for i from 1 to 20 collect i)) ;; Output 232792560
406
Common Lisp
.lisp
10
38.2
109
0.683673
sarab97/euler
0
0
0
GPL-3.0
9/19/2024, 11:51:15 AM (Europe/Amsterdam)
51302b2bd2551c79c8204cb49d439b03ac2488051d3e0c8acf68af12b70e5838
42,392
[ -1 ]
42,393
1.lisp
sarab97_euler/1.lisp
;; If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. ;; Find the sum of all the multiples of 3 or 5 below 1000. (let ((sum 0)) (loop for a from 1 to 999 if (or (= (mod a 3) 0) (= (mod a 5) 0)) do (incf sum a) ) (print sum) ) ;; Output 233168
340
Common Lisp
.lisp
10
31.2
132
0.638037
sarab97/euler
0
0
0
GPL-3.0
9/19/2024, 11:51:15 AM (Europe/Amsterdam)
34fbfadbe217ba31489cd1137f8854b49ad40cfc90ab0aae31273b522e454be5
42,393
[ -1 ]
42,394
4.lisp
sarab97_euler/4.lisp
;; A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99. ;; Find the largest palindrome made from the product of two 3-digit numbers. (defun is-palindrome (n) (let ((original n) (reverse 0)) (loop while (> n 0) do (setq reverse (+ (* 10 reverse) (mod n 10))) (setq n (floor n 10))) (if (= original reverse) (return-from is-palindrome 1) (return-from is-palindrome 0)))) (defun find-palindrome () (let ((x 100) (y 100) (num 0)) (loop (setq y 100) (loop (when (= (is-palindrome (* x y)) 1) (if (< num (* x y)) (setq num (* x y)) ) ) (incf y 1) (when (> y 1000) (return y)) ) (incf x 1) (when (> x 1000) (return x)) ) (return-from find-palindrome num) ) ) (print (find-palindrome)) ;; Output 906609
844
Common Lisp
.lisp
34
21.852941
137
0.628109
sarab97/euler
0
0
0
GPL-3.0
9/19/2024, 11:51:15 AM (Europe/Amsterdam)
0950d97f7e90683735946cc01f95405e972d99dab7d43774e79a6a51e077d49b
42,394
[ -1 ]
42,395
3.lisp
sarab97_euler/3.lisp
;; The prime factors of 13195 are 5, 7, 13 and 29. ;; What is the largest prime factor of the number 600851475143 ? (defun largest-prime-factor (n) (let ((result 2)) (loop for i from 2 to (floor (sqrt n)) do (when (zerop (mod n i)) (loop while (zerop (mod n i)) do (setf n (/ n i))) (setf result i))) (if (> n 1) n result))) (largest-prime-factor 600851475143) ;; Output 6857
395
Common Lisp
.lisp
11
33.181818
64
0.656992
sarab97/euler
0
0
0
GPL-3.0
9/19/2024, 11:51:15 AM (Europe/Amsterdam)
c0e276451a43b1ce60e45eb30bd938791cded8d34595ec2d538ce90b1e5b2a7e
42,395
[ -1 ]
42,396
2.lisp
sarab97_euler/2.lisp
;; Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: ;; 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... ;; By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. (let ((a 0) (b 1) (c 0) (sum 0)) (loop (setq c (+ a b)) (when (> c 4000000) (print sum) (return sum)) (if (= (mod c 2) 0) (incf sum c)) (setq a b) (setq b c) ) ) ;; Output 4613732
522
Common Lisp
.lisp
16
30.25
143
0.649402
sarab97/euler
0
0
0
GPL-3.0
9/19/2024, 11:51:15 AM (Europe/Amsterdam)
0ec61ef0683832cb93d7016c6612e1309461c4725d82fcdc8701ff54d910c296
42,396
[ -1 ]
42,397
7.lisp
sarab97_euler/7.lisp
;; By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. ;; What is the 10 001st prime number? (defun is-prime (n) (loop for i from 2 to (floor (/ n 2)) if (= (mod n i) 0) do (return-from is-prime 0) ) 1) (let ((c 2) (p 3)) (loop (loop while (= (is-prime p) 0) do (incf p 1)) (when (= c 10001) (return)) (incf c 1) (incf p 2) ) (print p) ) ;; Output 104743
442
Common Lisp
.lisp
19
20.263158
103
0.582339
sarab97/euler
0
0
0
GPL-3.0
9/19/2024, 11:51:15 AM (Europe/Amsterdam)
a08481a00752ba7f1bbeaa349325d75f70a58058d54c0e7c7c3b6d5acfe266b2
42,397
[ -1 ]
42,423
jsonparse.lisp
lucabrini_unimib-json-parser/Lisp/jsonparse.lisp
;;;; -*- Mode: Lisp -*- ;;;; Luca Brini 879459 (defun jsonparse (json-string) (let ((json-char-list (remove-whitespaces (str-to-chr-list json-string)))) (or (jsonparse-array json-char-list) (jsonparse-object json-char-list) (error "Error: invalid JSON string")))) ;;; JSONPARSE ARRAY ;;; This function checks if there are '[' and ']' ;;; In case of no chars between the brackets, then JSONARRAY will be ;;; the only element of the list. ;;; Otherwise, it starts to parsing the values in between. (defun jsonparse-array (json-char-list) (cond ((string-equal (car json-char-list) "[") (if (string-equal (cadr json-char-list) "]") (values (cons 'JSONARRAY '()) (cddr json-char-list)) (multiple-value-bind (elements char-list-rest) (jsonparse-elements (cdr json-char-list)) (if (not (string-equal (car char-list-rest) "]")) (error "Syntax Error: cannot find closing ]") (values (cons 'JSONARRAY elements) (cdr char-list-rest)))))))) ;;; This function checks if there is a ',' after parsing the first ;;; value. If so, it parses the next value until it reaches the end ;;; of the json-array (defun jsonparse-elements (json-char-list) (multiple-value-bind (element next-element-and-rest) (jsonparse-value json-char-list) (cond ((string-equal (car next-element-and-rest) ",") (multiple-value-bind (next-element char-list-rest) (jsonparse-elements (cdr next-element-and-rest)) (values (cons element next-element) char-list-rest))) (T (values (list element) next-element-and-rest))))) ;;; JSONPARSE OBJECT ;;; This function checks if there are '{' and '}' ;;; In case of no chars between the brackets, then JSONOBJ will be ;;; the only element of the list. ;;; Otherwise, it starts to parsing the members in between. (defun jsonparse-object (json-char-list) (cond ((string-equal (car json-char-list) "{") (if (string-equal (cadr json-char-list) "}") (values (cons 'JSONOBJ '()) (cddr json-char-list)) (multiple-value-bind (members char-list-rest) (jsonparse-members (cdr json-char-list)) (if (not (string-equal (car char-list-rest) "}")) (error "Syntax Error: cannot find closing }") (values (cons 'JSONOBJ members) (cdr char-list-rest)))))))) ;;; This function checks if there is a ',' after parsing the first ;;; pair. If so, it parses the next pair until it reaches the end ;;; of the json-obj (defun jsonparse-members (json-char-list) (multiple-value-bind (pair next-pair-and-rest) (jsonparse-pair json-char-list) (cond ((string-equal (car next-pair-and-rest) ",") (multiple-value-bind (next-pair char-list-rest) (jsonparse-members (cdr next-pair-and-rest)) (values (cons pair next-pair) char-list-rest))) (T (values (list pair) next-pair-and-rest))))) ;;; This function checks if after the key there is the mandatory ':' ;;; If not, it throws an error. Otherwise it parses the value of the ;;; pair. (defun jsonparse-pair (json-char-list) (multiple-value-bind (pair-key raw-value-and-rest) (jsonparse-pair-key json-char-list) (if (string-equal (car raw-value-and-rest) ":") (multiple-value-bind (pair-value char-list-rest) (jsonparse-value (cdr raw-value-and-rest)) (values (list pair-key pair-value) char-list-rest)) (error "Syntax Error: missing a colon")))) ;;; This functions checks if the key is a string. Otherwise it throws ;;; an error. (defun jsonparse-pair-key (json-char-list) (if (not (string-equal (car json-char-list) "\"")) (error "Syntax Error: cannot find a valid pair key") (multiple-value-bind (pair-key raw-value-and-rest) (jsonparse-string (cdr json-char-list)) (values (chr-list-to-str pair-key) raw-value-and-rest)))) ;;; JSONPARSE VALUE ;;; This function parse the value in the json-char-list ;;; It supports: Strings, Objects, Arrays, Numbers, Booleans and null (defun jsonparse-value (json-char-list) (cond ((string-equal (car json-char-list) "\"") (multiple-value-bind (str char-list-rest) (jsonparse-string (cdr json-char-list)) (values (chr-list-to-str str) char-list-rest))) ((string-equal (car json-char-list) "{") (multiple-value-bind (json-object char-list-rest) (jsonparse-object json-char-list) (values json-object char-list-rest))) ((string-equal (car json-char-list) "[") (multiple-value-bind (json-array char-list-rest) (jsonparse-array json-char-list) (values json-array char-list-rest))) ((or (digit-char-p (car json-char-list)) (string-equal (car json-char-list) "-")) (multiple-value-bind (json-num char-list-rest) (jsonparse-number json-char-list) (values json-num char-list-rest))) ((string-equal (car json-char-list) "t") (values 'true (subseq json-char-list 4))) ((string-equal (car json-char-list) "f") (values 'false (subseq json-char-list 5))) ((string-equal (car json-char-list) "n") (values 'null (subseq json-char-list 4))) (T (error "Syntax Error: unknown value type")))) (defun jsonparse-string (json-char-list) (cond ((string-equal (first json-char-list) "\"") (values NIL (cdr json-char-list))) (T (multiple-value-bind (str char-list-rest) (jsonparse-string (cdr json-char-list)) (values (cons (car json-char-list) str) char-list-rest))))) ;;; This function takes the digits of the number from the ;;; json-char-list by calling the jsonparse-number-proxy function. ;;; Suddently, it gets the number value with digits-list-to-number (defun jsonparse-number (json-char-list) (if (and (string-equal (car json-char-list) "0") (not (string-equal (cdr json-char-list) "."))) (error "Syntax Error: after a 0 is mandatory to have a .") (multiple-value-bind (digits-char-list char-list-rest) (jsonparse-number-proxy json-char-list) (let ((json-number (digits-list-to-number digits-char-list))) (values json-number char-list-rest))))) ;;; This function checks ;;; - If there's a '.' in the digits-list ;;; - If there's a 'e' or 'E' in the digits-list (defun jsonparse-number-proxy (json-char-list) (multiple-value-bind (int decimals-and-rest) (jsonparse-number-integer json-char-list) (if (string-equal (car decimals-and-rest) ".") (multiple-value-bind (floating-number exponential-and-rest) (jsonparse-number-floating int (cdr decimals-and-rest)) (if (or (string-equal (car exponential-and-rest) "e") (string-equal (car exponential-and-rest) "E")) (multiple-value-bind (exponential-number char-list-rest) (jsonparse-number-exponential floating-number (cdr exponential-and-rest)) (values exponential-number char-list-rest)) (values floating-number exponential-and-rest))) (if (or (string-equal (car decimals-and-rest) "e") (string-equal (car decimals-and-rest) "E")) (multiple-value-bind (exponential-number char-list-rest) (jsonparse-number-exponential int (cdr decimals-and-rest)) (values exponential-number char-list-rest)) (values int decimals-and-rest))))) ;;; This function checks the integer number, considering also the ;;; sign. By setting the optional parameter 'ignore-singn' to T, ;;; it will ignore the presence of the sign (defun jsonparse-number-integer (json-char-list &optional (ignore-sign NIL)) (cond ((or (string-equal (car json-char-list) "+") (string-equal (car json-char-list) "-")) (if (and (not ignore-sign) (not (null (cdr json-char-list)))) (multiple-value-bind (digit char-list-rest) (jsonparse-number-integer (cdr json-char-list) T) (values (cons (car json-char-list) digit) char-list-rest)) (error "Syntax Error: sign in not in the correct position"))) ((or (null json-char-list) (not (digit-char-p (car json-char-list)))) (values NIL json-char-list)) (T (multiple-value-bind (digt char-list-rest) (jsonparse-number-integer (cdr json-char-list) T) (values (cons (car json-char-list) digt) char-list-rest))))) ;;;This functions include in the digits list the '.' (defun jsonparse-number-floating (int json-char-list) (multiple-value-bind (decimals char-list-rest) (jsonparse-number-integer json-char-list T) (values (append int '(#\.) decimals) char-list-rest))) ;;;This functions include in the digits list the 'e' (defun jsonparse-number-exponential (current-number json-char-list) (multiple-value-bind (exponent char-list-rest) (jsonparse-number-integer json-char-list) (values (append current-number '(#\e) exponent) char-list-rest))) ;;; JSON ACCESS (defun jsonaccess (json-object &rest raw-fields) (let ((fields (flatten raw-fields))) (cond ((null fields) json-object) ((eq (car json-object) 'JSONOBJ) (jsonaccess-object (cdr json-object) fields)) ((eq (car json-object) 'JSONARRAY) (jsonaccess-array (cdr json-object) fields)) (T (error "JSON Access Error: unknown object type"))))) ;;; This function extracts the value of the pair with key equal to the ;;; first element of the fields list. (defun jsonaccess-object (json-object fields) (cond ((null json-object) NIL) ((not (stringp (car fields))) (error "JSON Access Error: invalid field")) ((= (length fields) 1) (jsonaccess-object-one-field json-object fields)) (T (if (not (string-equal (caar json-object) (car fields))) (jsonaccess-object (cdr json-object) fields) (jsonaccess (cadar json-object) (cdr fields)))))) ;;; This function extracts the value of the pair with a certain key (defun jsonaccess-object-one-field (json-object field) (cond ((null json-object) NIL) (T (if (not (string-equal (caar json-object) (car field))) (jsonaccess-object-one-field (cdr json-object) field) (cadar json-object))))) ;;; This function extracts the value of the element at the first ;;; index in the list (defun jsonaccess-array (json-array indexes) (cond ((or (>= (car indexes) (length json-array)) (minusp (car indexes))) (error "JSON Access Error: index out of bounds")) ((not (numberp (car indexes))) (error "JSON Access Error: invalid field")) (T (jsonaccess (nth (car indexes) json-array) (cdr indexes))))) ;;; JSONREAD (defun jsonread (filename) (if (or (null filename) (string= filename "")) (error "JSON Read: invalid filename. Filename can't be nullish") (with-open-file (stream filename :if-does-not-exist :error :direction :input) (jsonparse (read-char-by-char stream))))) ;;; this function reads, char by char, a stream. (defun read-char-by-char (stream) (let ((chr (read-char stream NIL NIL))) (cond ((null chr) chr) (T (cons chr (read-char-by-char stream)))))) ;;; JSONDUMP (defun jsondump (json-object filename) (if (or (null filename) (string= filename "")) (error "JSON Dump: invalid filename. Filename can't be nullish") (with-open-file (out filename :direction :output :if-exists :supersede :if-does-not-exist :create) (format out "~A" (chr-list-to-str (jsonreverse json-object 1))) filename))) ;;; This function, given a certain json-object, returns the ;;; corrispondent json string representation of the json-object. ;;; The parameter depth is used to determine how much tabs need ;;; to be placed before a value or a key. (defun jsonreverse (json-object depth) (flatten (cond ((eq (car json-object) 'JSONOBJ) (list #\{ #\Newline (jsonreverse-object (cdr json-object) depth) (jsonreverse-tab-dispenser (1- depth)) #\})) ((eq (car json-object) 'JSONARRAY) (list #\[ #\Newline (jsonreverse-array (cdr json-object) depth) (jsonreverse-tab-dispenser (1- depth)) #\])) (T (error "JSON Reverse Error: unknown object type "))))) ;;; Given the members of an object, it returns their ;;; json string representation (defun jsonreverse-object (json-members depth) (if (null (car json-members)) #\Space (list (jsonreverse-tab-dispenser depth) (jsonreverse-string (caar json-members)) #\Space #\: #\Space (jsonreverse-value (cadar json-members) depth) (if (not (null (cdr json-members))) (list #\, #\Newline (jsonreverse-object (cdr json-members) depth)) #\Newline)))) ;;; Given the elements of an array, it returns their ;;; json string representation (defun jsonreverse-array (json-elements depth) (if (null (car json-elements)) #\Space (list (jsonreverse-tab-dispenser depth) (jsonreverse-value (car json-elements) depth) (if (not (null (cdr json-elements))) (list #\, #\Newline (jsonreverse-array (cdr json-elements) depth)) #\Newline)))) ;;; This function converts a parsed json-value to its string json-value (defun jsonreverse-value (json-value depth) (cond ((stringp json-value) (jsonreverse-string json-value)) ((numberp json-value) (str-to-chr-list (write-to-string json-value))) ((or (eq json-value 'true) (eq json-value 'false) (eq json-value 'null)) (jsonreverse-constant json-value)) (T (jsonreverse json-value (1+ depth))))) ;;; Adding '"' at both sides of the string, after converting it to ;;; a list of chars. (defun jsonreverse-string (json-string) (list #\" (str-to-chr-list json-string) #\")) ;;; Converting the parsed NULL, TRUE and FALSE values to their ;;; json string representation (defun jsonreverse-constant (json-constant) (str-to-chr-list (string-downcase (string json-constant)))) ;;; This function adds a certain number of horizontal tabs based ;;; on the depth parameter (defun jsonreverse-tab-dispenser (depth) (if (> depth 0) (cons #\Tab (jsonreverse-tab-dispenser (1- depth))))) ;;; UTILS SECTION ;;; From string to char-list and viceversa (defun str-to-chr-list (str) (coerce str 'list)) (defun chr-list-to-str (char-list) (coerce char-list 'string)) ;;; This function flats a list. It brings nested lists to the same ;;; level of nesting. (defun flatten (lst) (cond ((null lst) nil) ((atom lst) (list lst)) (t (append (flatten (car lst)) (flatten (cdr lst)))))) ;;; These utility functions convert a digit-char-list to ;;; real CL numbers. Floating, integers, and in-scientific ;;; notation numbers are supported (defun digits-list-to-number (digits-list) (multiple-value-bind (raw-base-part raw-exponent-part) (split-list-at-element digits-list #\e) (if (not (null raw-exponent-part)) (if (member #\. raw-exponent-part) (error "Syntax Error: exponent in exponential notation must be an integer") (let* ((base-number (digits-list-to-number-floating-or-int raw-base-part)) (exponent-number (digits-list-to-number-integer raw-exponent-part))) (float (* base-number (expt 10 exponent-number))))) (digits-list-to-number-floating-or-int raw-base-part)))) ;;; This functions checks if the input digit-char-list contains a dot. ;;; If so, it gets the integer and decimal part. The decimals then ;;; are divided by 10^(length decimals) in order to get the real ;;; decimals value. Finally, integer part and decimals part are ;;; added together. (defun digits-list-to-number-floating-or-int (digits-list) (multiple-value-bind (raw-integer-part raw-decimal-part) (split-list-at-element digits-list #\.) (if (not (null raw-decimal-part)) (let* ((integer-number (digits-list-to-number-integer raw-integer-part)) (decimal-number (float (/ (digits-list-to-number-integer raw-decimal-part) (expt 10 (length raw-decimal-part)))))) (if (minusp integer-number) (- integer-number decimal-number) (+ integer-number decimal-number))) (digits-list-to-number-integer raw-integer-part)))) ;;; This functions check if there's the sign. Then it gets the ;;; number value by calling the helper function. The final value ;;; is the number from the helper multiplied by -1 if sign was ;;; negative or by +1 if sign was positive or not present. (defun digits-list-to-number-integer (input-digits-list) (multiple-value-bind (sign unsigned-digits-list) (cond ((digit-char-p (car input-digits-list)) (values 1 input-digits-list)) ((string-equal (car input-digits-list) "+") (values 1 (cdr input-digits-list))) ((string-equal (car input-digits-list) "-") (values -1 (cdr input-digits-list)))) (let ((reverse-unsigned-digits-list (reverse unsigned-digits-list))) (* sign (digits-list-to-number-integer-helper reverse-unsigned-digits-list))))) ;;; This function takes a reverse digit-char-list number and ;;; compute the real value. It uses the following mechanism: ;;; 123 = 1*10^2 + 2*10^1 + 3*10^0 (defun digits-list-to-number-integer-helper (digits-list &optional (position 0)) (cond ((or (null digits-list)) 0) (T (let ((incremental-number (digits-list-to-number-integer-helper (cdr digits-list) (1+ position)))) (+ (* (digit-char-p (car digits-list)) (expt 10 position)) incremental-number))))) ;;; This functions split a list in two sublist at a certain ;;; element. If element is not in the list, then it returns the ;;; initial list and NIL. Otherwise, it returns the sublists (defun split-list-at-element (lst target-element) (let ((sublist-after (member target-element lst))) (if (not sublist-after) (values lst NIL) (values (subseq lst 0 (- (length lst) (length sublist-after))) (cdr sublist-after))))) ;; removing the target-element ;;; This function removes all the whitespaces from the json-char-list. ;;; When it encounters a start string char (\") it calls the function ;;; which will ignore all the whitespace chars in the string. (defun remove-whitespaces (json-char-list) (let ((chr (car json-char-list))) (cond ((null json-char-list) json-char-list) ((or (string-equal chr #\Space) (string-equal chr #\Tab) (string-equal chr #\Return) (string-equal chr #\Newline)) (remove-whitespaces (cdr json-char-list))) ((string-equal chr "\"") (cons chr (remove-whitespaces-ignore (cdr json-char-list)))) (t (cons chr (remove-whitespaces (cdr json-char-list))))))) (defun remove-whitespaces-ignore (json-char-list) (let ((chr (car json-char-list))) (cond ((null json-char-list) (error "Error: syntax error")) ((and (string-equal chr "\"") (string-equal (cadr json-char-list) "\"")) (cons chr (cons (cadr json-char-list) (remove-whitespaces-ignore (cddr json-char-list))))) ((string-equal chr "\"") (cons chr (remove-whitespaces (cdr json-char-list)))) (T (cons chr (remove-whitespaces-ignore (cdr json-char-list)))))))
18,816
Common Lisp
.lisp
421
40.266033
71
0.681674
lucabrini/unimib-json-parser
0
0
0
GPL-3.0
9/19/2024, 11:51:15 AM (Europe/Amsterdam)
cd9126008faf4e652e6d057de479afc52e8beb8e5c5ca657704c50f4d7d30f21
42,423
[ -1 ]
42,425
jsonreverse.pl
lucabrini_unimib-json-parser/Prolog/jsonreverse.pl
%%%% -*- Mode: Prolog -*- %%%% Luca Brini 879459 % JSONReverse % Handling case where object is a jsonobj jsonreverse(jsonobj(Members), AtomString) :- jsonreverse_members(Members, IntermediateString), concat_atom(['{', IntermediateString, '}'], AtomString), !. % Handling case where object is a jsonarray jsonreverse(jsonarray(Elements), AtomString) :- jsonreverse_elements(Elements, IntermediateString), concat_atom(['[', IntermediateString, ']'], AtomString), !. % Members obj --> Member string : Base case jsonreverse_members([], ''). % Members obj --> Member string : only one pair jsonreverse_members([Pair | []], AtomString) :- jsonreverse_pair(Pair, AtomString). % Members obj --> Member string : More than one Pair jsonreverse_members([Pair | MoreMembers], AtomString) :- jsonreverse_pair(Pair, PairString), jsonreverse_members(MoreMembers, MoreMembersString), concat_atom([PairString, ',', MoreMembersString], AtomString). % Pair obj --> Pair string : Only one Pair jsonreverse_pair((RawKey, Value), AtomString) :- jsonreverse_value(RawKey, Key), jsonreverse_value(Value, IntermediateString), concat_atom([Key, ':', IntermediateString], AtomString). % Reversing elements: from list of values to string jsonreverse_elements([], ''). jsonreverse_elements([Element | []], AtomString) :- jsonreverse_value(Element, AtomString). jsonreverse_elements([Value | MoreElements], AtomString) :- jsonreverse_value(Value, ValueString), jsonreverse_elements(MoreElements, MoreElementsString), concat_atom([ValueString, ',', MoreElementsString], AtomString). jsonreverse_value(false, false). jsonreverse_value(true, true). jsonreverse_value(null, null). % JSONObject value is a string. jsonreverse_value(JSONString, String) :- string(JSONString), concat_atom(['\"', JSONString, '\"'], String), !. % Handling the case where JSONObject value is a number. jsonreverse_value(JSONNumber, String) :- number(JSONNumber), concat_atom([JSONNumber], String), !. % Handling the case where JSONObject value is a composite object jsonreverse_value(JSONObj, String) :- jsonreverse(JSONObj, String), !.
2,189
Common Lisp
.l
53
38.264151
68
0.730047
lucabrini/unimib-json-parser
0
0
0
GPL-3.0
9/19/2024, 11:51:15 AM (Europe/Amsterdam)
8716e0bba2fdbd65cb22ab7c87f35c732031f0a6decf509e8e6565f21b7be351
42,425
[ -1 ]
42,426
test.pl
lucabrini_unimib-json-parser/Prolog/test.pl
%%%% -*- Mode: Prolog -*- %%%% Luca Brini 879459 :- [jsonparse]. test_obj_vuoto :- jsonparse('{}', jsonobj([])). test_array_vuoto :- jsonparse('[]', jsonarray([])). test_two_pair_std :- jsonparse('{ "nome" : "Arthur", "cognome" : "Dent" }', jsonobj([ ("nome", "Arthur"), ("cognome", "Dent") ])). test_two_pair_string :- jsonparse("{ \"nome\" : \"Arthur\", \"cognome\" : \"Dentino\" }", jsonobj([ ("nome", "Arthur"), ("cognome", "Dentino") ])). test_superbook_std :- jsonparse('{ "modello" : "SuperBook 1234", "anno di produzione" : 2014, "processore" : { "produttore" : "EsseTi", "velocità di funzionamento (GHz)" : [1, 2, 4, 8] } }', jsonobj([ ("modello", "SuperBook 1234"), ("anno di produzione", 2014), ("processore", jsonobj([ ("produttore", "EsseTi"), ("velocità di funzionamento (GHz)", jsonarray([1, 2, 4, 8]))])) ])). test_superbook_string :- jsonparse("{ \"modello\" : \"SuperBook 1234\", \"anno di produzione\" : 2014, \"processore\" : { \"produttore\" : \"EsseTi\", \"velocità di funzionamento (GHz)\" : [1, 2, 4, 8] } }", jsonobj([ ("modello", "SuperBook 1234"), ("anno di produzione", 2014), ("processore", jsonobj([ ("produttore", "EsseTi"), ("velocità di funzionamento (GHz)", jsonarray([1, 2, 4, 8]))])) ])). test_menu_std :- jsonparse('{ "type": "menu", "value": "File", "items": [ {"value": "New", "action": "CreateNewDoc"}, {"value": "Open", "action": "OpenDoc"}, {"value": "Close", "action": "CloseDoc"} ] }', jsonobj([ ("type", "menu"), ("value", "File"), ("items", jsonarray([ jsonobj([("value", "New"), ("action", "CreateNewDoc")]), jsonobj([("value", "Open"), ("action", "OpenDoc")]), jsonobj([("value", "Close"), ("action", "CloseDoc")])])) ]) ). test_menu_string :- jsonparse("{ \"type\": \"menu\", \"value\": \"File\", \"items\": [ {\"value\": \"New\", \"action\": \"CreateNewDoc\"}, {\"value\": \"Open\", \"action\": \"OpenDoc\"}, {\"value\": \"Close\", \"action\": \"CloseDoc\"} ] }", jsonobj([ ("type", "menu"), ("value", "File"), ("items", jsonarray([ jsonobj([("value", "New"), ("action", "CreateNewDoc")]), jsonobj([("value", "Open"), ("action", "OpenDoc")]), jsonobj([("value", "Close"), ("action", "CloseDoc")])])) ]) ). % true test_access_special_1 :- jsonaccess(jsonobj(Members), [], jsonobj(Members)). %false pr_test_access_special_2 :- jsonaccess(jsonarray(_), [], _). test_access_special_2 :- not(pr_test_access_special_2). % O = jsonobj([(”nome”, ”Arthur”), (”cognome”, ”Dent”)]) % R = ”Arthur” test_parse_access_1 :- jsonparse('{"nome" : "Arthur", "cognome" : "Dent"}', O), jsonaccess(O, ["nome"], "Arthur"). % O = jsonobj([(”nome”, ”Arthur”), (”cognome”, ”Dent”)]) % R = ”Arthur” test_parse_access_2 :- jsonparse('{"nome": "Arthur", "cognome": "Dent"}', O), jsonaccess(O, "nome", "Arthur"). % Z = jsonobj([(”name”, ”Zaphod”), (”heads”, jsonarray([”Head1”, ”Head2”]))]) % R = ”Head2” test_parse_access_zaphod :- jsonparse('{"nome" : "Zaphod", "heads" : ["Head1", "Head2"]}', % Attenzione al newline. Z), jsonaccess(Z, ["heads", 1], "Head2"). % false pr_test_mismatched_brackets :- jsonparse('[}', _). test_mismatched_brackets :- not(pr_test_mismatched_brackets). % false pr_test_parse_access_out_of_bounds :- jsonparse('[1, 2, 3]', A), jsonaccess(A, [3], _). test_parse_access_out_of_bounds :- not(pr_test_parse_access_out_of_bounds). % No. pr_test_reverted_1 :- jsonparse('{"nome" : "Arthur", "cognome" : "Dent"}', jsonobj([jsonarray(_) | _])). test_reverted_1 :- not(pr_test_reverted_1). % N = "Arthur" test_reverted_2 :- jsonparse('{"nome" : "Arthur", "cognome" : "Dent"}', jsonobj([("nome", "Arthur") | _])). % R = "Dent" test_reverted_3 :- jsonparse('{"nome" : "Arthur", "cognome" : "Dent"}', JSObj), jsonaccess(JSObj, ["cognome"], "Dent"). test_once(Predicate) :- write(Predicate), call(Predicate), write(": ✅\n"). test_all :- test_once(test_obj_vuoto), test_once(test_array_vuoto), test_once(test_two_pair_std), test_once(test_two_pair_string), test_once(test_superbook_std), test_once(test_superbook_string), test_once(test_menu_std), test_once(test_menu_string), test_once(test_access_special_1), test_once(test_access_special_2), test_once(test_parse_access_1), test_once(test_parse_access_2), test_once(test_parse_access_zaphod), test_once(test_mismatched_brackets), test_once(test_parse_access_out_of_bounds), test_once(test_reverted_1), test_once(test_reverted_2), test_once(test_reverted_3). test :- print('\"'). reloadt :- [test], tty_clear.
5,218
Common Lisp
.l
162
26.154321
77
0.541003
lucabrini/unimib-json-parser
0
0
0
GPL-3.0
9/19/2024, 11:51:15 AM (Europe/Amsterdam)
9ac28b9afd1d344875b2878c94ca4845ca1a3d919eda59ea2304bf47f2c4367a
42,426
[ -1 ]
42,427
jsonaccess.pl
lucabrini_unimib-json-parser/Prolog/jsonaccess.pl
%%%% -*- Mode: Prolog -*- %%%% Luca Brini 879459 % JSONACCESS with Fields list % Base case for fields list : One field in the list jsonaccess(JSONObj, [Field | []], Result) :- jsonaccess(JSONObj, Field, Result), !. % Recursive case for fields list: Two o More fields in the list jsonaccess(JSONObj, [Field | MoreFields], Result) :- jsonaccess(JSONObj, Field, RawResult), jsonaccess(RawResult, MoreFields, Result), !. % JSONACCESS through one Field % Handling the case where Jsonobj is a jsonobj % Special case jsonaccess(jsonobj(Members), [], jsonobj(Members)) :- !. % Forcing backtracking jsonaccess(jsonobj(Members), Field, Result) :- jsonaccess_members(Members, Field, Result). % Handling the case where Jsonobj is a jsonarray jsonaccess(jsonarray(_), [], _) :- fail, !. jsonaccess(jsonarray(Elements), N, Result) :- number(N), jsonaccess_elements(Elements, N, Result). jsonaccess_members([(Field, Result) | _], Field, Result) :- !. jsonaccess_members([ _ | MoreMembers], Field, Result) :- jsonaccess_members(MoreMembers, Field, Result). jsonaccess_elements([Result | _], 0, Result) :- !. jsonaccess_elements([_ | MoreElements], N, Result) :- NewIndex is N - 1, jsonaccess_elements(MoreElements, NewIndex, Result).
1,260
Common Lisp
.l
28
42.5
79
0.711491
lucabrini/unimib-json-parser
0
0
0
GPL-3.0
9/19/2024, 11:51:15 AM (Europe/Amsterdam)
4fc6d4d11e2c15c498246238284d9df832383a5ee7d53aa84cf2b42b701e5525
42,427
[ -1 ]
42,428
jsonparse.pl
lucabrini_unimib-json-parser/Prolog/jsonparse.pl
%%%% -*- Mode: Prolog -*- %%%% Luca Brini 879459 :- [jsonaccess]. :- [jsonreverse]. jsonparse(JSONString, Object) :- atomic(JSONString), atom_chars(JSONString, JSONStringList), phrase(grammar(Object), JSONStringList). grammar(jsonobj([])) --> ['{'], whitespace, ['}'], !. grammar(jsonobj(Members)) --> ['{'], members(Members), ['}'], !. grammar(jsonarray([])) --> ['['], whitespace, [']'], !. grammar(jsonarray(Elements)) --> ['['], values(Elements), [']'], !. % PAIRS GRAMMAR members([Pair | MoreMembers]) --> pair(Pair), [','], % dividing members by ',' members(MoreMembers). % parsing members recursively members([Pair]) --> pair(Pair), !. % parsing single pair % PAIR GRAMMAR pair((Attribute, Value)) --> whitespace, string(Attribute), whitespace, [':'], value(Value), !. values([Value | MoreElements]) --> value(Value), [','], values(MoreElements). values([Element]) --> value(Element), !. value(Value) --> whitespace, ( grammar(Value) | string(Value) | number(Value) | boolean(Value) | null(Value) ), whitespace, !. % STRING GRAMMAR string('') --> ['"'], ['"']. % empty string string(String) --> ['"'], format_string(String), ['"']. format_string(String) --> chars(Chars), {Chars \= []}, % checking if string is not empty { atom_chars(RawAtom, Chars), % converting chars list to atom string_to_atom(String, RawAtom) % and then to Prolog string }. % stacking up chars of a string recursively using DGCs. chars([]) --> []. chars([Char | Chars]) --> char(Char), !, chars(Chars). % need to escaping some chars char(Char) --> [Char], {check_char(Char)}. % check_char/1 : check if a given Char is valid or not. % Char must to be instantiate. check_char('\"'). check_char(Char) :- string_codes(Char, [_ | _]). % NUMBER GRAMMAR number(Number) --> format_digits(Digits), { atom_chars(RawNumberAtom, Digits), atom_number(RawNumberAtom, Number) }. format_digits(Digits) --> digits(Digits), {Digits \= []}. % Parsing digits of a number digits([Digit | Digits]) --> digit(Digit), !, digits(Digits). % Base case. It's here due to the left-most SLD policy of Prolog. digits([]) --> []. % Numbers could be positive or negative, floating or integer; % as well as exponential (<base>e<exponent> = <base>*10^<exponent>) digit('-') --> ['-']. digit('+') --> ['+']. digit('.') --> ['.']. digit('e') --> ['e'] | ['E']. digit(Digit) --> [Digit], {char_type(Digit, digit)}. % BOOLEAN GRAMMAR boolean(true) --> ['t'], ['r'], ['u'], ['e']. boolean(false) --> ['f'],['a'],['l'],['s'],['e']. % NULL GRAMMAR null(null) --> ['n'], ['u'], ['l'], ['l']. % WHITESPACE GRAMMAR whitespace --> ['\t'] , !, whitespace. % it manages indentations, whitespace --> ['\n'], ! , whitespace. % line feeds, whitespace --> ['\r'], !, whitespace. % and carriage returns whitespace --> [' '], !, whitespace. % spaces whitespace --> []. jsonread(FileName, JSON) :- read_file_to_string(FileName, String, []), jsonparse(String, JSON). jsondump(JSON, FileName) :- jsonreverse(JSON, JSONAtom), string_to_atom(JSONString, JSONAtom), open(FileName, write, Stream), write(Stream, JSONString), close(Stream). % tty_clear valid only for UNIX systems. reload :- [jsonparse], tty_clear.
3,547
Common Lisp
.l
122
25.319672
70
0.580418
lucabrini/unimib-json-parser
0
0
0
GPL-3.0
9/19/2024, 11:51:15 AM (Europe/Amsterdam)
2f19717d2b1f559894704112ae2bfb59f7c5a8b1859236b9bb044c39e122b2c3
42,428
[ -1 ]
42,444
serve.lisp
kasimirmoilanen_byte-temple/serve.lisp
(ql:quickload :hunchentoot) (ql:quickload :spinneret) ; On a unix system, the root seems to be the user's home directory. (defparameter *path* "./path/to/file-directory/") (defparameter *server* (make-instance 'hunchentoot:easy-acceptor :port 33333 :address "0.0.0.0" :document-root (truename *path*))) (defun start () (hunchentoot:start *server*)) (defun server-stop () (hunchentoot:stop *server*)) (hunchentoot:define-easy-handler (main :uri "/") () (spinneret:with-html-string (:html (:head) (:body (:h1 "Files") (:h4 "Made with secret alien technology...") (loop :for i :in (uiop:directory-files *path*) :collect (:p (:a :href (file-namestring i) (file-namestring i)))) (:br) ))))
896
Common Lisp
.lisp
23
28.782609
74
0.550808
kasimirmoilanen/byte-temple
0
0
0
GPL-3.0
9/19/2024, 11:51:15 AM (Europe/Amsterdam)
0b300852464323827e16857dfc1ffee5576f98d2df87155ff587df2b5139a012
42,444
[ -1 ]
42,461
random-string.lisp
Carht_lisp-scripts/random-string.lisp
;; Generate random string in CL (defparameter *characters* (concatenate 'string "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789")) (defparameter *nums* "0123456789") (defun random-element (lst) (aref lst (random (length lst)))) (defun random-string (length-characters) (if (zerop length-characters) nil (cons (random-element *characters*) (random-string (1- length-characters))))) (defun random-num (length-nums) (if (zerop length-nums) nil (cons (random-element *nums*) (random-num (1- length-nums))))) (defun rand-str (length-chars) (let ((list-of-random-chars (random-string length-chars))) (concatenate 'string list-of-random-chars))) (defun rand-nums (length-nums) (let ((list-of-random-nums (random-num length-nums))) (concatenate 'string list-of-random-nums)))
875
Common Lisp
.lisp
25
30.6
60
0.697509
Carht/lisp-scripts
0
0
2
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
b8524bcd2dc952239034139434016d73166cb0679fab1784440e5d78ce41ee53
42,461
[ -1 ]
42,462
clean-files.lisp
Carht_lisp-scripts/clean-files.lisp
(ql:quickload '(:osicat :uiop :cl-fad)) (defun directory-p (filepath) "Is a directory?" (if (cl-fad:directory-exists-p filepath) t nil)) (defparameter *dir* nil "Path of files in a directory") (defmacro clean-file (filepath) "Create a process-info object and call the command shred for the file." `(defparameter *clean* (uiop:wait-process (uiop:launch-program (concatenate 'string "/usr/bin/shred -u -n 5 " ,filepath))))) (defun walker (filepath) "Return a list of files and subdirectories of a directory, recursively." (cl-fad:walk-directory filepath (lambda (file) (push (format nil "~A" file) *dir*)) :directories t)) (defun clean-files (list-of-files) "Clean the files of the walker path." (mapcar #'(lambda (file) (if (directory-p file) (format t "Directory: ~A~%" file) (progn (format t "Cleaning file: ~A~%" file) (clean-file file)))) list-of-files)) (defun secure-delete (filepath) "If `filepath' is a directory, apply clean over all sub directories. If `filepath' is not a directory, clean the file, securely." (let ((is-dir? (directory-p filepath))) (if is-dir? (progn (walker filepath) (clean-files *dir*)) (clean-file filepath)))) (defun usage () "Return the usage documentation." (format t "For files: (secure-delete \"/home/user/file.txt\") Delete the file securely. For directory: (secure-delete \"/home/user/directory/\") Delete securely all files recursively. The main application shred: https://www.man7.org/linux/man-pages/man1/shred.1.html"))
1,622
Common Lisp
.lisp
46
30.804348
91
0.673899
Carht/lisp-scripts
0
0
2
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
8f44369cf477180ffa1cfdf8f345d4f46310744475e2164f340487319cf952e2
42,462
[ -1 ]
42,463
postgresql-conn.lisp
Carht_lisp-scripts/postgresql-conn.lisp
(ql:quickload "postmodern") (use-package :postmodern) (connect-toplevel "databasename" "username" "userpass" "hostip" :port 5454) (query "SELECT column_name, data_type FROM information_schema.columns WHERE table_name = 'users';")
232
Common Lisp
.lisp
4
56.5
99
0.769912
Carht/lisp-scripts
0
0
2
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
0ebc9a89fa9f61dd575806f331de5ba2ae7d63549111877671a85264e5371e4b
42,463
[ -1 ]
42,464
list-big-files.lisp
Carht_lisp-scripts/list-big-files.lisp
(ql:quickload '(:osicat :uiop :cl-fad)) (defparameter *dir* nil "All file paths") (defun size-file (filepath) "For some `filepath' return the size." (let ((stat (osicat-posix:stat filepath))) (osicat-posix:stat-size stat))) (defun directory-p (filepath) "Is a directory?" (if (cl-fad:directory-exists-p filepath) t nil)) (defun walker (filepath) "List the files and directories of a directory, recursively." (cl-fad:walk-directory filepath (lambda (file) (push (list (format nil "~A" file) (size-file file)) *dir*)) :directories t)) (defun good-printing (lst) "Good printing for the list of list, the nested list have the filepath and the size." (if (equal nil lst) nil (progn (format t "~A ~A~%" (first (car lst)) (second (car lst))) (good-printing (cdr lst))))) (defun list-big-files (filepath) "Check if the input is a file or a directory, return the list of files ordered by size." (if (directory-p filepath) (progn (setf *dir* nil) (walker filepath) (let ((sorted-filepaths (sort *dir* #'> :key #'second))) (good-printing sorted-filepaths))) (format t "~A ~A" filepath (size-file filepath))))
1,188
Common Lisp
.lisp
34
31.294118
90
0.673345
Carht/lisp-scripts
0
0
2
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
fe8fbd798b9ca089be32d202cd3180dda5feaa6756e73ff65342e62c516401fb
42,464
[ -1 ]
42,485
flake.lock
carjorvaz_learning-lisp/flake.lock
{ "nodes": { "flake-utils": { "locked": { "lastModified": 1667395993, "narHash": "sha256-nuEHfE/LcWyuSWnS8t12N1wc105Qtau+/OdUAjtQ0rA=", "owner": "numtide", "repo": "flake-utils", "rev": "5aed5285a952e0b949eb3ba02c12fa4fcfef535f", "type": "github" }, "original": { "owner": "numtide", "repo": "flake-utils", "type": "github" } }, "nixpkgs": { "locked": { "lastModified": 1675631141, "narHash": "sha256-mYjGoPIFVD+i5UXaf4w5+p8qIqWrZNarLM/P92gl7Xw=", "owner": "nixos", "repo": "nixpkgs", "rev": "04795bedd56074d797e93c70b7efe2e607f39d53", "type": "github" }, "original": { "owner": "nixos", "repo": "nixpkgs", "type": "github" } }, "root": { "inputs": { "flake-utils": "flake-utils", "nixpkgs": "nixpkgs" } } }, "root": "root", "version": 7 }
992
Common Lisp
.l
42
16.619048
73
0.505263
carjorvaz/learning-lisp
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
fe42476a746ed8009bed2a2367595dcf75138c1fcb9efa0556a6ca78fb0fcb6f
42,485
[ -1 ]
42,486
flake.nix
carjorvaz_learning-lisp/flake.nix
# Enter the dev shell with: nix develop { inputs = { nixpkgs.url = "github:nixos/nixpkgs"; flake-utils.url = "github:numtide/flake-utils"; }; outputs = { self, nixpkgs, flake-utils }: flake-utils.lib.eachDefaultSystem (system: let pkgs = nixpkgs.legacyPackages.${system}; in { devShell = pkgs.mkShell { buildInputs = with pkgs; [ rlwrap sbcl lispPackages.quicklisp ]; }; }); }
441
Common Lisp
.l
15
24.133333
74
0.634434
carjorvaz/learning-lisp
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
52be2a306a1363512a44548d0ef933abdffab75ded0c9889d267c495f2db9d20
42,486
[ -1 ]
42,533
enc-cp437.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/babel-20200925-git/src/enc-cp437.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; enc-cp437.lisp --- Implementation of the IBM Code Page 437 ;;; ;;; Copyright (C) 2020, Nicolas Hafner <[email protected]> ;;; ;;; Permission is hereby granted, free of charge, to any person ;;; obtaining a copy of this software and associated documentation ;;; files (the "Software"), to deal in the Software without ;;; restriction, including without limitation the rights to use, copy, ;;; modify, merge, publish, distribute, sublicense, and/or sell copies ;;; of the Software, and to permit persons to whom the Software is ;;; furnished to do so, subject to the following conditions: ;;; ;;; The above copyright notice and this permission notice shall be ;;; included in all copies or substantial portions of the Software. ;;; ;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;;; DEALINGS IN THE SOFTWARE. (in-package #:babel-encodings) (define-character-encoding :cp437 "An 8-bit, fixed-width character encoding from IBM." :aliases '(:oem-us :oem-437 :pc-8 :dos-latin-us) :literal-char-code-limit #xFF) (define-constant +cp437-to-unicode+ #(#x0000 #x0001 #x0002 #x0003 #x0004 #x0005 #x0006 #x0007 #x0008 #x0009 #x000a #x000b #x000c #x000d #x000e #x000f #x0010 #x0011 #x0012 #x0013 #x0014 #x0015 #x0016 #x0017 #x0018 #x0019 #x001a #x001b #x001c #x001d #x001e #x001f #x0020 #x0021 #x0022 #x0023 #x0024 #x0025 #x0026 #x0027 #x0028 #x0029 #x002a #x002b #x002c #x002d #x002e #x002f #x0030 #x0031 #x0032 #x0033 #x0034 #x0035 #x0036 #x0037 #x0038 #x0039 #x003a #x003b #x003c #x003d #x003e #x003f #x0040 #x0041 #x0042 #x0043 #x0044 #x0045 #x0046 #x0047 #x0048 #x0049 #x004a #x004b #x004c #x004d #x004e #x004f #x0050 #x0051 #x0052 #x0053 #x0054 #x0055 #x0056 #x0057 #x0058 #x0059 #x005a #x005b #x005c #x005d #x005e #x005f #x0060 #x0061 #x0062 #x0063 #x0064 #x0065 #x0066 #x0067 #x0068 #x0069 #x006a #x006b #x006c #x006d #x006e #x006f #x0070 #x0071 #x0072 #x0073 #x0074 #x0075 #x0076 #x0077 #x0078 #x0079 #x007a #x007b #x007c #x007d #x007e #x007f #x00c7 #x00fc #x00e9 #x00e2 #x00e4 #x00e0 #x00e5 #x00e7 #x00ea #x00eb #x00e8 #x00ef #x00ee #x00ec #x00c4 #x00c5 #x00c9 #x00e6 #x00c6 #x00f4 #x00f6 #x00f2 #x00fb #x00f9 #x00ff #x00d6 #x00dc #x00a2 #x00a3 #x00a5 #x20a7 #x0192 #x00e1 #x00ed #x00f3 #x00fa #x00f1 #x00d1 #x00aa #x00ba #x00bf #x2310 #x00ac #x00bd #x00bc #x00a1 #x00ab #x00bb #x2591 #x2592 #x2593 #x2502 #x2524 #x2561 #x2562 #x2556 #x2555 #x2563 #x2551 #x2557 #x255d #x255c #x255b #x2510 #x2514 #x2534 #x252c #x251c #x2500 #x253c #x255e #x255f #x255a #x2554 #x2569 #x2566 #x2560 #x2550 #x256c #x2567 #x2568 #x2564 #x2565 #x2559 #x2558 #x2552 #x2553 #x256b #x256a #x2518 #x250c #x2588 #x2584 #x258c #x2590 #x2580 #x03b1 #x00df #x0393 #x03c0 #x03a3 #x03c3 #x00b5 #x03c4 #x03a6 #x0398 #x03a9 #x03b4 #x221e #x03c6 #x03b5 #x2229 #x2261 #x00b1 #x2265 #x2264 #x2320 #x2321 #x00f7 #x2248 #x00b0 #x2219 #x00b7 #x221a #x207f #x00b2 #x25a0 #x00a0) :test #'equalp) (define-unibyte-decoder :cp437 (octet) (svref +cp437-to-unicode+ octet)) (define-unibyte-encoder :cp437 (code) (if (<= code 127) code ;; Adjacent code point groups are too small and too many to be ;; worth tabulating this, so we just use a case. (case code (#x7F #x7F) (#xA0 #x80) (#xA1 #x81) (#xA2 #x82) (#xA3 #x83) (#xA5 #x84) (#xAA #x85) (#xAB #x86) (#xAC #x87) (#xB0 #x88) (#xB1 #x89) (#xB2 #x8A) (#xB5 #x8B) (#xB7 #x8C) (#xBA #x8D) (#xBB #x8E) (#xBC #x8F) (#xBD #x90) (#xBF #x91) (#xC4 #x92) (#xC5 #x93) (#xC6 #x94) (#xC7 #x95) (#xC9 #x96) (#xD1 #x97) (#xD6 #x98) (#xDC #x99) (#xDF #x9A) (#xE0 #x9B) (#xE1 #x9C) (#xE2 #x9D) (#xE4 #x9E) (#xE5 #x9F) (#xE6 #xA0) (#xE7 #xA1) (#xE8 #xA2) (#xE9 #xA3) (#xEA #xA4) (#xEB #xA5) (#xEC #xA6) (#xED #xA7) (#xEE #xA8) (#xEF #xA9) (#xF1 #xAA) (#xF2 #xAB) (#xF3 #xAC) (#xF4 #xAD) (#xF6 #xAE) (#xF7 #xAF) (#xF9 #xB0) (#xFA #xB1) (#xFB #xB2) (#xFC #xB3) (#xFF #xB4) (#x192 #xB5) (#x393 #xB6) (#x398 #xB7) (#x3A3 #xB8) (#x3A6 #xB9) (#x3A9 #xBA) (#x3B1 #xBB) (#x3B4 #xBC) (#x3B5 #xBD) (#x3C0 #xBE) (#x3C3 #xBF) (#x3C4 #xC0) (#x3C6 #xC1) (#x207F #xC2) (#x20A7 #xC3) (#x2219 #xC4) (#x221A #xC5) (#x221E #xC6) (#x2229 #xC7) (#x2248 #xC8) (#x2261 #xC9) (#x2264 #xCA) (#x2265 #xCB) (#x2310 #xCC) (#x2320 #xCD) (#x2321 #xCE) (#x2500 #xCF) (#x2502 #xD0) (#x250C #xD1) (#x2510 #xD2) (#x2514 #xD3) (#x2518 #xD4) (#x251C #xD5) (#x2524 #xD6) (#x252C #xD7) (#x2534 #xD8) (#x253C #xD9) (#x2550 #xDA) (#x2551 #xDB) (#x2552 #xDC) (#x2553 #xDD) (#x2554 #xDE) (#x2555 #xDF) (#x2556 #xE0) (#x2557 #xE1) (#x2558 #xE2) (#x2559 #xE3) (#x255A #xE4) (#x255B #xE5) (#x255C #xE6) (#x255D #xE7) (#x255E #xE8) (#x255F #xE9) (#x2560 #xEA) (#x2561 #xEB) (#x2562 #xEC) (#x2563 #xED) (#x2564 #xEE) (#x2565 #xEF) (#x2566 #xF0) (#x2567 #xF1) (#x2568 #xF2) (#x2569 #xF3) (#x256A #xF4) (#x256B #xF5) (#x256C #xF6) (#x2580 #xF7) (#x2584 #xF8) (#x2588 #xF9) (#x258C #xFA) (#x2590 #xFB) (#x2591 #xFC) (#x2592 #xFD) (#x2593 #xFE) (#x25A0 #xFF) (t (handle-error)))))
6,563
Common Lisp
.lisp
202
25.188119
70
0.552549
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
8ee205b3b00cd225923ed17634e06e001d5da0165ed262058d65d1c19de6bc60
42,533
[ 428343 ]
42,537
streams.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/babel-20200925-git/src/streams.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; streams.lisp --- Conversions between strings and UB8 vectors. ;;; ;;; Copyright (c) 2005-2007, Dr. Edmund Weitz. All rights reserved. ;;; Copyright (c) 2008, Attila Lendvai. All rights reserved. ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;; STATUS ;;; ;;; - in-memory output streams support binary/bivalent/character ;;; element-types and file-position ;;; TODO ;;; ;;; - filter-stream types/mixins that can wrap a binary stream and ;;; turn it into a bivalent/character stream ;;; - in-memory input streams with file-position similar to in-memory ;;; output streams ;;; - in-memory input/output streams? (in-package #:babel) (defpackage #:babel-streams (:use #:common-lisp #:babel #:trivial-gray-streams #:alexandria) (:export #:in-memory-stream #:vector-output-stream #:vector-input-stream #:make-in-memory-output-stream #:make-in-memory-input-stream #:get-output-stream-sequence #:with-output-to-sequence #:with-input-from-sequence)) (in-package :babel-streams) (declaim (inline check-if-open check-if-accepts-octets check-if-accepts-characters stream-accepts-characters? stream-accepts-octets? vector-extend extend-vector-output-stream-buffer)) (defgeneric get-output-stream-sequence (stream &key &allow-other-keys)) ;;;; Some utilities (on top due to inlining) (defun vector-extend (extension vector &key (start 0) (end (length extension))) ;; copied over from cl-quasi-quote (declare (optimize speed) (type vector extension vector) (type array-index start end)) (let* ((original-length (length vector)) (extension-length (- end start)) (new-length (+ original-length extension-length)) (original-dimension (array-dimension vector 0))) (when (< original-dimension new-length) (setf vector (adjust-array vector (max (* 2 original-dimension) new-length)))) (setf (fill-pointer vector) new-length) (replace vector extension :start1 original-length :start2 start :end2 end) vector)) (defclass in-memory-stream (trivial-gray-stream-mixin) ((element-type ; :default means bivalent :initform :default :initarg :element-type :accessor element-type-of) (%external-format :initform (ensure-external-format *default-character-encoding*) :initarg :%external-format :accessor external-format-of) #+cmu (open-p :initform t :accessor in-memory-stream-open-p :documentation "For CMUCL we have to keep track of this manually.")) (:documentation "An IN-MEMORY-STREAM is a binary stream that reads octets from or writes octets to a sequence in RAM.")) (defmethod stream-element-type ((self in-memory-stream)) ;; stream-element-type is a CL symbol, we may not install an accessor on it. ;; so, go through this extra step. (element-type-of self)) (defun stream-accepts-octets? (stream) (let ((element-type (element-type-of stream))) (or (eq element-type :default) (equal element-type '(unsigned-byte 8)) (subtypep element-type '(unsigned-byte 8))))) (defun stream-accepts-characters? (stream) (let ((element-type (element-type-of stream))) (member element-type '(:default character base-char)))) (defclass in-memory-input-stream (in-memory-stream fundamental-binary-input-stream) () (:documentation "An IN-MEMORY-INPUT-STREAM is a binary stream that reads octets from a sequence in RAM.")) #+cmu (defmethod output-stream-p ((stream in-memory-input-stream)) "Explicitly states whether this is an output stream." (declare (optimize speed)) nil) (defclass in-memory-output-stream (in-memory-stream fundamental-binary-output-stream) () (:documentation "An IN-MEMORY-OUTPUT-STREAM is a binary stream that writes octets to a sequence in RAM.")) #+cmu (defmethod input-stream-p ((stream in-memory-output-stream)) "Explicitly states whether this is an input stream." (declare (optimize speed)) nil) (defun make-in-memory-output-stream (&key (element-type :default) external-format initial-buffer-size) "Returns a binary output stream which accepts objects of type ELEMENT-TYPE \(a subtype of OCTET) and makes available a sequence that contains the octes that were actually output." (declare (optimize speed)) (unless external-format (setf external-format *default-character-encoding*)) (when (eq element-type :bivalent) (setf element-type :default)) (make-instance 'vector-output-stream :vector (make-vector-stream-buffer :element-type (cond ((or (eq element-type :default) (equal element-type '(unsigned-byte 8))) '(unsigned-byte 8)) ((eq element-type 'character) 'character) ((subtypep element-type '(unsigned-byte 8)) '(unsigned-byte 8)) (t (error "Illegal element-type ~S" element-type))) :initial-size initial-buffer-size) :element-type element-type :%external-format (ensure-external-format external-format))) (defun make-in-memory-input-stream (data &key (element-type :default) external-format) "Returns a binary input stream which provides the elements of DATA when read." (declare (optimize speed)) (unless external-format (setf external-format *default-character-encoding*)) (when (eq element-type :bivalent) (setf element-type :default)) (make-instance 'vector-input-stream :vector data :element-type element-type :end (length data) :%external-format (ensure-external-format external-format))) (defclass vector-stream () ((vector :initarg :vector :accessor vector-stream-vector :documentation "The underlying vector of the stream which \(for output) must always be adjustable and have a fill pointer.") (index :initform 0 :initarg :index :accessor vector-stream-index :type (integer 0 #.array-dimension-limit) :documentation "An index into the underlying vector denoting the current position.")) (:documentation "A VECTOR-STREAM is a mixin for IN-MEMORY streams where the underlying sequence is a vector.")) (defclass vector-input-stream (vector-stream in-memory-input-stream) ((end :initarg :end :accessor vector-stream-end :type (integer 0 #.array-dimension-limit) :documentation "An index into the underlying vector denoting the end of the available data.")) (:documentation "A binary input stream that gets its data from an associated vector of octets.")) (defclass vector-output-stream (vector-stream in-memory-output-stream) () (:documentation "A binary output stream that writes its data to an associated vector.")) (define-condition in-memory-stream-error (stream-error) () (:documentation "Superclass for all errors related to IN-MEMORY streams.")) (define-condition in-memory-stream-closed-error (in-memory-stream-error) () (:report (lambda (condition stream) (format stream "~S is closed." (stream-error-stream condition)))) (:documentation "An error that is signalled when someone is trying to read from or write to a closed IN-MEMORY stream.")) (define-condition wrong-element-type-stream-error (stream-error) ((expected-type :accessor expected-type-of :initarg :expected-type)) (:report (lambda (condition output) (let ((stream (stream-error-stream condition))) (format output "The element-type of ~S is ~S while expecting ~ a stream that accepts ~S." stream (element-type-of stream) (expected-type-of condition)))))) (defun wrong-element-type-stream-error (stream expected-type) (error 'wrong-element-type-stream-error :stream stream :expected-type expected-type)) #+cmu (defmethod open-stream-p ((stream in-memory-stream)) "Returns a true value if STREAM is open. See ANSI standard." (declare (optimize speed)) (in-memory-stream-open-p stream)) #+cmu (defmethod close ((stream in-memory-stream) &key abort) "Closes the stream STREAM. See ANSI standard." (declare (ignore abort) (optimize speed)) (prog1 (in-memory-stream-open-p stream) (setf (in-memory-stream-open-p stream) nil))) (defun check-if-open (stream) "Checks if STREAM is open and signals an error otherwise." (declare (optimize speed)) (unless (open-stream-p stream) (error 'in-memory-stream-closed-error :stream stream))) (defun check-if-accepts-octets (stream) (declare (optimize speed)) (unless (stream-accepts-octets? stream) (wrong-element-type-stream-error stream '(unsigned-byte 8)))) (defun check-if-accepts-characters (stream) (declare (optimize speed)) (unless (stream-accepts-characters? stream) (wrong-element-type-stream-error stream 'character))) (defmethod stream-read-byte ((stream vector-input-stream)) "Reads one byte and increments INDEX pointer unless we're beyond END pointer." (declare (optimize speed)) (check-if-open stream) (let ((index (vector-stream-index stream))) (cond ((< index (vector-stream-end stream)) (incf (vector-stream-index stream)) (aref (vector-stream-vector stream) index)) (t :eof)))) #+#:ignore (defmethod stream-read-char ((stream vector-input-stream)) ;; TODO ) (defmethod stream-listen ((stream vector-input-stream)) "Checking whether INDEX is beyond END." (declare (optimize speed)) (check-if-open stream) (< (vector-stream-index stream) (vector-stream-end stream))) (defmethod stream-read-sequence ((stream vector-input-stream) sequence start end &key) (declare (optimize speed) (type array-index start end)) ;; TODO check the sequence type, assert for the element-type and use ;; the external-format. (loop with vector-end of-type array-index = (vector-stream-end stream) with vector = (vector-stream-vector stream) for index from start below end for vector-index of-type array-index = (vector-stream-index stream) while (< vector-index vector-end) do (setf (elt sequence index) (aref vector vector-index)) (incf (vector-stream-index stream)) finally (return index))) (defmethod stream-write-byte ((stream vector-output-stream) byte) "Writes a byte \(octet) by extending the underlying vector." (declare (optimize speed)) (check-if-open stream) (check-if-accepts-octets stream) (vector-push-extend byte (vector-stream-vector stream)) (incf (vector-stream-index stream)) byte) (defun extend-vector-output-stream-buffer (extension stream &key (start 0) (end (length extension))) (declare (optimize speed) (type array-index start end) (type vector extension)) (vector-extend extension (vector-stream-vector stream) :start start :end end) (incf (vector-stream-index stream) (- end start)) (values)) (defmethod stream-write-char ((stream vector-output-stream) char) (declare (optimize speed)) (check-if-open stream) (if (eq (element-type-of stream) 'character) (vector-push-extend char (vector-stream-vector stream)) (let ((octets (string-to-octets (string char) :encoding (external-format-of stream)))) (extend-vector-output-stream-buffer octets stream))) char) (defmethod stream-write-sequence ((stream vector-output-stream) sequence start end &key) "Just calls VECTOR-PUSH-EXTEND repeatedly." (declare (optimize speed) (type array-index start end)) (etypecase sequence (string (if (stream-accepts-octets? stream) ;; TODO this is naiive here, there's room for optimization (let ((octets (string-to-octets sequence :encoding (external-format-of stream) :start start :end end))) (extend-vector-output-stream-buffer octets stream)) (progn (assert (stream-accepts-characters? stream)) (extend-vector-output-stream-buffer sequence stream :start start :end end)))) ((vector (unsigned-byte 8)) ;; specialized branch to help inlining (check-if-accepts-octets stream) (extend-vector-output-stream-buffer sequence stream :start start :end end)) (vector (check-if-accepts-octets stream) (extend-vector-output-stream-buffer sequence stream :start start :end end))) sequence) (defmethod stream-write-string ((stream vector-output-stream) string &optional (start 0) (end (length string))) (stream-write-sequence stream string start (or end (length string)))) (defmethod stream-line-column ((stream vector-output-stream)) "Dummy line-column method that always returns NIL. Needed for character output streams." nil) (defmethod stream-file-position ((stream vector-stream)) "Simply returns the index into the underlying vector." (declare (optimize speed)) (vector-stream-index stream)) (defun make-vector-stream-buffer (&key (element-type '(unsigned-byte 8)) initial-size) "Creates and returns an array which can be used as the underlying vector for a VECTOR-OUTPUT-STREAM." (declare (optimize speed) (type (or null array-index) initial-size)) (make-array (the array-index (or initial-size 32)) :adjustable t :fill-pointer 0 :element-type element-type)) (defmethod get-output-stream-sequence ((stream in-memory-output-stream) &key (return-as 'vector)) "Returns a vector containing, in order, all the octets that have been output to the IN-MEMORY stream STREAM. This operation clears any octets on STREAM, so the vector contains only those octets which have been output since the last call to GET-OUTPUT-STREAM-SEQUENCE or since the creation of the stream, whichever occurred most recently. If AS-LIST is true the return value is coerced to a list." (declare (optimize speed)) (let ((vector (vector-stream-vector stream))) (prog1 (ecase return-as (vector vector) (string (octets-to-string vector :encoding (external-format-of stream))) (list (coerce vector 'list))) (setf (vector-stream-vector stream) (make-vector-stream-buffer :element-type (element-type-of stream)))))) (defmacro with-output-to-sequence ((var &key (return-as ''vector) (element-type '':default) (external-format '*default-character-encoding*) initial-buffer-size) &body body) "Creates an IN-MEMORY output stream, binds VAR to this stream and then executes the code in BODY. The stream stores data of type ELEMENT-TYPE \(a subtype of OCTET). The stream is automatically closed on exit from WITH-OUTPUT-TO-SEQUENCE, no matter whether the exit is normal or abnormal. The return value of this macro is a vector \(or a list if AS-LIST is true) containing the octets that were sent to the stream within BODY." (multiple-value-bind (body declarations) (parse-body body) ;; this is here to stop SBCL complaining about binding them to NIL `(let ((,var (make-in-memory-output-stream :element-type ,element-type :external-format ,external-format :initial-buffer-size ,initial-buffer-size))) ,@declarations (unwind-protect (progn ,@body (get-output-stream-sequence ,var :return-as ,return-as)) (close ,var))))) (defmacro with-input-from-sequence ((var data &key (element-type '':default) (external-format '*default-character-encoding*)) &body body) "Creates an IN-MEMORY input stream that will return the values available in DATA, binds VAR to this stream and then executes the code in BODY. The stream stores data of type ELEMENT-TYPE \(a subtype of OCTET). The stream is automatically closed on exit from WITH-INPUT-FROM-SEQUENCE, no matter whether the exit is normal or abnormal. The return value of this macro is the return value of BODY." (multiple-value-bind (body declarations) (parse-body body) ;; this is here to stop SBCL complaining about binding them to NIL `(let ((,var (make-in-memory-input-stream ,data :element-type ,element-type :external-format ,external-format))) ,@declarations (unwind-protect (progn ,@body) (close ,var)))))
18,470
Common Lisp
.lisp
391
40.01023
97
0.674097
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
c1aae9eb9fbbdaa998c8963cdbe457e719459591be2fc45c34f3e4ad370d19b0
42,537
[ 454181 ]
42,541
tests.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/babel-20200925-git/tests/tests.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; tests.lisp --- Unit and regression tests for Babel. ;;; ;;; Copyright (C) 2007-2009, Luis Oliveira <[email protected]> ;;; ;;; Permission is hereby granted, free of charge, to any person ;;; obtaining a copy of this software and associated documentation ;;; files (the "Software"), to deal in the Software without ;;; restriction, including without limitation the rights to use, copy, ;;; modify, merge, publish, distribute, sublicense, and/or sell copies ;;; of the Software, and to permit persons to whom the Software is ;;; furnished to do so, subject to the following conditions: ;;; ;;; The above copyright notice and this permission notice shall be ;;; included in all copies or substantial portions of the Software. ;;; ;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, ;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;;; DEALINGS IN THE SOFTWARE. (in-package #:cl-user) (defpackage #:babel-tests (:use #:common-lisp #:babel #:babel-encodings #:hu.dwim.stefil) (:import-from #:alexandria #:ignore-some-conditions) (:export #:run)) (in-package #:babel-tests) (defun indented-format (level stream format-control &rest format-arguments) (let ((line-prefix (make-string level :initial-element #\Space))) (let ((output (format nil "~?~%" format-control format-arguments))) (with-input-from-string (s output) (loop for line = (read-line s nil nil) until (null line) do (format stream "~A~A~%" line-prefix line)))))) ;; adapted from https://github.com/luismbo/stefil/blob/master/source/suite.lisp (defun describe-failed-tests (&key (result *last-test-result*) (stream t)) "Prints out a report for RESULT in STREAM. RESULT defaults to `*last-test-result*' and STREAM defaults to t" (let ((descs (hu.dwim.stefil::failure-descriptions-of result))) (cond ((zerop (length descs)) (format stream "~&~%[no failures!]")) (t (format stream "~&~%Test failures:~%") (dotimes (i (length descs)) (let ((desc (aref descs i)) format-control format-arguments) ;; XXX: most of Stefil's conditions specialise DESCRIBE-OBJECT ;; with nice human-readable messages. We should add any missing ;; ones (like UNEXPECTED-ERROR) and ditch this code. (etypecase desc (hu.dwim.stefil::unexpected-error (let ((c (hu.dwim.stefil::condition-of desc))) (typecase c (simple-condition (setf format-control (simple-condition-format-control c)) (setf format-arguments (simple-condition-format-arguments c))) (t (setf format-control "~S" format-arguments (list c)))))) (hu.dwim.stefil::failed-assertion (setf format-control (hu.dwim.stefil::format-control-of desc) format-arguments (hu.dwim.stefil::format-arguments-of desc))) (hu.dwim.stefil::missing-condition (setf format-control "~A" format-arguments (list (with-output-to-string (stream) (describe desc stream))))) (null (setf format-control "Test succeeded!"))) (format stream "~%Failure ~A: ~A when running ~S~%~%" (1+ i) (type-of desc) (hu.dwim.stefil::name-of (hu.dwim.stefil::test-of (first (hu.dwim.stefil::test-context-backtrace-of desc))))) (indented-format 4 stream "~?" format-control format-arguments))))))) (defun run () (let ((test-run (without-debugging (babel-tests)))) (print test-run) (describe-failed-tests :result test-run) (values (zerop (length (hu.dwim.stefil::failure-descriptions-of test-run))) test-run))) (defsuite* (babel-tests :in root-suite)) (defun ub8v (&rest contents) (make-array (length contents) :element-type '(unsigned-byte 8) :initial-contents contents)) (defun make-ub8-vector (size) (make-array size :element-type '(unsigned-byte 8) :initial-element 0)) (defmacro returns (form &rest values) "Asserts, through EQUALP, that FORM returns VALUES." `(is (equalp (multiple-value-list ,form) (list ,@values)))) (defmacro defstest (name form &body return-values) "Similar to RT's DEFTEST." `(deftest ,name () (returns ,form ,@(mapcar (lambda (x) `',x) return-values)))) (defun fail (control-string &rest arguments) (hu.dwim.stefil::record/failure 'hu.dwim.stefil::failed-assertion :format-control control-string :format-arguments arguments)) (defun expected (expected &key got) (fail "expected ~A, got ~A instead" expected got)) (enable-sharp-backslash-syntax) ;;;; Simple tests using ASCII (defstest enc.ascii.1 (string-to-octets "abc" :encoding :ascii) #(97 98 99)) (defstest enc.ascii.2 (string-to-octets (string #\uED) :encoding :ascii :errorp nil) #(#x1a)) (deftest enc.ascii.3 () (handler-case (string-to-octets (string #\uED) :encoding :ascii :errorp t) (character-encoding-error (c) (is (eql 0 (character-coding-error-position c))) (is (eq :ascii (character-coding-error-encoding c))) (is (eql #xed (character-encoding-error-code c)))) (:no-error (result) (expected 'character-encoding-error :got result)))) (defstest dec.ascii.1 (octets-to-string (ub8v 97 98 99) :encoding :ascii) "abc") (deftest dec.ascii.2 () (handler-case (octets-to-string (ub8v 97 128 99) :encoding :ascii :errorp t) (character-decoding-error (c) (is (equalp #(128) (character-decoding-error-octets c))) (is (eql 1 (character-coding-error-position c))) (is (eq :ascii (character-coding-error-encoding c)))) (:no-error (result) (expected 'character-decoding-error :got result)))) (defstest dec.ascii.3 (octets-to-string (ub8v 97 255 98 99) :encoding :ascii :errorp nil) #(#\a #\Sub #\b #\c)) (defstest oct-count.ascii.1 (string-size-in-octets "abc" :encoding :ascii) 3 3) (defstest char-count.ascii.1 (vector-size-in-chars (ub8v 97 98 99) :encoding :ascii) 3 3) ;;;; UTF-8 (defstest char-count.utf-8.1 ;; "ni hao" in hanzi with the last octet missing (vector-size-in-chars (ub8v 228 189 160 229 165) :errorp nil) 2 5) (deftest char-count.utf-8.2 () ;; same as above with the last 2 octets missing (handler-case (vector-size-in-chars (ub8v 228 189 160 229) :errorp t) (end-of-input-in-character (c) (is (equalp #(229) (character-decoding-error-octets c))) (is (eql 3 (character-coding-error-position c))) (is (eq :utf-8 (character-coding-error-encoding c)))) (:no-error (result) (expected 'end-of-input-in-character :got result)))) ;;; Lispworks bug? ;; #+lispworks ;; (pushnew 'dec.utf-8.1 rtest::*expected-failures*) (defstest dec.utf-8.1 (octets-to-string (ub8v 228 189 160 229) :errorp nil) #(#\u4f60 #\ufffd)) (deftest dec.utf-8.2 () (handler-case (octets-to-string (ub8v 228 189 160 229) :errorp t) (end-of-input-in-character (c) (is (equalp #(229) (character-decoding-error-octets c))) (is (eql 3 (character-coding-error-position c))) (is (eq :utf-8 (character-coding-error-encoding c)))) (:no-error (result) (expected 'end-of-input-in-character :got result)))) ;;;; UTF-16 ;;; Test that the BOM is not being counted as a character. (deftest char-count.utf-16.bom () (is (eql (vector-size-in-chars (ub8v #xfe #xff #x00 #x55 #x00 #x54 #x00 #x46) :encoding :utf-16) 3)) (is (eql (vector-size-in-chars (ub8v #xff #xfe #x00 #x55 #x00 #x54 #x00 #x46) :encoding :utf-16) 3))) ;;;; UTF-32 ;;; RT: check that UTF-32 characters without a BOM are treated as ;;; little-endian. (deftest endianness.utf-32.no-bom () (is (string= "a" (octets-to-string (ub8v 0 0 0 97) :encoding :utf-32)))) ;;;; MORE TESTS (defparameter *standard-characters* "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!$\"'(),_-./:;?+<=>#%&*@[\\]{|}`^~") ;;; Testing consistency by encoding and decoding a simple string for ;;; all character encodings. (deftest rw-equiv.1 () (let ((compatible-encodings (remove :ebcdic-international (list-character-encodings)))) (dolist (*default-character-encoding* compatible-encodings) (let ((octets (string-to-octets *standard-characters*))) (is (string= (octets-to-string octets) *standard-characters*)))))) ;;; FIXME: assumes little-endianness. Easily fixable when we ;;; implement the BE and LE variants of :UTF-16. (deftest concatenate-strings-to-octets-equiv.1 () (let ((foo (octets-to-string (ub8v 102 195 186 195 186) :encoding :utf-8)) (bar (octets-to-string (ub8v 98 195 161 114) :encoding :utf-8))) ;; note: FOO and BAR are not ascii (is (equalp (concatenate-strings-to-octets :utf-8 foo bar) (ub8v 102 195 186 195 186 98 195 161 114))) (is (equalp (concatenate-strings-to-octets :utf-16 foo bar) (ub8v 102 0 250 0 250 0 98 0 225 0 114 0))))) ;;;; Testing against files generated by GNU iconv. (defun test-file (name type) (uiop:subpathname (asdf:system-relative-pathname "babel-tests" "tests/") name :type type)) (defun read-test-file (name type) (with-open-file (in (test-file name type) :element-type '(unsigned-byte 8)) (let* ((data (loop for byte = (read-byte in nil nil) until (null byte) collect byte))) (make-array (length data) :element-type '(unsigned-byte 8) :initial-contents data)))) (deftest test-encoding (enc &optional input-enc-name) (let* ((*default-character-encoding* enc) (enc-name (string-downcase (symbol-name enc))) (utf8-octets (read-test-file enc-name "txt-utf8")) (foo-octets (read-test-file (or input-enc-name enc-name) "txt")) (utf8-string (octets-to-string utf8-octets :encoding :utf-8 :errorp t)) (foo-string (octets-to-string foo-octets :errorp t))) (is (string= utf8-string foo-string)) (is (= (length foo-string) (vector-size-in-chars foo-octets :errorp t))) (unless (member enc '(:utf-16 :utf-32)) ;; FIXME: skipping UTF-16 and UTF-32 because of the BOMs and ;; because the input might not be in native-endian order so the ;; comparison will fail there. (let ((new-octets (string-to-octets foo-string :errorp t))) (is (equalp new-octets foo-octets)) (is (eql (length foo-octets) (string-size-in-octets foo-string :errorp t))))))) (deftest iconv-test () (dolist (enc '(:ascii :ebcdic-us :utf-8 :utf-16 :utf-32)) (case enc (:utf-16 (test-encoding :utf-16 "utf-16-with-le-bom")) (:utf-32 (test-encoding :utf-32 "utf-32-with-le-bom"))) (test-encoding enc))) ;;; RT: accept encoding objects in LOOKUP-MAPPING etc. (defstest encoding-objects.1 (string-to-octets "abc" :encoding (get-character-encoding :ascii)) #(97 98 99)) (defmacro with-sharp-backslash-syntax (&body body) `(let ((*readtable* (copy-readtable *readtable*))) (set-sharp-backslash-syntax-in-readtable) ,@body)) (defstest sharp-backslash.1 (with-sharp-backslash-syntax (loop for string in '("#\\a" "#\\u" "#\\ued") collect (char-code (read-from-string string)))) (97 117 #xed)) (deftest sharp-backslash.2 () (signals reader-error (with-sharp-backslash-syntax (read-from-string "#\\u12zz")))) (deftest test-read-from-string (string object position) "Test that (read-from-string STRING) returns values OBJECT and POSITION." (multiple-value-bind (obj pos) (read-from-string string) (is (eql object obj)) (is (eql position pos)))) ;;; RT: our #\ reader didn't honor *READ-SUPPRESS*. (deftest sharp-backslash.3 () (with-sharp-backslash-syntax (let ((*read-suppress* t)) (test-read-from-string "#\\ujunk" nil 7) (test-read-from-string "#\\u12zz" nil 7)))) ;;; RT: the slow implementation of with-simple-vector was buggy. (defstest string-to-octets.1 (code-char (aref (string-to-octets "abc" :start 1 :end 2) 0)) #\b) (defstest simple-base-string.1 (string-to-octets (coerce "abc" 'base-string) :encoding :ascii) #(97 98 99)) ;;; For now, disable this tests for Lisps that are strict about ;;; non-character code points. In the future, simply mark them as ;;; expected failures. #-(or abcl ccl) (progn (defstest utf-8b.1 (string-to-octets (coerce #(#\a #\b #\udcf0) 'unicode-string) :encoding :utf-8b) #(97 98 #xf0)) #+#:temporarily-disabled (defstest utf-8b.2 (octets-to-string (ub8v 97 98 #xcd) :encoding :utf-8b) #(#\a #\b #\udccd)) (defstest utf-8b.3 (octets-to-string (ub8v 97 #xf0 #xf1 #xff #x01) :encoding :utf-8b) #(#\a #\udcf0 #\udcf1 #\udcff #\udc01)) (deftest utf-8b.4 () (let* ((octets (coerce (loop repeat 8192 collect (random (+ #x82))) '(array (unsigned-byte 8) (*)))) (string (octets-to-string octets :encoding :utf-8b))) (is (equalp octets (string-to-octets string :encoding :utf-8b)))))) ;;; The following tests have been adapted from SBCL's ;;; tests/octets.pure.lisp file. (deftest ensure-roundtrip-ascii () (let ((octets (make-ub8-vector 128))) (dotimes (i 128) (setf (aref octets i) i)) (let* ((str (octets-to-string octets :encoding :ascii)) (oct2 (string-to-octets str :encoding :ascii))) (is (= (length octets) (length oct2))) (is (every #'= octets oct2))))) (deftest test-8bit-roundtrip (enc) (let ((octets (make-ub8-vector 256))) (dotimes (i 256) (setf (aref octets i) i)) (let* ((str (octets-to-string octets :encoding enc))) ;; remove the undefined code-points because they translate ;; to #xFFFD and string-to-octets raises an error when ;; encoding #xFFFD (multiple-value-bind (filtered-str filtered-octets) (let ((s (make-array 0 :element-type 'character :adjustable t :fill-pointer 0)) (o (make-array 0 :element-type '(unsigned-byte 16) :adjustable t :fill-pointer 0))) (loop for i below 256 for c = (aref str i) when (/= (char-code c) #xFFFD) do (vector-push-extend c s) (vector-push-extend (aref octets i) o)) (values s o)) (let ((oct2 (string-to-octets filtered-str :encoding enc))) (is (eql (length filtered-octets) (length oct2))) (is (every #'eql filtered-octets oct2))))))) (defparameter *iso-8859-charsets* '(:iso-8859-1 :iso-8859-2 :iso-8859-3 :iso-8859-4 :iso-8859-5 :iso-8859-6 :iso-8859-7 :iso-8859-8 :iso-8859-9 :iso-8859-10 :iso-8859-11 :iso-8859-13 :iso-8859-14 :iso-8859-15 :iso-8859-16)) ;;; Don't actually see what comes out, but there shouldn't be any ;;; errors. (deftest iso-8859-roundtrip-no-checking () (loop for enc in *iso-8859-charsets* do (test-8bit-roundtrip enc))) (deftest ensure-roundtrip-latin () (loop for enc in '(:latin1 :latin9) do (test-8bit-roundtrip enc))) ;;; Latin-9 chars; the previous test checked roundtrip from ;;; octets->char and back, now test that the latin-9 characters did in ;;; fact appear during that trip. (deftest ensure-roundtrip-latin9 () (let ((l9c (map 'string #'code-char '(8364 352 353 381 382 338 339 376)))) (is (string= (octets-to-string (string-to-octets l9c :encoding :latin9) :encoding :latin9) l9c)))) ;; Expected to fail on Lisps that are strict about non-character code ;; points. Mark this as an expected failure when Stefil supports such ;; a feature. #-(or abcl ccl) (deftest code-char-nilness () (is (loop for i below unicode-char-code-limit never (null (code-char i))))) (deftest test-unicode-roundtrip (enc) (let ((string (make-string unicode-char-code-limit))) (dotimes (i unicode-char-code-limit) (setf (char string i) (if (or (<= #xD800 i #xDFFF) (<= #xFDD0 i #xFDEF) (eql (logand i #xFFFF) #xFFFF) (eql (logand i #xFFFF) #xFFFE)) #\? ; don't try to encode non-characters. (code-char i)))) (let ((string2 (octets-to-string (string-to-octets string :encoding enc :errorp t) :encoding enc :errorp t))) (is (eql (length string2) (length string))) (is (string= string string2))))) (deftest ensure-roundtrip.utf8 () (test-unicode-roundtrip :utf-8)) (deftest ensure-roundtrip.utf16 () (test-unicode-roundtrip :utf-16)) (deftest ensure-roundtrip.utf32 () (test-unicode-roundtrip :utf-32)) #+sbcl (progn (deftest test-encode-against-sbcl (enc) (let ((string (make-string unicode-char-code-limit))) (dotimes (i unicode-char-code-limit) (setf (char string i) (code-char i))) (loop for ch across string for babel = (string-to-octets (string ch) :encoding enc) for sbcl = (sb-ext:string-to-octets (string ch) :external-format enc) do (is (equalp babel sbcl))))) ;; not run automatically because it's a bit slow (1114112 assertions) (deftest (test-encode-against-sbcl.utf-8 :auto-call nil) () (test-encode-against-sbcl :utf-8))) (deftest non-ascii-bytes () (let ((octets (make-array 128 :element-type '(unsigned-byte 8) :initial-contents (loop for i from 128 below 256 collect i)))) (is (string= (octets-to-string octets :encoding :ascii :errorp nil) (make-string 128 :initial-element #\Sub))))) (deftest non-ascii-chars () (let ((string (make-array 128 :element-type 'character :initial-contents (loop for i from 128 below 256 collect (code-char i))))) (is (equalp (string-to-octets string :encoding :ascii :errorp nil) (make-array 128 :initial-element (char-code #\Sub)))))) ;;;; The following UTF-8 decoding tests are adapted from ;;;; <http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt>. (deftest utf8-decode-test (octets expected-results expected-errors) (let ((string (octets-to-string (coerce octets '(vector (unsigned-byte 8) *)) :encoding :utf-8 :errorp nil))) (is (string= expected-results string)) (is (= (count #\ufffd string) expected-errors)))) (deftest utf8-decode-tests (octets expected-results) (setf expected-results (coerce expected-results '(simple-array character (*)))) (let ((expected-errors (count #\? expected-results)) (expected-results (substitute #\ufffd #\? expected-results))) (utf8-decode-test octets expected-results expected-errors) (utf8-decode-test (concatenate 'vector '(34) octets '(34)) (format nil "\"~A\"" expected-results) expected-errors))) (deftest utf8-too-big-characters () (utf8-decode-tests #(#xf4 #x90 #x80 #x80) "?") ; #x110000 (utf8-decode-tests #(#xf7 #xbf #xbf #xbf) "?") ; #x1fffff (utf8-decode-tests #(#xf8 #x88 #x80 #x80 #x80) "?") ; #x200000 (utf8-decode-tests #(#xfb #xbf #xbf #xbf #xbf) "?") ; #x3ffffff (utf8-decode-tests #(#xfc #x84 #x80 #x80 #x80 #x80) "?") ; #x4000000e (utf8-decode-tests #(#xfd #xbf #xbf #xbf #xbf #xbf) "?")) ; #x7fffffff (deftest utf8-unexpected-continuation-bytes () (utf8-decode-tests #(#x80) "?") (utf8-decode-tests #(#xbf) "?") (utf8-decode-tests #(#x80 #xbf) "??") (utf8-decode-tests #(#x80 #xbf #x80) "???") (utf8-decode-tests #(#x80 #xbf #x80 #xbf) "????") (utf8-decode-tests #(#x80 #xbf #x80 #xbf #x80) "?????") (utf8-decode-tests #(#x80 #xbf #x80 #xbf #x80 #xbf) "??????") (utf8-decode-tests #(#x80 #xbf #x80 #xbf #x80 #xbf #x80) "???????")) ;;; All 64 continuation bytes in a row. (deftest utf8-continuation-bytes () (apply #'utf8-decode-tests (loop for i from #x80 to #xbf collect i into bytes collect #\? into chars finally (return (list bytes (coerce chars 'string)))))) (deftest utf8-lonely-start-characters () (flet ((lsc (first last) (apply #'utf8-decode-tests (loop for i from first to last nconc (list i 32) into bytes nconc (list #\? #\Space) into chars finally (return (list bytes (coerce chars 'string))))) (apply #'utf8-decode-tests (loop for i from first to last collect i into bytes collect #\? into chars finally (return (list bytes (coerce chars 'string))))))) (lsc #xc0 #xdf) ; 2-byte sequence start chars (lsc #xe0 #xef) ; 3-byte (lsc #xf0 #xf7) ; 4-byte (lsc #xf8 #xfb) ; 5-byte (lsc #xfc #xfd))) ; 6-byte ;;; Otherwise incomplete sequences (last continuation byte missing) (deftest utf8-incomplete-sequences () (utf8-decode-tests #0=#(#xc0) "?") (utf8-decode-tests #1=#(#xe0 #x80) "?") (utf8-decode-tests #2=#(#xf0 #x80 #x80) "?") (utf8-decode-tests #3=#(#xf8 #x80 #x80 #x80) "?") (utf8-decode-tests #4=#(#xfc #x80 #x80 #x80 #x80) "?") (utf8-decode-tests #5=#(#xdf) "?") (utf8-decode-tests #6=#(#xef #xbf) "?") (utf8-decode-tests #7=#(#xf7 #xbf #xbf) "?") (utf8-decode-tests #8=#(#xfb #xbf #xbf #xbf) "?") (utf8-decode-tests #9=#(#xfd #xbf #xbf #xbf #xbf) "?") ;; All ten previous tests concatenated (utf8-decode-tests (concatenate 'vector #0# #1# #2# #3# #4# #5# #6# #7# #8# #9#) "??????????")) (deftest utf8-random-impossible-bytes () (utf8-decode-tests #(#xfe) "?") (utf8-decode-tests #(#xff) "?") (utf8-decode-tests #(#xfe #xfe #xff #xff) "????")) (deftest utf8-overlong-sequences-/ () (utf8-decode-tests #(#xc0 #xaf) "?") (utf8-decode-tests #(#xe0 #x80 #xaf) "?") (utf8-decode-tests #(#xf0 #x80 #x80 #xaf) "?") (utf8-decode-tests #(#xf8 #x80 #x80 #x80 #xaf) "?") (utf8-decode-tests #(#xfc #x80 #x80 #x80 #x80 #xaf) "?")) (deftest utf8-overlong-sequences-rubout () (utf8-decode-tests #(#xc1 #xbf) "?") (utf8-decode-tests #(#xe0 #x9f #xbf) "?") (utf8-decode-tests #(#xf0 #x8f #xbf #xbf) "?") (utf8-decode-tests #(#xf8 #x87 #xbf #xbf #xbf) "?") (utf8-decode-tests #(#xfc #x83 #xbf #xbf #xbf #xbf) "?")) (deftest utf8-overlong-sequences-null () (utf8-decode-tests #(#xc0 #x80) "?") (utf8-decode-tests #(#xe0 #x80 #x80) "?") (utf8-decode-tests #(#xf0 #x80 #x80 #x80) "?") (utf8-decode-tests #(#xf8 #x80 #x80 #x80 #x80) "?") (utf8-decode-tests #(#xfc #x80 #x80 #x80 #x80 #x80) "?")) ;;;; End of adapted SBCL tests. ;;; Expected to fail, for now. #+#:ignore (deftest utf8-illegal-code-positions () ;; single UTF-16 surrogates (utf8-decode-tests #(#xed #xa0 #x80) "?") (utf8-decode-tests #(#xed #xad #xbf) "?") (utf8-decode-tests #(#xed #xae #x80) "?") (utf8-decode-tests #(#xed #xaf #xbf) "?") (utf8-decode-tests #(#xed #xb0 #x80) "?") (utf8-decode-tests #(#xed #xbe #x80) "?") (utf8-decode-tests #(#xed #xbf #xbf) "?") ;; paired UTF-16 surrogates (utf8-decode-tests #(ed a0 80 ed b0 80) "??") (utf8-decode-tests #(ed a0 80 ed bf bf) "??") (utf8-decode-tests #(ed ad bf ed b0 80) "??") (utf8-decode-tests #(ed ad bf ed bf bf) "??") (utf8-decode-tests #(ed ae 80 ed b0 80) "??") (utf8-decode-tests #(ed ae 80 ed bf bf) "??") (utf8-decode-tests #(ed af bf ed b0 80) "??") (utf8-decode-tests #(ed af bf ed bf bf) "??") ;; other illegal code positions (utf8-decode-tests #(#xef #xbf #xbe) "?") ; #\uFFFE (utf8-decode-tests #(#xef #xbf #xbf) "?")) ; #\uFFFF ;;; A list of the ISO-8859 encodings where each element is a cons with ;;; the car being a keyword denoting the encoding and the cdr being a ;;; vector enumerating the corresponding character codes. ;;; ;;; It was auto-generated from files which can be found at ;;; <ftp://ftp.unicode.org/Public/MAPPINGS/ISO8859/>. ;;; ;;; Taken from flexi-streams. (defparameter *iso-8859-tables* '((:iso-8859-1 . #(0 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 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255)) (:iso-8859-2 . #(0 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 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 260 728 321 164 317 346 167 168 352 350 356 377 173 381 379 176 261 731 322 180 318 347 711 184 353 351 357 378 733 382 380 340 193 194 258 196 313 262 199 268 201 280 203 282 205 206 270 272 323 327 211 212 336 214 215 344 366 218 368 220 221 354 223 341 225 226 259 228 314 263 231 269 233 281 235 283 237 238 271 273 324 328 243 244 337 246 247 345 367 250 369 252 253 355 729)) (:iso-8859-3 . #(0 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 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 294 728 163 164 65533 292 167 168 304 350 286 308 173 65533 379 176 295 178 179 180 181 293 183 184 305 351 287 309 189 65533 380 192 193 194 65533 196 266 264 199 200 201 202 203 204 205 206 207 65533 209 210 211 212 288 214 215 284 217 218 219 220 364 348 223 224 225 226 65533 228 267 265 231 232 233 234 235 236 237 238 239 65533 241 242 243 244 289 246 247 285 249 250 251 252 365 349 729)) (:iso-8859-4 . #(0 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 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 260 312 342 164 296 315 167 168 352 274 290 358 173 381 175 176 261 731 343 180 297 316 711 184 353 275 291 359 330 382 331 256 193 194 195 196 197 198 302 268 201 280 203 278 205 206 298 272 325 332 310 212 213 214 215 216 370 218 219 220 360 362 223 257 225 226 227 228 229 230 303 269 233 281 235 279 237 238 299 273 326 333 311 244 245 246 247 248 371 250 251 252 361 363 729)) (:iso-8859-5 . #(0 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 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 173 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 8470 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 167 1118 1119)) (:iso-8859-6 . #(0 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 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 65533 65533 65533 164 65533 65533 65533 65533 65533 65533 65533 1548 173 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 1563 65533 65533 65533 1567 65533 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 65533 65533 65533 65533 65533 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533)) (:iso-8859-7 . #(0 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 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 8216 8217 163 8364 8367 166 167 168 169 890 171 172 173 65533 8213 176 177 178 179 900 901 902 183 904 905 906 187 908 189 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 65533 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 65533)) (:iso-8859-8 . #(0 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 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 65533 162 163 164 165 166 167 168 169 215 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 247 187 188 189 190 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 65533 8215 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 65533 65533 8206 8207 65533)) (:iso-8859-9 . #(0 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 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 286 209 210 211 212 213 214 215 216 217 218 219 220 304 350 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 287 241 242 243 244 245 246 247 248 249 250 251 252 305 351 255)) (:iso-8859-10 . #(0 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 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 260 274 290 298 296 310 167 315 272 352 358 381 173 362 330 176 261 275 291 299 297 311 183 316 273 353 359 382 8213 363 331 256 193 194 195 196 197 198 302 268 201 280 203 278 205 206 207 208 325 332 211 212 213 214 360 216 370 218 219 220 221 222 223 257 225 226 227 228 229 230 303 269 233 281 235 279 237 238 239 240 326 333 243 244 245 246 361 248 371 250 251 252 253 254 312)) (:iso-8859-11 . #(0 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 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 65533 65533 65533 65533 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 65533 65533 65533 65533)) (:iso-8859-13 . #(0 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 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 8221 162 163 164 8222 166 167 216 169 342 171 172 173 174 198 176 177 178 179 8220 181 182 183 248 185 343 187 188 189 190 230 260 302 256 262 196 197 280 274 268 201 377 278 290 310 298 315 352 323 325 211 332 213 214 215 370 321 346 362 220 379 381 223 261 303 257 263 228 229 281 275 269 233 378 279 291 311 299 316 353 324 326 243 333 245 246 247 371 322 347 363 252 380 382 8217)) (:iso-8859-14 . #(0 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 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 7682 7683 163 266 267 7690 167 7808 169 7810 7691 7922 173 174 376 7710 7711 288 289 7744 7745 182 7766 7809 7767 7811 7776 7923 7812 7813 7777 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 372 209 210 211 212 213 214 7786 216 217 218 219 220 221 374 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 373 241 242 243 244 245 246 7787 248 249 250 251 252 253 375 255)) (:iso-8859-15 . #(0 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 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 8364 165 352 167 353 169 170 171 172 173 174 175 176 177 178 179 381 181 182 183 382 185 186 187 338 339 376 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255)) (:iso-8859-16 . #(0 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 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 260 261 321 8364 8222 352 167 353 169 536 171 377 173 378 379 176 177 268 322 381 8221 182 183 382 269 537 187 338 339 376 380 192 193 194 258 196 262 198 199 200 201 202 203 204 205 206 207 272 323 210 211 212 336 214 346 368 217 218 219 220 280 538 223 224 225 226 259 228 263 230 231 232 233 234 235 236 237 238 239 273 324 242 243 244 337 246 347 369 249 250 251 252 281 539 255)))) (deftest iso-8859-decode-check () (loop for enc in *iso-8859-charsets* for octets = (let ((octets (make-ub8-vector 256))) (dotimes (i 256 octets) (setf (aref octets i) i))) for string = (octets-to-string octets :encoding enc) do (is (equalp (map 'vector #'char-code string) (cdr (assoc enc *iso-8859-tables*)))))) (deftest character-out-of-range.utf-32 () (signals character-out-of-range (octets-to-string (ub8v 0 0 #xfe #xff 0 #x11 0 0) :encoding :utf-32 :errorp t))) ;;; RT: encoders and decoders were returning bogus values. (deftest encoder/decoder-retvals (encoding &optional (test-string (coerce "abc" '(simple-array character (*))))) (let* ((mapping (lookup-mapping babel::*string-vector-mappings* encoding)) (strlen (length test-string)) ;; encoding (octet-precount (funcall (octet-counter mapping) test-string 0 strlen -1)) (array (make-array octet-precount :element-type '(unsigned-byte 8))) (encoded-octet-count (funcall (encoder mapping) test-string 0 strlen array 0)) ;; decoding (string (make-string strlen)) (char-precount (funcall (code-point-counter mapping) array 0 octet-precount -1)) (char-count (funcall (decoder mapping) array 0 octet-precount string 0))) (is (= octet-precount encoded-octet-count)) (is (= char-precount char-count)) (is (string= test-string string)))) (deftest encoder-and-decoder-return-values () (mapcar 'encoder/decoder-retvals (remove-if 'ambiguous-encoding-p (list-character-encodings)))) (deftest code-point-sweep (encoding) (finishes (dotimes (i char-code-limit) (let ((char (ignore-errors (code-char i)))) (when char (ignore-some-conditions (character-encoding-error) (string-to-octets (string char) :encoding encoding))))))) #+enable-slow-babel-tests (deftest code-point-sweep-all-encodings () (mapc #'code-point-sweep (list-character-encodings))) (deftest octet-sweep (encoding) (finishes (loop for b1 upto #xff do (loop for b2 upto #xff do (loop for b3 upto #xff do (loop for b4 upto #xff do (ignore-some-conditions (character-decoding-error) (octets-to-string (ub8v b1 b2 b3 b4) :encoding encoding)))))))) #+enable-slow-babel-tests (deftest octet-sweep-all-encodings () (mapc #'octet-sweep (list-character-encodings)))
44,012
Common Lisp
.lisp
806
46.926799
132
0.630905
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
5f318b167d6ffa5d39606706720a2ed37af9f57c57617fda301d99e7a461ee16
42,541
[ 177769 ]
42,545
encoding.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/drakma-v2.0.9/encoding.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: DRAKMA; Base: 10 -*- ;;; $Header: /usr/local/cvsrep/drakma/read.lisp,v 1.17 2008/05/25 11:35:20 edi Exp $ ;;; Copyright (c) 2006-2012, Dr. Edmund Weitz. All rights reserved. ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :drakma) (defgeneric decode-stream (encoding-type stream) (:documentation "Generic function to decode a stream. This is a generic function which decodes the stream based on the encoding-type. If a response contains one or more transfer or content encodings, then decode-stream is called for each encoding type in the correct order to properly decode the stream to its original content. ENCODING-TYPE will be a keyword created by upcasing and interning the encoding type from the header. STREAM will be the stream that needs to be decoded. decode-stream returns a new stream from which you can read the decoded data.")) (defmethod decode-stream ((encoding-type t) stream) "Default handler, just return the stream." stream) #-:drakma-no-chipz (defmethod decode-stream ((encoding-type (eql :gzip)) stream) "Decode stream using gzip compression." (chipz:make-decompressing-stream 'chipz:gzip stream)) #-:drakma-no-chipz (defmethod decode-stream ((encoding-type (eql :deflate)) stream) "Decode stream using deflate compression in zlib container." (chipz:make-decompressing-stream 'chipz:zlib stream)) (defmethod decode-stream ((encoding-type (eql :chunked)) (stream chunked-input-stream)) "Decode a chunked stream. Special method for chunked-input-stream that just turns chunking on." (setf (chunked-stream-input-chunking-p stream) t) stream) (defmethod decode-stream ((encoding-type (eql :chunked)) stream) "General decode method for chunked stream. Creates new chunked-stream." (let ((chunk-stream (make-chunked-stream stream))) (decode-stream :chunked chunk-stream))) (defun decode-response-stream (headers stream &key (decode-content t)) "Perform all necessary decodings on stream, from the Transfer-Encoding and Content-Encoding headers. If DECODE-CONTENT is nil, only the Transfer-Encoding headers will be used." (let ((transfer-encodings (header-value :transfer-encoding headers)) (content-encodings (and decode-content (header-value :content-encoding headers)))) (when transfer-encodings (setq transfer-encodings (split-tokens transfer-encodings))) (when content-encodings (setq content-encodings (split-tokens content-encodings))) ;; Reverse, because we need to run decodings in the opposite order ;; they were applied. (let ((encodings (nreverse (nconc content-encodings transfer-encodings)))) (loop for s = stream then (decode-stream encoding s) for encoding-str in encodings for encoding = (intern (string-upcase encoding-str) 'keyword) finally (return s))))) (defun decode-flexi-stream (headers stream &key (decode-content t)) (declare (flexi-input-stream stream)) "Perform all necessary decodings on the internal stream of a flexi-stream. Wrapper around decode-response-stream which preserverves the external format of the flexi-stream. If DECODE-CONTENT is nil, the Content-Encoding header will not be used to determine which decoding mechanisms to use. Most servers use Content-Encoding to identify compression." (let* ((raw-stream (flexi-stream-stream stream)) (result (decode-response-stream headers raw-stream :decode-content decode-content))) (if (eq raw-stream result) stream (make-flexi-stream result :external-format (flexi-stream-external-format stream) :element-type (flexi-stream-element-type stream)))))
5,090
Common Lisp
.lisp
90
51.7
100
0.734497
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
049f9b7141aa1f7c6b361bdbe2b8be2c0a421052298bb1ed92d0ab43cd298fab
42,545
[ 108278, 128803 ]
42,546
util.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/drakma-v2.0.9/util.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: DRAKMA; Base: 10 -*- ;;; $Header: /usr/local/cvsrep/drakma/util.lisp,v 1.36 2008/05/30 11:30:45 edi Exp $ ;;; Copyright (c) 2006-2012, Dr. Edmund Weitz. All rights reserved. ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :drakma) #+:lispworks (require "comm") #+:lispworks (eval-when (:compile-toplevel :load-toplevel :execute) (import 'lw:when-let)) #-:lispworks (defmacro when-let ((var expr) &body body) "Evaluates EXPR, binds it to VAR, and executes BODY if VAR has a true value." `(let ((,var ,expr)) (when ,var ,@body))) #+:lispworks (eval-when (:compile-toplevel :load-toplevel :execute) (import 'lw:with-unique-names)) #-:lispworks (defmacro with-unique-names ((&rest bindings) &body body) "Syntax: WITH-UNIQUE-NAMES ( { var | (var x) }* ) declaration* form* Executes a series of forms with each VAR bound to a fresh, uninterned symbol. The uninterned symbol is as if returned by a call to GENSYM with the string denoted by X - or, if X is not supplied, the string denoted by VAR - as argument. The variable bindings created are lexical unless special declarations are specified. The scopes of the name bindings and declarations do not include the Xs. The forms are evaluated in order, and the values of all but the last are discarded \(that is, the body is an implicit PROGN)." ;; reference implementation posted to comp.lang.lisp as ;; <[email protected]> by Vebjorn Ljosa - see also ;; <http://www.cliki.net/Common%20Lisp%20Utilities> `(let ,(mapcar #'(lambda (binding) (check-type binding (or cons symbol)) (if (consp binding) (destructuring-bind (var x) binding (check-type var symbol) `(,var (gensym ,(etypecase x (symbol (symbol-name x)) (character (string x)) (string x))))) `(,binding (gensym ,(symbol-name binding))))) bindings) ,@body)) (defun ends-with-p (seq suffix &key (test #'char-equal)) "Returns true if the sequence SEQ ends with the sequence SUFFIX. Individual elements are compared with TEST." (let ((mismatch (mismatch seq suffix :from-end t :test test))) (or (null mismatch) (= mismatch (- (length seq) (length suffix)))))) (defun starts-with-p (seq prefix &key (test #'char-equal)) "Returns true if the sequence SEQ starts with the sequence PREFIX whereby the elements are compared using TEST." (let ((mismatch (mismatch seq prefix :test test))) (or (null mismatch) (= mismatch (length prefix))))) (defun url-encode (string external-format) "Returns a URL-encoded version of the string STRING using the external format EXTERNAL-FORMAT." (with-output-to-string (out) (loop for octet across (string-to-octets (or string "") :external-format external-format) for char = (code-char octet) do (cond ((or (char<= #\0 char #\9) (char<= #\a char #\z) (char<= #\A char #\Z) (find char "$-_.!*'()," :test #'char=)) (write-char char out)) ((char= char #\Space) (write-char #\+ out)) (t (format out "%~2,'0x" (char-code char))))))) (defun alist-to-url-encoded-string (alist external-format url-encoder) "ALIST is supposed to be an alist of name/value pairs where both names and values are strings \(or, for values, NIL). This function returns a string where this list is represented as for the content type `application/x-www-form-urlencoded', i.e. the values are URL-encoded using the external format EXTERNAL-FORMAT, the pairs are joined with a #\\& character, and each name is separated from its value with a #\\= character. If the value is NIL, no #\\= is used." (with-output-to-string (out) (loop for first = t then nil for (name . value) in alist unless first do (write-char #\& out) do (format out "~A~:[~;=~A~]" (funcall url-encoder name external-format) value (funcall url-encoder value external-format))))) (defun default-port (uri) "Returns the default port number for the \(PURI) URI URI. Works only with the http and https schemes." (ecase (puri:uri-scheme uri) (:http 80) (:https 443))) (defun non-default-port (uri) "If the \(PURI) URI specifies an explicit port number which is different from the default port its scheme, this port number is returned, otherwise NIL." (when-let (port (puri:uri-port uri)) (when (/= port (default-port uri)) port))) (defun user-agent-string (token) "Returns a corresponding user agent string if TOKEN is one of the keywords :DRAKMA, :FIREFOX, :EXPLORER, :OPERA, or :SAFARI. Returns TOKEN itself otherwise." (case token (:drakma (format nil "Drakma/~A (~A~@[ ~A~]; ~A;~@[ ~A;~] http://weitz.de/drakma/)" *drakma-version* (or (lisp-implementation-type) "Common Lisp") (or (lisp-implementation-version) "") (or #-:clisp (software-type) #+(or :win32 :mswindows) "Windows" #-(or :win32 :mswindows) "Unix") (or #-:clisp (software-version)))) (:firefox "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6") (:explorer "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)") (:opera "Opera/9.01 (Windows NT 5.1; U; en)") (:safari "Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en) AppleWebKit/418.8 (KHTML, like Gecko) Safari/419.3") (otherwise token))) (defun header-value (name headers) "If HEADERS is an alist of headers as returned by HTTP-REQUEST and NAME is a keyword naming a header, this function returns the corresponding value of this header \(or NIL if it's not in HEADERS)." (cdr (assoc name headers :test #'eq))) (defun parameter-present-p (name parameters) "If PARAMETERS is an alist of parameters as returned by, for example, READ-TOKENS-AND-PARAMETERS and NAME is a string naming a parameter, this function returns the full parameter \(name and value) - or NIL if it's not in PARAMETERS." (assoc name parameters :test #'string-equal)) (defun parameter-value (name parameters) "If PARAMETERS is an alist of parameters as returned by, for example, READ-TOKENS-AND-PARAMETERS and NAME is a string naming a parameter, this function returns the value of this parameter - or NIL if it's not in PARAMETERS." (cdr (parameter-present-p name parameters))) (defun make-random-string (&optional (length 50)) "Generates and returns a random string length LENGTH. The string will consist solely of decimal digits and ASCII letters." (with-output-to-string (s) (dotimes (i length) (write-char (ecase (random 5) ((0 1) (code-char (+ #.(char-code #\a) (random 26)))) ((2 3) (code-char (+ #.(char-code #\A) (random 26)))) ((4) (code-char (+ #.(char-code #\0) (random 10))))) s)))) (defun safe-parse-integer (string) "Like PARSE-INTEGER, but returns NIL instead of signalling an error." (ignore-errors (parse-integer string))) (defun interpret-as-month (string) "Tries to interpret STRING as a string denoting a month and returns the corresponding number of the month. Accepts three-letter abbreviations like \"Feb\" and full month names likes \"February\". Finally, the function also accepts strings representing integers from one to twelve." (or (when-let (pos (position (subseq string 0 (min 3 (length string))) '("Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec") :test #'string=)) (1+ pos)) (when-let (num (safe-parse-integer string)) (when (<= 1 num 12) num)))) (defun interpret-as-time-zone (string) "Tries to interpret STRING as a time zone abbreviation which can either be something like \"PST\" or \"GMT\" with an offset like \"GMT-02:00\"." (or (cdr (assoc string *time-zone-map* :test #'string=)) (cl-ppcre:register-groups-bind (sign hours minutes) ("(?:GMT|)\\s*([+-]?)(\\d\\d):?(\\d\\d)" string) (* (if (equal sign "-") 1 -1) (+ (parse-integer hours) (/ (parse-integer minutes) 60)))) (cookie-date-parse-error "Can't interpret ~S as a time zone." string))) (defun set-referer (referer-uri &optional alist) "Returns a fresh copy of the HTTP header list ALIST with the `Referer' header set to REFERER-URI. If REFERER-URI is NIL, the result will be a list of headers without a `Referer' header." (let ((alist-sans-referer (remove "Referer" alist :key #'car :test #'string=))) (cond (referer-uri (acons "Referer" referer-uri alist-sans-referer)) (t alist-sans-referer)))) (defun text-content-type-p (type subtype) "Returns a true value iff the combination of TYPE and SUBTYPE matches an entry of *TEXT-CONTENT-TYPES*. See docstring of *TEXT-CONTENT-TYPES* for more info." (loop for (candidate-type . candidate-subtype) in *text-content-types* thereis (and (or (null candidate-type) (string-equal type candidate-type)) (or (null candidate-subtype) (string-equal subtype candidate-subtype))))) (defmacro with-sequence-from-string ((stream string) &body body) "Kludge to make Chunga tokenizing functionality usable. Works like WITH-INPUT-FROM-STRING, but creates a sequence of octets that works with CHUNGA::PEEK-CHAR* and friends." `(flex:with-input-from-sequence (,stream (map 'list #'char-code ,string)) ,@body)) (defun split-set-cookie-string (string) "Splits the string STRING which is assumed to be the value of a `Set-Cookie' into parts corresponding to individual cookies and returns a list of these parts \(substrings). The string /should/ be split at commas, but heuristical approach is used instead which doesn't split at commas which are followed by what cannot be recognized as the start of the next cookie. This is necessary because servers send headers containing unquoted commas which are not meant as separators." ;; this would of course be a lot easier with CL-PPCRE's SPLIT (let ((cookie-start 0) (string-length (length string)) search-start result) (tagbody ;; at this point we know that COOKIE-START is the start of a new ;; cookie (at the start of the string or behind a comma) next-cookie (setq search-start cookie-start) ;; we reach this point if the last comma didn't separate two ;; cookies or if there was no previous comma skip-comma (unless (< search-start string-length) (return-from split-set-cookie-string (nreverse result))) ;; look is there's a comma (let* ((comma-pos (position #\, string :start search-start)) ;; and if so, look for a #\= behind the comma (equals-pos (and comma-pos (position #\= string :start comma-pos))) ;; check that (except for whitespace) there's only a token ;; (the name of the next cookie) between #\, and #\= (new-cookie-start-p (and equals-pos (every 'token-char-p (trim-whitespace string :start (1+ comma-pos) :end equals-pos))))) (when (and comma-pos (not new-cookie-start-p)) (setq search-start (1+ comma-pos)) (go skip-comma)) (let ((end-pos (or comma-pos string-length))) (push (trim-whitespace (subseq string cookie-start end-pos)) result) (setq cookie-start (1+ end-pos)) (go next-cookie)))))) #-:lispworks7.1 (defun make-ssl-stream (http-stream &key certificate key certificate-password verify (max-depth 10) ca-file ca-directory hostname) "Attaches SSL to the stream HTTP-STREAM and returns the SSL stream \(which will not be equal to HTTP-STREAM)." (declare (ignorable http-stream certificate-password max-depth ca-directory hostname)) (check-type verify (member nil :optional :required)) (when (and certificate (not (probe-file certificate))) (error "certificate file ~A not found" certificate)) (when (and key (not (probe-file key))) (error "key file ~A not found" key)) (when (and ca-file (not (probe-file ca-file))) (error "ca file ~A not found" ca-file)) #+(and :allegro (not :allegro-cl-express) (not :drakma-no-ssl)) (socket:make-ssl-client-stream http-stream :certificate certificate :key key :certificate-password certificate-password :verify verify :max-depth max-depth :ca-file ca-file :ca-directory ca-directory) #+(and :mocl-ssl (not :drakma-no-ssl)) (progn (when (or ca-file ca-directory) (warn ":max-depth, :ca-file and :ca-directory arguments not available on this platform")) (rt:start-ssl http-stream :verify verify)) #+(and (or :allegro-cl-express (not :allegro)) (not :mocl-ssl) (not :drakma-no-ssl)) (let ((s http-stream) (ctx (cl+ssl:make-context :verify-depth max-depth :verify-mode cl+ssl:+ssl-verify-none+ :verify-callback nil :verify-location (or (and ca-file ca-directory (list ca-file ca-directory)) ca-file ca-directory :default)))) (cl+ssl:with-global-context (ctx :auto-free-p t) (cl+ssl:make-ssl-client-stream (cl+ssl:stream-fd s) :verify verify :hostname hostname :close-callback (lambda () (close s)) :certificate certificate :key key :password certificate-password))) #+:drakma-no-ssl (error "SSL not supported. Remove :drakma-no-ssl from *features* to enable SSL")) (defun dissect-query (query-string) "Accepts a query string as in PURI:URI-QUERY and returns a corresponding alist of name/value pairs." (when query-string (loop for parameter-pair in (cl-ppcre:split "&" query-string) for (name value) = (cl-ppcre:split "=" parameter-pair :limit 2) collect (cons name value))))
16,298
Common Lisp
.lisp
320
42.328125
120
0.63219
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
3a55e70e0c29d94dfa3d8cf64f98acacb92aa439d76c5ae9220487e679bb28e6
42,546
[ 314232 ]
42,547
specials.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/drakma-v2.0.9/specials.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: DRAKMA; Base: 10 -*- ;;; $Header: /usr/local/cvsrep/drakma/specials.lisp,v 1.19 2008/01/14 01:57:02 edi Exp $ ;;; Copyright (c) 2006-2012, Dr. Edmund Weitz. All rights reserved. ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :drakma) (defparameter *drakma-version* #.(asdf:component-version (asdf:find-system :drakma)) "Drakma's version number as a string.") (defmacro define-constant (name value &optional doc) "A version of DEFCONSTANT for, cough, /strict/ CL implementations." ;; See <http://www.sbcl.org/manual#Defining-Constants> `(defconstant ,name (if (boundp ',name) (symbol-value ',name) ,value) ,@(when doc (list doc)))) (define-constant +latin-1+ (make-external-format :latin-1 :eol-style :lf) "Default external format when reading headers.") (define-constant +redirect-codes+ '(301 302 303 307) "A list of all HTTP return codes that redirect us to another URI.") (define-constant +redirect-to-get-codes+ '(302 303) "A list of HTTP return codes that redirect using a GET method (see http://en.wikipedia.org/wiki/Post/Redirect/Get).") (define-constant +known-methods+ '(:copy :delete :get :head :lock :mkcol :move :options :options* :patch :post :propfind :proppatch :put :report :trace :unlock) "The HTTP methods \(including WebDAV methods) Drakma knows.") (define-constant +redirect-to-get-methods+ '(:post) "A list of HTTP methods that should be changed to GET in case of redirect (see http://en.wikipedia.org/wiki/Post/Redirect/Get).") (defconstant +buffer-size+ 8192) (defvar *drakma-default-external-format* ':latin-1 "The default value for the external format keyword arguments of HTTP-REQUEST. The value of this variable will be interpreted by FLEXI-STREAMS. The initial value is the keyword :LATIN-1. (Note that Drakma binds *DEFAULT-EOL-STYLE* to :LF).") (defvar *header-stream* nil "If this variable is not NIL, it should be bound to a stream to which incoming and outgoing headers will be written for debugging purposes.") (defvar *allow-dotless-cookie-domains-p* nil "When this variable is not NIL, cookie domains containing no dots are considered valid. The default is NIL, meaning to disallow such domains except for \"localhost\".") (defvar *ignore-unparseable-cookie-dates-p* nil "Whether Drakma is allowed to treat `Expires' dates in cookie headers as non-existent if it can't parse them. If the value of this variable is NIL \(which is the default), an error will be signalled instead.") (defvar *remove-duplicate-cookies-p* t "Determines how duplicate cookies in the response are handled, defaults to T. Cookies are considered duplicate using COOKIE=. Valid values are: NIL - duplicates will not be removed, T or :KEEP-LAST - for duplicates, only the last cookie value will be kept, based on the order of the response header, :KEEP-FIRST - for duplicates, only the first cookie value will be kept, based on the order of the response header. Misbehaving servers may send duplicate cookies back in the same Set-Cookie header: HTTP/1.1 200 OK Server: My-hand-rolled-server Date: Wed, 07 Apr 2010 15:12:30 GMT Connection: Close Content-Type: text/html Content-Length: 82 Set-Cookie: a=1; Path=/; Secure, a=2; Path=/; Secure In this case Drakma has to choose whether cookie 'a' has the value '1' or '2'. By default, Drakma will choose the last value specified, in this case '2'. By default, Drakma conforms to RFC2109 HTTP State Management Mechanism, section 4.3.3 Cookie Management: If a user agent receives a Set-Cookie response header whose NAME is the same as a pre-existing cookie, and whose Domain and Path attribute values exactly \(string) match those of a pre-existing cookie, the new cookie supersedes the old.") (defvar *text-content-types* '(("text" . nil)) "A list of conses which are used by the default value of *BODY-FORMAT-FUNCTION* to decide whether a 'Content-Type' header denotes text content. The car and cdr of each cons should each be a string or NIL. A content type matches one of these entries (and thus denotes text) if the type part is STRING-EQUAL to the car or if the car is NIL and if the subtype part is STRING-EQUAL to the cdr or if the cdr is NIL. The initial value of this variable is the list \((\"text\" . nil)) which means that every content type that starts with \"text/\" is regarded as text, no matter what the subtype is.") (defvar *body-format-function* 'determine-body-format "A function which determines whether the content body returned by the server is text and should be treated as such or not. The function is called after the request headers have been read and it must accept two arguments, headers and external-format-in, where headers is like the third return value of HTTP-REQUEST while external-format-in is the HTTP-REQUEST argument of the same name. It should return NIL if the body should be regarded as binary content, or a FLEXI-STREAMS external format \(which will be used to read the body) otherwise. This function will only be called if the force-binary argument to HTTP-REQUEST is NIL. The initial value of this variable is a function which uses *TEXT-CONTENT-TYPES* to determine whether the body is text and then proceeds as described in the HTTP-REQUEST documentation entry.") (defvar *time-zone-map* ;; list taken from ;; <http://www.timeanddate.com/library/abbreviations/timezones/> '(("A" . -1) ("ACDT" . -10.5) ("ACST" . -9.5) ("ADT" . 3) ("AEDT" . -11) ("AEST" . -10) ("AKDT" . 8) ("AKST" . 9) ("AST" . 4) ("AWDT" . -9) ("AWST" . -8) ("B" . -2) ("BST" . -1) ("C" . -3) ("CDT" . 5) ("CEDT" . -2) ("CEST" . -2) ("CET" . -1) ("CST" . -10.5) ("CST" . -9.5) ("CST" . 6) ("CXT" . -7) ("D" . -4) ("E" . -5) ("EDT" . 4) ("EEDT" . -3) ("EEST" . -3) ("EET" . -2) ("EST" . -11) ("EST" . -10) ("EST" . 5) ("F" . -6) ("G" . -7) ("GMT" . 0) ("H" . -8) ("HAA" . 3) ("HAC" . 5) ("HADT" . 9) ("HAE" . 4) ("HAP" . 7) ("HAR" . 6) ("HAST" . 10) ("HAT" . 2.5) ("HAY" . 8) ("HNA" . 4) ("HNC" . 6) ("HNE" . 5) ("HNP" . 8) ("HNR" . 7) ("HNT" . 3.5) ("HNY" . 9) ("I" . -9) ("IST" . -1) ("K" . -10) ("L" . -11) ("M" . -12) ("MDT" . 6) ("MESZ" . -2) ("MEZ" . -1) ("MST" . 7) ("N" . 1) ("NDT" . 2.5) ("NFT" . -11.5) ("NST" . 3.5) ("O" . 2) ("P" . 3) ("PDT" . 7) ("PST" . 8) ("Q" . 4) ("R" . 5) ("S" . 6) ("T" . 7) ("U" . 8) ("UTC" . 0) ("V" . 9) ("W" . 10) ("WEDT" . -1) ("WEST" . -1) ("WET" . 0) ("WST" . -9) ("WST" . -8) ("X" . 11) ("Y" . 12) ("Z" . 0)) "An alist which maps time zone abbreviations to Common Lisp timezones.") (defvar *default-http-proxy* nil "HTTP proxy to be used as default. If not NIL, it should be a string denoting a proxy server through which the request should be sent. Or it can be a list of two values - a string denoting the proxy server and an integer denoting the port to use \(which will default to 80 otherwise).") ;; stuff for Nikodemus Siivola's HYPERDOC ;; see <http://common-lisp.net/project/hyperdoc/> ;; and <http://www.cliki.net/hyperdoc> ;; also used by LW-ADD-ONS (defvar *no-proxy-domains* nil "A list of domains for which a proxy should not be used.") (defvar *hyperdoc-base-uri* "http://weitz.de/drakma/") (let ((exported-symbols-alist (loop for symbol being the external-symbols of :drakma collect (cons symbol (concatenate 'string "#" (string-downcase symbol)))))) (defun hyperdoc-lookup (symbol type) (declare (ignore type)) (cdr (assoc symbol exported-symbols-alist :test #'eq))))
9,775
Common Lisp
.lisp
244
34.270492
107
0.63735
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
11a852dcaf441405b83893110cfecfbbeeb4e241eb89ef7b5ad45f4bd9662959
42,547
[ 217392, 470223 ]
42,548
read.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/drakma-v2.0.9/read.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: DRAKMA; Base: 10 -*- ;;; $Header: /usr/local/cvsrep/drakma/read.lisp,v 1.17 2008/05/25 11:35:20 edi Exp $ ;;; Copyright (c) 2006-2012, Dr. Edmund Weitz. All rights reserved. ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :drakma) (defun read-status-line (stream &optional log-stream) "Reads one line from STREAM \(using Chunga's READ-LINE*) and interprets it as a HTTP status line. Returns a list of two or three values - the protocol \(HTTP version) as a keyword, the status code as an integer, and optionally the reason phrase." (let* ((*current-error-message* "While reading status line:") (line (or (read-line* stream log-stream) (error 'drakma-simple-error :format-control "No status line - probably network error."))) (first-space-pos (or (position #\Space line :test #'char=) (syntax-error "No space in status line ~S." line))) (second-space-pos (position #\Space line :test #'char= :start (1+ first-space-pos)))) (list (cond ((string-equal line "HTTP/1.0" :end1 first-space-pos) :http/1.0) ((string-equal line "HTTP/1.1" :end1 first-space-pos) :http/1.1) (t (syntax-error "Unknown protocol in ~S." line))) (or (ignore-errors (parse-integer line :start (1+ first-space-pos) :end second-space-pos)) (syntax-error "Status code in ~S is not an integer." line)) (and second-space-pos (subseq line (1+ second-space-pos)))))) (defun get-content-type (headers) "Reads and parses a `Content-Type' header and returns it as three values - the type, the subtype, and an alist \(possibly empty) of name/value pairs for the optional parameters. HEADERS is supposed to be an alist of headers as returned by HTTP-REQUEST. Returns NIL if there is no such header amongst HEADERS." (when-let (content-type (header-value :content-type headers)) (with-sequence-from-string (stream content-type) (let* ((*current-error-message* "Corrupted Content-Type header:") (type (read-token stream)) (subtype (and (assert-char stream #\/) (read-token stream))) (parameters (read-name-value-pairs stream))) (values type subtype parameters))))) (defun read-token-and-parameters (stream) "Reads and returns \(as a two-element list) from STREAM a token and an optional list of parameters \(attribute/value pairs) following the token." (skip-whitespace stream) (list (read-token stream) (read-name-value-pairs stream))) (defun skip-more-commas (stream) "Reads and consumes from STREAM any number of commas and whitespace. Returns the following character or NIL in case of END-OF-FILE." (loop while (eql (peek-char* stream nil) #\,) do (read-char* stream) (skip-whitespace stream)) (skip-whitespace stream)) (defun read-tokens-and-parameters (string &key (value-required-p t)) "Reads a comma-separated list of tokens from the string STRING. Each token can be followed by an optional, semicolon-separated list of attribute/value pairs where the attributes are tokens followed by a #\\= character and a token or a quoted string. Returned is a list where each element is either a string \(for a simple token) or a cons of a string \(the token) and an alist \(the attribute/value pairs). If VALUE-REQUIRED-P is NIL, the value part \(including the #\\= character) of each attribute/value pair is optional." (with-sequence-from-string (stream string) (loop with *current-error-message* = (format nil "While parsing ~S:" string) for first = t then nil for next = (and (skip-whitespace stream) (or first (assert-char stream #\,)) (skip-whitespace stream) (skip-more-commas stream)) for token = (and next (read-token stream)) for parameters = (and token (read-name-value-pairs stream :value-required-p value-required-p)) while token collect (if parameters (cons token parameters) token)))) (defun split-tokens (string) "Splits the string STRING into a list of substrings separated by commas and optional whitespace. Empty substrings are ignored." (loop for old-position = -1 then position for position = (and old-position (position #\, string :test #'char= :start (1+ old-position))) for substring = (and old-position (trim-whitespace (subseq string (1+ old-position) position))) while old-position when (plusp (length substring)) collect substring))
6,213
Common Lisp
.lisp
110
48.209091
91
0.659826
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
cc2d69b8aeed7eb5493c01a1000ca87a6c74450090773e447093fe600e0c48f5
42,548
[ 108600, 280803 ]
42,549
conditions.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/drakma-v2.0.9/conditions.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: ODD-STREAMS; Base: 10 -*- ;;; $Header: /usr/local/cvsrep/odd-streams/conditions.lisp,v 1.5 2007/12/31 01:08:45 edi Exp $ ;;; Copyright (c) 2008-2012, Dr. Edmund Weitz. All rights reserved. ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :drakma) (define-condition drakma-condition (condition) () (:documentation "Superclass for all conditions related to Drakma.")) (define-condition drakma-error (drakma-condition error) () (:documentation "Superclass for all errors related to Drakma.")) (define-condition drakma-simple-error (drakma-error simple-condition) () (:documentation "Like DRAKMA-ERROR but with formatting capabilities.")) (define-condition drakma-warning (drakma-condition warning) () (:documentation "Superclass for all warnings related to Drakma.")) (define-condition drakma-simple-warning (drakma-warning simple-condition) () (:documentation "Like DRAKMA-WARNING but with formatting capabilities.")) (defun drakma-warn (format-control &rest format-arguments) "Signals a warning of type DRAKMA-SIMPLE-WARNING with the provided format control and arguments." (warn 'drakma-simple-warning :format-control format-control :format-arguments format-arguments)) (define-condition parameter-error (drakma-simple-error) () (:documentation "Signalled if a function was called with inconsistent or illegal parameters.")) (defun parameter-error (format-control &rest format-arguments) "Signals an error of type PARAMETER-ERROR with the provided format control and arguments." (error 'parameter-error :format-control format-control :format-arguments format-arguments)) (define-condition syntax-error (drakma-simple-error) () (:documentation "Signalled if Drakma encounters wrong or unknown syntax when reading the reply from the server.")) (defun syntax-error (format-control &rest format-arguments) "Signals an error of type SYNTAX-ERROR with the provided format control and arguments." (error 'syntax-error :format-control format-control :format-arguments format-arguments)) (define-condition cookie-error (drakma-simple-error) ((cookie :initarg :cookie :initform nil :reader cookie-error-cookie :documentation "The COOKIE object that caused this error. Can be NIL in case such an object couldn't be initialized.")) (:documentation "Signalled if someone tries to create a COOKIE object that's not valid.")) (defun cookie-error (cookie format-control &rest format-arguments) "Signals an error of type COOKIE-ERROR with the provided cookie \(can be NIL), format control and arguments." (error 'cookie-error :cookie cookie :format-control format-control :format-arguments format-arguments)) (define-condition cookie-date-parse-error (cookie-error) () (:documentation "Signalled if Drakma tries to parse the date of an incoming cookie header and can't interpret it.")) (defun cookie-date-parse-error (format-control &rest format-arguments) "Signals an error of type COOKIE-DATE-PARSE-ERROR with the provided format control and arguments." (error 'cookie-date-parse-error :format-control format-control :format-arguments format-arguments))
4,539
Common Lisp
.lisp
89
47.685393
94
0.758465
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
50a8ca227589b747269fdbfa4aff8217662aa7f566418b883cacefc8f4a68325
42,549
[ 193980, 420892 ]
42,550
cookies.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/drakma-v2.0.9/cookies.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: DRAKMA; Base: 10 -*- ;;; $Header: /usr/local/cvsrep/drakma/cookies.lisp,v 1.15 2008/01/14 01:57:01 edi Exp $ ;;; Copyright (c) 2006-2012, Dr. Edmund Weitz. All rights reserved. ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :drakma) (defclass cookie () ((name :initarg :name :initform (cookie-error nil "A cookie must have a name.") :accessor cookie-name :documentation "The name of the cookie.") (value :initarg :value :initform "" :accessor cookie-value :documentation "The cookie's value.") (domain :initarg :domain :initform (cookie-error nil "A cookie must have a domain.") :accessor cookie-domain :documentation "The domain the cookie is valid for.") (path :initarg :path :initform "/" :accessor cookie-path :documentation "The path prefix the cookie is valid for.") (expires :initarg :expires :initform nil :accessor cookie-expires :documentation "When the cookie expires. A Lisp universal time or NIL.") (securep :initarg :securep :initform nil :accessor cookie-securep :documentation "Whether the cookie must only be transmitted over secure connections.") (http-only-p :initarg :http-only-p :initform nil :accessor cookie-http-only-p :documentation "Whether the cookie should not be accessible from Javascript. This is a Microsoft extension that has been implemented in Firefox as well. See <http://msdn2.microsoft.com/en-us/library/ms533046.aspx>.")) (:documentation "Instances of this class represent HTTP cookies. If you need to create your own cookies, you should use MAKE-INSTANCE with the initargs :NAME, :DOMAIN, :VALUE, :PATH, :EXPIRES, :SECUREP, and :HTTP-ONLY-P all of which are optional except for the first two. The meaning of these initargs and the corresponding accessors should be pretty clear if one looks at the original cookie specification <http://wp.netscape.com/newsref/std/cookie_spec.html> (and at this page <http://msdn2.microsoft.com/en-us/library/ms533046.aspx> for the HttpOnly extension).")) (defun render-cookie-date (time) "Returns a string representation of the universal time TIME which can be used for cookie headers." (multiple-value-bind (second minute hour date month year weekday) (decode-universal-time time 0) (format nil "~A, ~2,'0d-~2,'0d-~4,'0d ~2,'0d:~2,'0d:~2,'0d GMT" (aref #("Mon" "Tue" "Wed" "Thu" "Fri" "Sat" "Sun") weekday) date month year hour minute second))) (defmethod print-object ((cookie cookie) stream) "Prints a representation of COOKIE similar to a `Set-Cookie' header." (print-unreadable-object (cookie stream :type t) (with-slots (name value expires path domain securep http-only-p) cookie (format stream "~A~@[=~A~]~@[; expires=~A~]~@[; path=~A~]~@[; domain=~A~]~@[; secure~]~@[; HttpOnly~]" name (and (plusp (length value)) value) (and expires (render-cookie-date expires)) path domain securep http-only-p)))) (defun normalize-cookie-domain (domain) "Adds a dot at the beginning of the string DOMAIN unless there is already one." (cond ((starts-with-p domain ".") domain) (t (format nil ".~A" domain)))) (defun valid-cookie-domain-p (domain) "Checks if the string DOMAIN contains enough dots to be acceptable. If *ALLOW-DOTLESS-COOKIE-DOMAINS-P* is non-NIL, every domain name is considered acceptable." (or *allow-dotless-cookie-domains-p* (string-equal domain "localhost") (> (count #\. (normalize-cookie-domain domain) :test #'char=) 1))) (defun cookie-domain-matches (domain uri) "Checks if the domain DOMAIN \(a string) matches the \(PURI) URI URI." (ends-with-p (normalize-cookie-domain (puri:uri-host uri)) (normalize-cookie-domain domain))) (defun send-cookie-p (cookie uri force-ssl) "Checks if the cookie COOKIE should be sent to the server depending on the \(PURI) URI URI and the value of FORCE-SSL \(as in HTTP-REQUEST)." (and ;; check domain (cookie-domain-matches (cookie-domain cookie) uri) ;; check path (starts-with-p (or (puri:uri-path uri) "/") (cookie-path cookie)) ;; check expiry date (let ((expires (cookie-expires cookie))) (or (null expires) (> expires (get-universal-time)))) ;; check if connection must be secure (or (null (cookie-securep cookie)) force-ssl (eq (puri:uri-scheme uri) :https)))) (defun check-cookie (cookie) "Checks if the slots of the COOKIE object COOKIE have valid values and raises a corresponding error of type COOKIE-ERROR otherwise." (with-slots (name value domain path expires) cookie (unless (and (stringp name) (plusp (length name))) (cookie-error cookie "Cookie name ~S must be a non-empty string." name)) (unless (stringp value) (cookie-error cookie "Cookie value ~S must be a non-empty string." value)) (unless (valid-cookie-domain-p domain) (cookie-error cookie "Invalid cookie domain ~S." domain)) (unless (and (stringp path) (plusp (length path))) (cookie-error cookie "Cookie path ~S must be a non-empty string." path)) (unless (or (null expires) (and (integerp expires) (plusp expires))) (cookie-error cookie "Cookie expiry ~S should have been NIL or a universal time." expires)))) (defmethod initialize-instance :after ((cookie cookie) &rest initargs) "Check cookie validity after creation." (declare (ignore initargs)) (check-cookie cookie)) (defmethod (setf cookie-name) :after (new-value (cookie cookie)) "Check cookie validity after name change." (declare (ignore new-value)) (check-cookie cookie)) (defmethod (setf cookie-value) :after (new-value (cookie cookie)) "Check cookie validity after value change." (declare (ignore new-value)) (check-cookie cookie)) (defmethod (setf cookie-domain) :after (new-value (cookie cookie)) "Check cookie validity after domain change." (declare (ignore new-value)) (check-cookie cookie)) (defmethod (setf cookie-path) :after (new-value (cookie cookie)) "Check cookie validity after path change." (declare (ignore new-value)) (check-cookie cookie)) (defmethod (setf cookie-expires) :after (new-value (cookie cookie)) "Check cookie validity after expiry change." (declare (ignore new-value)) (check-cookie cookie)) (defun cookie= (cookie1 cookie2) "Returns true if the cookies COOKIE1 and COOKIE2 are equal. Two cookies are considered to be equal if name and path are equal." (and (string= (cookie-name cookie1) (cookie-name cookie2)) (string= (cookie-path cookie1) (cookie-path cookie2)))) (defclass cookie-jar () ((cookies :initarg :cookies :initform nil :accessor cookie-jar-cookies :documentation "A list of the cookies in this cookie jar.")) (:documentation "An object of this class encapsulates a collection (a list, actually) of COOKIE objects. You create a new cookie jar with (MAKE-INSTANCE 'COOKIE-JAR) where you can optionally provide a list of COOKIE objects with the :COOKIES initarg. The cookies in a cookie jar are accessed with COOKIE-JAR-COOKIES.")) (defmethod print-object ((cookie-jar cookie-jar) stream) "Print a cookie jar, showing the number of cookies it contains." (print-unreadable-object (cookie-jar stream :type t :identity t) (format stream "(with ~A cookie~:P)" (length (cookie-jar-cookies cookie-jar))))) (defun parse-cookie-date (string) "Parses a cookie expiry date and returns it as a Lisp universal time. Currently understands the following formats: \"Wed, 06-Feb-2008 21:01:38 GMT\" \"Wed, 06-Feb-08 21:01:38 GMT\" \"Tue Feb 13 08:00:00 2007 GMT\" \"Wednesday, 07-February-2027 08:55:23 GMT\" \"Wed, 07-02-2017 10:34:45 GMT\" Instead of \"GMT\" time zone abbreviations like \"CEST\" and UTC offsets like \"GMT-01:30\" are also allowed. While this function has \"cookie\" in its name, it might come in handy in other situations as well and it is thus exported as a convenience function. " ;; it seems like everybody and their sister invents their own format ;; for this, so (as there's no real standard for it) we'll have to ;; make this function more flexible once we come across something ;; new; as an alternative we could use net-telent-date, but it also ;; fails to parse some of the stuff you encounter in the wild; or we ;; could try to employ CL-PPCRE, but that'd add a new dependency ;; without making this code much cleaner (handler-case (let* ((last-space-pos (or (position #\Space string :test #'char= :from-end t) (cookie-date-parse-error "Can't parse cookie date ~S, no space found." string))) (time-zone-string (subseq string (1+ last-space-pos))) (time-zone (interpret-as-time-zone time-zone-string)) second minute hour day month year) (dolist (part (rest (cl-ppcre:split "[ ,-]" (subseq string 0 last-space-pos)))) (when (and day month) (cond ((every #'digit-char-p part) (when year (cookie-date-parse-error "Can't parse cookie date ~S, confused by ~S part." string part)) (setq year (parse-integer part))) ((= (count #\: part :test #'char=) 2) (let ((h-m-s (mapcar #'safe-parse-integer (cl-ppcre:split ":" part)))) (setq hour (first h-m-s) minute (second h-m-s) second (third h-m-s)))) (t (cookie-date-parse-error "Can't parse cookie date ~S, confused by ~S part." string part)))) (cond ((null day) (unless (setq day (safe-parse-integer part)) (setq month (interpret-as-month part)))) ((null month) (setq month (interpret-as-month part))))) (unless (and second minute hour day month year) (cookie-date-parse-error "Can't parse cookie date ~S, component missing." string)) (when (< year 100) (setq year (+ year 2000))) (encode-universal-time second minute hour day month year time-zone)) (cookie-date-parse-error (condition) (cond (*ignore-unparseable-cookie-dates-p* (drakma-warn "~A" condition) nil) (t (error condition)))))) (defun parse-set-cookie (string) "Parses the `Set-Cookie' header line STRING and returns a list of three-element lists where each one contains the name of the cookie, the value of the cookie, and an attribute/value list for the optional cookie parameters." (let ((*current-error-message* (format nil "While parsing cookie header ~S:" string)) result) (dolist (substring (split-set-cookie-string string)) (with-sequence-from-string (stream substring) (let* ((name/value (read-name-value-pair stream :cookie-syntax t)) (parameters (read-name-value-pairs stream :value-required-p nil :cookie-syntax t))) (push (list (car name/value) (cdr name/value) parameters) result)))) (nreverse result))) (defun get-cookies (headers uri) "Returns a list of COOKIE objects corresponding to the `Set-Cookie' header as found in HEADERS \(an alist as returned by HTTP-REQUEST). Collects only cookies which match the domain of the \(PURI) URI URI." (loop with set-cookie-header = (header-value :set-cookie headers) with parsed-cookies = (and set-cookie-header (parse-set-cookie set-cookie-header)) for (name value parameters) in parsed-cookies for expires = (parameter-value "expires" parameters) for domain = (or (parameter-value "domain" parameters) (puri:uri-host uri)) when (and (valid-cookie-domain-p domain) (cookie-domain-matches domain uri)) collect (make-instance 'cookie :name name :value value :path (or (parameter-value "path" parameters) (puri:uri-path uri) "/") :expires (and expires (plusp (length expires)) (parse-cookie-date expires)) :domain domain :securep (not (not (parameter-present-p "secure" parameters))) :http-only-p (not (not (parameter-present-p "HttpOnly" parameters)))) into new-cookies finally (return (ccase *remove-duplicate-cookies-p* ((nil) new-cookies) ((:keep-last t) (delete-duplicates new-cookies :test #'cookie=)) (:keep-first (delete-duplicates new-cookies :test #'cookie= :from-end T)))))) (defun update-cookies (new-cookies cookie-jar) "Updates the cookies in COOKIE-JAR by replacing those which are equal to a cookie in \(the list) NEW-COOKIES with the corresponding `new' cookie and adding those which are really new." (setf (cookie-jar-cookies cookie-jar) (let ((updated-cookies (loop for old-cookie in (cookie-jar-cookies cookie-jar) collect (or (find old-cookie new-cookies :test #'cookie=) old-cookie)))) (union updated-cookies (set-difference new-cookies updated-cookies :test #'cookie=) :test #'cookie=))) cookie-jar) (defun delete-old-cookies (cookie-jar) "Removes all cookies from COOKIE-JAR which have either expired or which don't have an expiry date." (setf (cookie-jar-cookies cookie-jar) (loop with now = (get-universal-time) for cookie in (cookie-jar-cookies cookie-jar) for expires = (cookie-expires cookie) unless (or (null expires) (< expires now)) collect cookie)) cookie-jar)
15,585
Common Lisp
.lisp
301
43.76412
108
0.655335
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
4392696e255eddd2b8ef6e7dc4f227a07e3ab28579ed8daa9062839a5765c473
42,550
[ 124072, 368586 ]
42,551
packages.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/drakma-v2.0.9/packages.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-USER; Base: 10 -*- ;;; $Header: /usr/local/cvsrep/drakma/packages.lisp,v 1.22 2008/01/14 01:57:01 edi Exp $ ;;; Copyright (c) 2006-2012, Dr. Edmund Weitz. All rights reserved. ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (in-package :cl-user) (defpackage :drakma (:use :cl :flexi-streams :chunga) ;; the variable defined in the ASDF system definition (:shadow #:syntax-error #:parameter-error) (:export #:*drakma-version* #:*allow-dotless-cookie-domains-p* #:*body-format-function* #:*remove-duplicate-cookies-p* #:*default-http-proxy* #:*no-proxy-domains* #:*drakma-default-external-format* #:*header-stream* #:*ignore-unparseable-cookie-dates-p* #:*text-content-types* #:cookie #:cookie-error #:cookie-error-cookie #:cookie-date-parse-error #:cookie-domain #:cookie-expires #:cookie-http-only-p #:cookie-jar #:cookie-jar-cookies #:cookie-name #:cookie-path #:cookie-securep #:cookie-value #:cookie= #:delete-old-cookies #:decode-stream #:drakma-condition #:drakma-error #:drakma-warning #:get-content-type #:header-value #:http-request #:parameter-error #:parameter-present-p #:parameter-value #:parse-cookie-date #:read-tokens-and-parameters #:split-tokens #:syntax-error #:url-encode))
2,923
Common Lisp
.lisp
68
35.455882
88
0.642907
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
c05010b941d2f0310df7ae6b8d19ff92bb5a692c67f9e89a049d72f7e922c6c8
42,551
[ 57190, 296191 ]
42,552
drakma-test.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/drakma-v2.0.9/test/drakma-test.lisp
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-USER; Base: 10 -*- ;;; Copyright (c) 2013, Anton Vodonosov. All rights reserved. ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; * Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; * Redistributions in binary form must reproduce the above ;;; copyright notice, this list of conditions and the following ;;; disclaimer in the documentation and/or other materials ;;; provided with the distribution. ;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED ;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ;;; ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY ;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE ;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS ;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. (defpackage :drakma-test (:use :cl :fiveam)) (in-package :drakma-test) (def-suite :drakma) (in-suite :drakma) (test get-google (let ((drakma:*header-stream* *standard-output*)) (multiple-value-bind (body-or-stream status-code) (drakma:http-request "http://google.com/") (is (> (length body-or-stream) 0)) (is (= 200 status-code))))) (test get-google-ssl (let ((drakma:*header-stream* *standard-output*)) (multiple-value-bind (body-or-stream status-code) (drakma:http-request "https://google.com/") (is (> (length body-or-stream) 0)) (is (= 200 status-code))))) (test post-google (let ((drakma:*header-stream* *standard-output*)) (multiple-value-bind (body-or-stream status-code headers uri stream must-close reason-phrase) (drakma:http-request "http://google.com/" :method :post :parameters '(("a" . "b"))) (declare (ignore headers uri stream must-close)) (is (> (length body-or-stream) 0)) (is (= 405 status-code)) (is (string= "Method Not Allowed" reason-phrase))))) (test post-google-ssl (let ((drakma:*header-stream* *standard-output*)) (multiple-value-bind (body-or-stream status-code headers uri stream must-close reason-phrase) (drakma:http-request "https://google.com/" :method :post :parameters '(("a" . "b"))) (declare (ignore headers uri stream must-close)) (is (> (length body-or-stream) 0)) (is (= 405 status-code)) (is (string= "Method Not Allowed" reason-phrase))))) (test gzip-content (let ((drakma:*header-stream* *standard-output*) (drakma:*text-content-types* (cons '(nil . "json") drakma:*text-content-types*))) (multiple-value-bind (body-or-stream status-code) (drakma:http-request "http://httpbin.org/gzip" :decode-content t) (is (= 200 status-code)) (is (typep body-or-stream 'string)) (is (search "\"gzipped\": true" body-or-stream))))) (test deflate-content (let ((drakma:*header-stream* *standard-output*) (drakma:*text-content-types* (cons '(nil . "json") drakma:*text-content-types*))) (multiple-value-bind (body-or-stream status-code) (drakma:http-request "http://httpbin.org/deflate" :decode-content t) (is (= 200 status-code)) (is (typep body-or-stream 'string)) (is (search "\"deflated\": true" body-or-stream))))) (test gzip-content-undecoded (let ((drakma:*header-stream* *standard-output*)) (multiple-value-bind (body-or-stream status-code) (drakma:http-request "http://httpbin.org/gzip") (is (= 200 status-code)) (is (typep body-or-stream '(vector flexi-streams:octet))) (is (> (length body-or-stream) 0)) (is (equalp #(#x1f #x8b) (subseq body-or-stream 0 2)))))) (test deflate-content-undecoded (let ((drakma:*header-stream* *standard-output*)) (multiple-value-bind (body-or-stream status-code) (drakma:http-request "http://httpbin.org/deflate") (is (= 200 status-code)) (is (typep body-or-stream '(vector flexi-streams:octet))) (is (> (length body-or-stream) 0)) (is (equalp #x78 (aref body-or-stream 0)))))) (test stream (multiple-value-bind (stream status-code) (drakma:http-request "http://google.com/" :want-stream t) (is (streamp stream)) (is (= 200 status-code)) (is (subtypep (stream-element-type stream) 'character)) (let ((buffer (make-string 1))) (read-sequence buffer stream)))) (test force-binary (multiple-value-bind (stream status-code) (drakma:http-request "http://google.com/" :want-stream t :force-binary t) (is (streamp stream)) (is (= 200 status-code)) (is (subtypep (stream-element-type stream) 'flexi-streams:octet)) (let ((buffer (make-array 1 :element-type 'flexi-streams:octet))) (read-sequence buffer stream)))) (test verify.wrong.host (signals error (drakma:http-request "https://wrong.host.badssl.com/" :verify :required)) (signals error (drakma:http-request "https://wrong.host.badssl.com/" :verify :optional)) (finishes (drakma:http-request "https://wrong.host.badssl.com//" :verify nil))) (test verify.expired (signals error (drakma:http-request "https://expired.badssl.com//" :verify :required)) (signals error (drakma:http-request "https://expired.badssl.com/" :verify :optional)) (finishes (drakma:http-request "https://expired.badssl.com/" :verify nil))) (test verify.self-signed (signals error (drakma:http-request "https://self-signed.badssl.com/" :verify :required))) (test verify.untrusted-root (signals error (drakma:http-request "https://untrusted-root.badssl.com/" :verify :required)))
6,175
Common Lisp
.lisp
124
44.806452
97
0.677173
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
54b503866449fa60cd3934a0f1300b7be0ab97520be88c88649ce4f6418522ed
42,552
[ 327231 ]
42,553
trivial-garbage.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/trivial-garbage-20211230-git/trivial-garbage.lisp
;;;; -*- Mode: LISP; Syntax: ANSI-Common-lisp; Base: 10 -*- ;;;; The above modeline is required for Genera. Do not change. ;; ;;; trivial-garbage.lisp --- Trivial Garbage! ;;; ;;; This software is placed in the public domain by Luis Oliveira ;;; <[email protected]> and is provided with absolutely no ;;; warranty. #+xcvb (module ()) (defpackage #:trivial-garbage (:use #:cl) (:shadow #:make-hash-table) (:nicknames #:tg) (:export #:gc #:make-weak-pointer #:weak-pointer-value #:weak-pointer-p #:make-weak-hash-table #:hash-table-weakness #:finalize #:cancel-finalization) (:documentation "@a[http://common-lisp.net/project/trivial-garbage]{trivial-garbage} provides a portable API to finalizers, weak hash-tables and weak pointers on all major implementations of the Common Lisp programming language. For a good introduction to these data-structures, have a look at @a[http://www.haible.de/bruno/papers/cs/weak/WeakDatastructures-writeup.html]{Weak References: Data Types and Implementation} by Bruno Haible. Source code is available at @a[https://github.com/trivial-garbage/trivial-garbage]{github}, which you are welcome to use for submitting patches and/or @a[https://github.com/trivial-garbage/trivial-garbage/issues]{bug reports}. Discussion takes place on @a[http://lists.common-lisp.net/cgi-bin/mailman/listinfo/trivial-garbage-devel]{trivial-garbage-devel at common-lisp.net}. @a[http://common-lisp.net/project/trivial-garbage/releases/]{Tarball releases} are available, but the easiest way to install this library is via @a[http://www.quicklisp.org/]{Quicklisp}: @code{(ql:quickload :trivial-garbage)}. @begin[Weak Pointers]{section} A @em{weak pointer} holds an object in a way that does not prevent it from being reclaimed by the garbage collector. An object referenced only by weak pointers is considered unreachable (or \"weakly reachable\") and so may be collected at any time. When that happens, the weak pointer's value becomes @code{nil}. @aboutfun{make-weak-pointer} @aboutfun{weak-pointer-value} @aboutfun{weak-pointer-p} @end{section} @begin[Weak Hash-Tables]{section} A @em{weak hash-table} is one that weakly references its keys and/or values. When both key and value are unreachable (or weakly reachable) that pair is reclaimed by the garbage collector. @aboutfun{make-weak-hash-table} @aboutfun{hash-table-weakness} @end{section} @begin[Finalizers]{section} A @em{finalizer} is a hook that is executed after a given object has been reclaimed by the garbage collector. @aboutfun{finalize} @aboutfun{cancel-finalization} @end{section}")) (in-package #:trivial-garbage) ;;;; GC (defun gc (&key full verbose) "Initiates a garbage collection. @code{full} forces the collection of all generations, when applicable. When @code{verbose} is @em{true}, diagnostic information about the collection is printed if possible." (declare (ignorable verbose full)) #+(or cmu scl) (ext:gc :verbose verbose :full full) #+sbcl (sb-ext:gc :full full) #+allegro (excl:gc (not (null full))) #+(or abcl clisp) (ext:gc) #+ecl (si:gc t) #+openmcl (ccl:gc) #+corman (ccl:gc (if full 3 0)) #+lispworks (hcl:gc-generation (if full t 0)) #+clasp (gctools:garbage-collect) #+mezzano (mezzano.extensions:gc :full full) #+genera (scl:let-globally ((si:gc-report-stream *standard-output*) (si:gc-reports-enable verbose) (si:gc-ephemeral-reports-enable verbose) (si:gc-warnings-enable verbose)) (if full (sys:gc-immediately t) (si:ephemeral-gc-flip)))) ;;;; Weak Pointers #+openmcl (defvar *weak-pointers* (cl:make-hash-table :test 'eq :weak :value) "Weak value hash-table mapping between pseudo weak pointers and its values.") #+genera (defvar *weak-pointers* (scl:make-hash-table :test 'eq :gc-protect-values nil) "Weak value hash-table mapping between pseudo weak pointers and its values.") #+(or allegro openmcl lispworks genera) (defstruct (weak-pointer (:constructor %make-weak-pointer)) #-(or openmcl genera) pointer) (defun make-weak-pointer (object) "Creates a new weak pointer which points to @code{object}. For portability reasons, @code{object} must not be @code{nil}." (assert (not (null object))) #+sbcl (sb-ext:make-weak-pointer object) #+(or cmu scl) (ext:make-weak-pointer object) #+clisp (ext:make-weak-pointer object) #+abcl (ext:make-weak-reference object) #+ecl (ext:make-weak-pointer object) #+allegro (let ((wv (excl:weak-vector 1))) (setf (svref wv 0) object) (%make-weak-pointer :pointer wv)) #+(or openmcl genera) (let ((wp (%make-weak-pointer))) (setf (gethash wp *weak-pointers*) object) wp) #+corman (ccl:make-weak-pointer object) #+lispworks (let ((array (make-array 1 :weak t))) (setf (svref array 0) object) (%make-weak-pointer :pointer array)) #+clasp (core:make-weak-pointer object) #+mezzano (mezzano.extensions:make-weak-pointer object)) #-(or allegro openmcl lispworks genera) (defun weak-pointer-p (object) "Returns @em{true} if @code{object} is a weak pointer and @code{nil} otherwise." #+sbcl (sb-ext:weak-pointer-p object) #+(or cmu scl) (ext:weak-pointer-p object) #+clisp (ext:weak-pointer-p object) #+abcl (typep object 'ext:weak-reference) #+ecl (typep object 'ext:weak-pointer) #+corman (ccl:weak-pointer-p object) #+clasp (core:weak-pointer-valid object) #+mezzano (mezzano.extensions:weak-pointer-p object)) (defun weak-pointer-value (weak-pointer) "If @code{weak-pointer} is valid, returns its value. Otherwise, returns @code{nil}." #+sbcl (values (sb-ext:weak-pointer-value weak-pointer)) #+(or cmu scl) (values (ext:weak-pointer-value weak-pointer)) #+clisp (values (ext:weak-pointer-value weak-pointer)) #+abcl (values (ext:weak-reference-value weak-pointer)) #+ecl (values (ext:weak-pointer-value weak-pointer)) #+allegro (svref (weak-pointer-pointer weak-pointer) 0) #+(or openmcl genera) (values (gethash weak-pointer *weak-pointers*)) #+corman (ccl:weak-pointer-obj weak-pointer) #+lispworks (svref (weak-pointer-pointer weak-pointer) 0) #+clasp (core:weak-pointer-value weak-pointer) #+mezzano (values (mezzano.extensions:weak-pointer-value object))) ;;;; Weak Hash-tables ;;; Allegro can apparently create weak hash-tables with both weak keys ;;; and weak values but it's not obvious whether it's an OR or an AND ;;; relation. TODO: figure that out. (defun weakness-keyword-arg (weakness) (declare (ignorable weakness)) #+(or sbcl abcl clasp ecl-weak-hash mezzano) :weakness #+(or clisp openmcl) :weak #+lispworks :weak-kind #+allegro (case weakness (:key :weak-keys) (:value :values)) #+cmu :weak-p #+genera :gc-protect-values) (defvar *weakness-warnings* '() "List of weaknesses that have already been warned about this session. Used by `weakness-missing'.") (defun weakness-missing (weakness errorp) "Signal an error or warning, depending on ERRORP, about lack of Lisp support for WEAKNESS." (cond (errorp (error "Your Lisp does not support weak ~(~A~) hash-tables." weakness)) ((member weakness *weakness-warnings*) nil) (t (push weakness *weakness-warnings*) (warn "Your Lisp does not support weak ~(~A~) hash-tables." weakness)))) (defun weakness-keyword-opt (weakness errorp) (declare (ignorable errorp)) (ecase weakness (:key #+(or lispworks sbcl abcl clasp clisp openmcl ecl-weak-hash mezzano) :key #+(or allegro cmu) t #-(or lispworks sbcl abcl clisp openmcl allegro cmu ecl-weak-hash clasp mezzano) (weakness-missing weakness errorp)) (:value #+allegro :weak #+(or clisp openmcl sbcl abcl lispworks cmu ecl-weak-hash mezzano) :value #+genera nil #-(or allegro clisp openmcl sbcl abcl lispworks cmu ecl-weak-hash mezzano genera) (weakness-missing weakness errorp)) (:key-or-value #+(or clisp sbcl abcl cmu mezzano) :key-or-value #+lispworks :either #-(or clisp sbcl abcl lispworks cmu mezzano) (weakness-missing weakness errorp)) (:key-and-value #+(or clisp abcl sbcl cmu ecl-weak-hash mezzano) :key-and-value #+lispworks :both #-(or clisp sbcl abcl lispworks cmu ecl-weak-hash mezzano) (weakness-missing weakness errorp)))) (defun make-weak-hash-table (&rest args &key weakness (weakness-matters t) #+openmcl (test #'eql) &allow-other-keys) "Returns a new weak hash table. In addition to the standard arguments accepted by @code{cl:make-hash-table}, this function adds extra keywords: @code{:weakness} being the kind of weak table it should create, and @code{:weakness-matters} being whether an error should be signalled when that weakness isn't available (the default is to signal an error). @code{weakness} can be one of @code{:key}, @code{:value}, @code{:key-or-value}, @code{:key-and-value}. If @code{weakness} is @code{:key} or @code{:value}, an entry is kept as long as its key or value is reachable, respectively. If @code{weakness} is @code{:key-or-value} or @code{:key-and-value}, an entry is kept if either or both of its key and value are reachable, respectively. @code{tg::make-hash-table} is available as an alias for this function should you wish to import it into your package and shadow @code{cl:make-hash-table}." (remf args :weakness) (remf args :weakness-matters) (if weakness (let ((arg (weakness-keyword-arg weakness)) (opt (weakness-keyword-opt weakness weakness-matters))) (apply #-genera #'cl:make-hash-table #+genera #'scl:make-hash-table #+openmcl :test #+openmcl (if (eq opt :key) #'eq test) #+clasp :test #+clasp #'eq (if arg (list* arg opt args) args))) (apply #'cl:make-hash-table args))) ;;; If you want to use this function to override CL:MAKE-HASH-TABLE, ;;; it's necessary to shadow-import it. For example: ;;; ;;; (defpackage #:foo ;;; (:use #:common-lisp #:trivial-garbage) ;;; (:shadowing-import-from #:trivial-garbage #:make-hash-table)) ;;; (defun make-hash-table (&rest args) (apply #'make-weak-hash-table args)) (defun hash-table-weakness (ht) "Returns one of @code{nil}, @code{:key}, @code{:value}, @code{:key-or-value} or @code{:key-and-value}." #-(or allegro sbcl abcl clisp cmu openmcl lispworks ecl-weak-hash clasp mezzano genera) (declare (ignore ht)) ;; keep this first if any of the other lisps bugously insert a NIL ;; for the returned (values) even when *read-suppress* is NIL (e.g. clisp) #.(if (find :sbcl *features*) (if (find-symbol "HASH-TABLE-WEAKNESS" "SB-EXT") (read-from-string "(sb-ext:hash-table-weakness ht)") nil) (values)) #+abcl (sys:hash-table-weakness ht) #+ecl-weak-hash (ext:hash-table-weakness ht) #+allegro (cond ((excl:hash-table-weak-keys ht) :key) ((eq (excl:hash-table-values ht) :weak) :value)) #+clisp (ext:hash-table-weak-p ht) #+cmu (let ((weakness (lisp::hash-table-weak-p ht))) (if (eq t weakness) :key weakness)) #+openmcl (ccl::hash-table-weak-p ht) #+lispworks (system::hash-table-weak-kind ht) #+clasp (core:hash-table-weakness ht) #+mezzano (mezzano.extensions:hash-table-weakness ht) #+genera (if (null (getf (cli::basic-table-options ht) :gc-protect-values t)) :value nil)) ;;;; Finalizers ;;; Note: Lispworks can't finalize gensyms. #+(or allegro clisp lispworks openmcl) (defvar *finalizers* (cl:make-hash-table :test 'eq #+allegro :weak-keys #+:allegro t #+(or clisp openmcl) :weak #+lispworks :weak-kind #+(or clisp openmcl lispworks) :key) "Weak hashtable that holds registered finalizers.") #+corman (progn (defvar *finalizers* '() "Weak alist that holds registered finalizers.") (defvar *finalizers-cs* (threads:allocate-critical-section))) #+lispworks (progn (hcl:add-special-free-action 'free-action) (defun free-action (object) (let ((finalizers (gethash object *finalizers*))) (unless (null finalizers) (mapc #'funcall finalizers))))) #+mezzano (progn (defvar *finalizers* (cl:make-hash-table :test 'eq :weakness :key) "Weak hashtable that holds registered finalizers.") (defvar *finalizers-lock* (mezzano.supervisor:make-mutex '*finalizers-lock*))) ;;; Note: ECL bytecmp does not perform escape analysis and unused ;;; variables are not optimized away from its lexenv. That leads to ;;; closing over whole definition lexenv. That's why we define ;;; EXTEND-FINALIZER-FN which defines lambda outside the lexical scope ;;; of FINALIZE (which inludes object) - to prevent closing over ;;; finalized object. This problem does not apply to C compiler. #+ecl (defun extend-finalizer-fn (old-fn new-fn) (if (null old-fn) (lambda (obj) (declare (ignore obj)) (funcall new-fn)) (lambda (obj) (declare (ignore obj)) (funcall new-fn) (funcall old-fn nil)))) (defun finalize (object function) "Pushes a new @code{function} to the @code{object}'s list of finalizers. @code{function} should take no arguments. Returns @code{object}. @b{Note:} @code{function} should not attempt to look at @code{object} by closing over it because that will prevent it from being garbage collected." #+genera (declare (ignore object function)) #+(or cmu scl) (ext:finalize object function) #+sbcl (sb-ext:finalize object function) #+abcl (ext:finalize object function) #+ecl (let* ((old-fn (ext:get-finalizer object)) (new-fn (extend-finalizer-fn old-fn function))) (ext:set-finalizer object new-fn) object) #+allegro (progn (push (excl:schedule-finalization object (lambda (obj) (declare (ignore obj)) (funcall function))) (gethash object *finalizers*)) object) #+clasp (gctools:finalize object (lambda (obj) (declare (ignore obj)) (funcall function))) #+clisp ;; The CLISP code used to be a bit simpler but we had to workaround ;; a bug regarding the interaction between GC and weak hashtables. ;; See <http://article.gmane.org/gmane.lisp.clisp.general/11028> ;; and <http://article.gmane.org/gmane.lisp.cffi.devel/994>. (multiple-value-bind (finalizers presentp) (gethash object *finalizers* (cons 'finalizers nil)) (unless presentp (setf (gethash object *finalizers*) finalizers) (ext:finalize object (lambda (obj) (declare (ignore obj)) (mapc #'funcall (cdr finalizers))))) (push function (cdr finalizers)) object) #+openmcl (progn (ccl:terminate-when-unreachable object (lambda (obj) (declare (ignore obj)) (funcall function))) ;; store number of finalizers (incf (gethash object *finalizers* 0)) object) #+corman (flet ((get-finalizers (obj) (assoc obj *finalizers* :test #'eq :key #'ccl:weak-pointer-obj))) (threads:with-synchronization *finalizers-cs* (let ((pair (get-finalizers object))) (if (null pair) (push (list (ccl:make-weak-pointer object) function) *finalizers*) (push function (cdr pair))))) (ccl:register-finalization object (lambda (obj) (threads:with-synchronization *finalizers-cs* (mapc #'funcall (cdr (get-finalizers obj))) (setq *finalizers* (delete obj *finalizers* :test #'eq :key #'ccl:weak-pointer-obj))))) object) #+lispworks (progn (let ((finalizers (gethash object *finalizers*))) (unless finalizers (hcl:flag-special-free-action object)) (setf (gethash object *finalizers*) (cons function finalizers))) object) #+mezzano (mezzano.supervisor:with-mutex (*finalizers-lock*) (let ((finalizer-key (gethash object *finalizers*))) (unless finalizer-key (setf finalizer-key (mezzano.extensions:make-weak-pointer object :finalizer (lambda () (let ((finalizers (mezzano.supervisor:with-mutex (*finalizers-lock*) (prog1 (gethash finalizer-key *finalizers*) (remhash finalizer-key *finalizers*))))) (mapc #'funcall finalizers))))) (setf (gethash object *finalizers*) finalizer-key)) (push function (gethash finalizer-key *finalizers*))) ;; Make sure the object doesn't actually get captured by the finalizer lambda. (prog1 object (setf object nil))) #+genera (error "Finalizers are not available in Genera.")) (defun cancel-finalization (object) "Cancels all of @code{object}'s finalizers, if any." #+genera (declare (ignore object)) #+cmu (ext:cancel-finalization object) #+scl (ext:cancel-finalization object nil) #+sbcl (sb-ext:cancel-finalization object) #+abcl (ext:cancel-finalization object) #+ecl (ext:set-finalizer object nil) #+allegro (progn (mapc #'excl:unschedule-finalization (gethash object *finalizers*)) (remhash object *finalizers*)) #+clasp (gctools:definalize object) #+clisp (multiple-value-bind (finalizers present-p) (gethash object *finalizers*) (when present-p (setf (cdr finalizers) nil)) (remhash object *finalizers*)) #+openmcl (let ((count (gethash object *finalizers*))) (unless (null count) (dotimes (i count) (ccl:cancel-terminate-when-unreachable object)))) #+corman (threads:with-synchronization *finalizers-cs* (setq *finalizers* (delete object *finalizers* :test #'eq :key #'ccl:weak-pointer-obj))) #+lispworks (progn (remhash object *finalizers*) (hcl:flag-not-special-free-action object)) #+mezzano (mezzano.supervisor:with-mutex (*finalizers-lock*) (let ((finalizer-key (gethash object *finalizers*))) (when finalizer-key (setf (gethash finalizer-key *finalizers*) '())))) #+genera (error "Finalizers are not available in Genera."))
18,753
Common Lisp
.lisp
434
37.119816
105
0.668582
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
71223f0c6cb5b63a89b27485a8a42f65bb89e460bb6f968a4cbb8425757a2651
42,553
[ -1 ]
42,554
tests.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/trivial-garbage-20211230-git/tests.lisp
;;;; -*- Mode: LISP; Syntax: ANSI-Common-lisp; Base: 10 -*- ;;;; The above modeline is required for Genera. Do not change. ;;; ;;; tests.lisp --- trivial-garbage tests. ;;; ;;; This software is placed in the public domain by Luis Oliveira ;;; <[email protected]> and is provided with absolutely no ;;; warranty. (defpackage #:trivial-garbage-tests (:use #:cl #:trivial-garbage #:regression-test) (:nicknames #:tg-tests) (:export #:run)) (in-package #:trivial-garbage-tests) (defun run () (let ((*package* (find-package :trivial-garbage-tests))) (do-tests) (null (set-difference (regression-test:pending-tests) rtest::*expected-failures*)))) ;;;; Weak Pointers (deftest pointers.1 (weak-pointer-p (make-weak-pointer 42)) t) (deftest pointers.2 (weak-pointer-value (make-weak-pointer 42)) 42) ;;;; Weak Hashtables (eval-when (:compile-toplevel :load-toplevel :execute) (defun sbcl-without-weak-hash-tables-p () (if (and (find :sbcl *features*) (not (find-symbol "HASH-TABLE-WEAKNESS" "SB-EXT"))) '(:and) '(:or)))) #+(or corman scl #.(tg-tests::sbcl-without-weak-hash-tables-p)) (progn (pushnew 'hashtables.weak-key.1 rt::*expected-failures*) (pushnew 'hashtables.weak-key.2 rt::*expected-failures*) (pushnew 'hashtables.weak-value.1 rt::*expected-failures*)) #+clasp (progn (pushnew 'pointers.1 rt::*expected-failures*) (pushnew 'pointers.2 rt::*expected-failures*) (pushnew 'hashtables.weak-value.1 rt::*expected-failures*)) #+genera (progn (pushnew 'hashtables.weak-key.1 rt::*expected-failures*) (pushnew 'hashtables.weak-key.2 rt::*expected-failures*)) (deftest hashtables.weak-key.1 (let ((ht (make-weak-hash-table :weakness :key))) (values (hash-table-p ht) (hash-table-weakness ht))) t :key) (deftest hashtables.weak-key.2 (let ((ht (make-weak-hash-table :weakness :key :test 'eq))) (values (hash-table-p ht) (hash-table-weakness ht))) t :key) (deftest hashtables.weak-value.1 (let ((ht (make-weak-hash-table :weakness :value))) (values (hash-table-p ht) (hash-table-weakness ht))) t :value) (deftest hashtables.not-weak.1 (hash-table-weakness (make-hash-table)) nil) ;;;; Finalizers ;;; ;;; These tests are, of course, not very reliable. (defun dummy (x) (declare (ignore x)) nil) (defun test-finalizers-aux (count extra-action) (let* ((cons (list 0)) ;; lbd should not be defined in a lexical scope where obj is ;; present to prevent closing over the variable on compilers ;; which does not optimize away unused lexenv variables (i.e ;; ecl's bytecmp). (lbd (lambda () (incf (car cons)))) (obj (string (gensym)))) (dotimes (i count) (finalize obj lbd)) (when extra-action (cancel-finalization obj) (when (eq extra-action :add-again) (dotimes (i count) (finalize obj lbd)))) (setq obj (gensym)) (setq obj (dummy obj)) cons)) (defvar *result*) #+genera (progn (pushnew 'finalizers.1 rt::*expected-failures*) (pushnew 'finalizers.2 rt::*expected-failures*) (pushnew 'finalizers.3 rt::*expected-failures*) (pushnew 'finalizers.4 rt::*expected-failures*) (pushnew 'finalizers.5 rt::*expected-failures*)) ;;; I don't really understand this, but it seems to work, and stems ;;; from the observation that typing the code in sequence at the REPL ;;; achieves the desired result. Superstition at its best. (defmacro voodoo (string) `(funcall (compile nil `(lambda () (eval (let ((*package* (find-package :tg-tests))) (read-from-string ,,string))))))) (defun test-finalizers (count &optional remove) (gc :full t) (voodoo (format nil "(setq *result* (test-finalizers-aux ~S ~S))" count remove)) (voodoo "(gc :full t)") ;; Normally done by a background thread every 0.3 sec: #+openmcl (ccl::drain-termination-queue) ;; (an alternative is to sleep a bit) (voodoo "(car *result*)")) (deftest finalizers.1 (test-finalizers 1) 1) (deftest finalizers.2 (test-finalizers 1 t) 0) (deftest finalizers.3 (test-finalizers 5) 5) (deftest finalizers.4 (test-finalizers 5 t) 0) (deftest finalizers.5 (test-finalizers 5 :add-again) 5)
4,381
Common Lisp
.lisp
128
29.648438
69
0.659489
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
6739c6b86ced91ad842cd2d9b9fd2746af7aebbf82a1a339c22e3d20cec5a74a
42,554
[ -1 ]
42,555
release.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/trivial-garbage-20211230-git/release.lisp
#!/usr/bin/env clisp ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- (defpackage :release-script (:use #:cl #:regexp)) (in-package :release-script) ;;;; Configuration ------------------------------------------------------------ (defparameter *project-name* "trivial-garbage") (defparameter *asdf-file* (format nil "~A.asd" *project-name*)) (defparameter *host* "common-lisp.net") (defparameter *release-dir* (format nil "/project/~A/public_html/releases" *project-name*)) (defparameter *version-file* "VERSION") (defparameter *version-file-dir* (format nil "/project/~A/public_html" *project-name*)) ;;;; -------------------------------------------------------------------------- ;;;; Utilities (defun ensure-list (x) (if (listp x) x (list x))) (defmacro string-case (expression &body clauses) `(let ((it ,expression)) ; yes, anaphoric, deal with it. (cond ,@(loop for clause in clauses collect `((or ,@(loop for alternative in (ensure-list (first clause)) collect (or (eq t alternative) `(string= it ,alternative)))) ,@(rest clause)))))) (defparameter *development-mode* nil) (defun die (format-control &rest format-args) (format *error-output* "~?" format-control format-args) (if *development-mode* (cerror "continue" "die") (ext:quit 1))) (defun numeric-split (string) (if (digit-char-p (char string 0)) (multiple-value-bind (number next-position) (parse-integer string :junk-allowed t) (cons number (when (< next-position (length string)) (numeric-split (subseq string next-position))))) (let ((next-digit-position (position-if #'digit-char-p string))) (if next-digit-position (cons (subseq string 0 next-digit-position) (numeric-split (subseq string next-digit-position))) (list string))))) (defun natural-string-< (s1 s2) (labels ((aux< (l1 l2) (cond ((null l1) (not (null l2))) ((null l2) nil) (t (destructuring-bind (x . xs) l1 (destructuring-bind (y . ys) l2 (cond ((and (numberp x) (stringp y)) t) ((and (numberp y) (stringp x)) nil) ((and (numberp x) (numberp y)) (or (< x y) (and (= x y) (aux< xs ys)))) (t (or (string-lessp x y) (and (string-equal x y) (aux< xs ys))))))))))) (aux< (numeric-split s1) (numeric-split s2)))) ;;;; Running commands (defparameter *dry-run* nil) (defun cmd? (format-control &rest format-args) (let ((cmd (format nil "~?" format-control format-args))) (with-open-stream (s1 (ext:run-shell-command cmd :output :stream)) (loop for line = (read-line s1 nil nil) while line collect line)))) ;; XXX: quote arguments. (defun cmd (format-control &rest format-args) (when *development-mode* (format *debug-io* "CMD: ~?~%" format-control format-args)) (let ((ret (ext:run-shell-command (format nil "~?" format-control format-args)))) (or (null ret) (zerop ret)))) (defun cmd! (format-control &rest format-args) (or (apply #'cmd format-control format-args) (die "cmd '~?' failed." format-control format-args))) (defun maybe-cmd! (format-control &rest format-args) (if *dry-run* (format t "SUPPRESSING: ~?~%" format-control format-args) (apply #'cmd! format-control format-args))) ;;;; (defun find-current-version () (subseq (reduce (lambda (x y) (if (natural-string-< x y) y x)) (or (cmd? "git tag -l v\\*") (die "no version tags found. Please specify initial version."))) 1)) (defun parse-version (string) (mapcar (lambda (x) (parse-integer x :junk-allowed t)) (loop repeat 3 ; XXX: parameterize for el in (regexp-split "\\." (find-current-version)) collect el))) (defun check-for-unrecorded-changes (&optional force) (unless (cmd "git diff --exit-code") (write-line "Unrecorded changes.") (if force (write-line "Continuing anyway.") (die "Aborting.~@ Use -f or --force if you want to make a release anyway.")))) (defun new-version-number-candidates (current-version) (let ((current-version (parse-version current-version))) (labels ((alternatives (before after) (when after (cons (append before (list (1+ (first after))) (mapcar (constantly 0) (rest after))) (alternatives (append before (list (first after))) (rest after)))))) (loop for alt in (alternatives nil current-version) collect (reduce (lambda (acc next) (format nil "~a.~a" acc next)) alt))))) (defun ask-user-for-version (current-version next-versions) (format *query-io* "Current version is ~A. Which will be the next one?~%" current-version) (loop for i from 1 and version in next-versions do (format *query-io* "~T~A) ~A~%" i version)) (format *query-io* "? ") (finish-output *query-io*) (nth (1- (parse-integer (read-line) :junk-allowed t)) next-versions)) (defun git-tag-tree (version) (write-line "Tagging the tree...") (maybe-cmd! "git tag \"v~A\"" version)) (defun add-version-to-system-file (version path-in path-out) (let ((defsystem-line (format nil "(defsystem ~A" *project-name*))) (with-open-file (in path-in :direction :input) (with-open-file (out path-out :direction :output) (loop for line = (read-line in nil nil) while line do (write-line line out) when (string= defsystem-line line) do (format out " :version ~s~%" version)))))) (defun create-dist (version distname) (write-line "Creating distribution...") (cmd! "mkdir \"~a\"" distname) (cmd! "git archive master | tar xC \"~A\"" distname) (format t "Updating ~A with new version: ~A~%" *asdf-file* version) (let* ((asdf-file-path (format nil "~A/~A" distname *asdf-file*)) (tmp-asdf-file-path (format nil "~a.tmp" asdf-file-path))) (add-version-to-system-file version asdf-file-path tmp-asdf-file-path) (cmd! "mv \"~a\" \"~a\"" tmp-asdf-file-path asdf-file-path))) (defun tar-and-sign (distname tarball) (write-line "Creating and signing tarball...") (cmd! "tar czf \"~a\" \"~a\"" tarball distname) (cmd! "gpg -b -a \"~a\"" tarball)) (defparameter *remote-directory* (format nil "~A:~A" *host* *release-dir*)) (defun upload-tarball (tarball signature remote-directory) (write-line "Copying tarball to web server...") (maybe-cmd! "scp \"~A\" \"~A\" \"~A\"" tarball signature remote-directory) (format t "Uploaded ~A and ~A.~%" tarball signature)) (defun update-remote-links (tarball signature host release-dir project-name) (format t "Updating ~A_latest links...~%" project-name) (maybe-cmd! "ssh \"~A\" ln -sf \"~A\" \"~A/~A_latest.tar.gz\"" host tarball release-dir project-name) (maybe-cmd! "ssh \"~A\" ln -sf \"~A\" \"~A/~A_latest.tar.gz.asc\"" host signature release-dir project-name)) (defun upload-version-file (version version-file host version-file-dir) (format t "Uploading ~A...~%" version-file) (with-open-file (out version-file :direction :output) (write-string version out)) (maybe-cmd! "scp \"~A\" \"~A\":\"~A\"" version-file host version-file-dir) (maybe-cmd! "rm \"~A\"" version-file)) (defun maybe-clean-things-up (tarball signature) (when (y-or-n-p "Clean local tarball and signature?") (cmd! "rm \"~A\" \"~A\"" tarball signature))) (defun run (force version) (check-for-unrecorded-changes force) ;; figure out what version we'll be preparing. (unless version (let* ((current-version (find-current-version)) (next-versions (new-version-number-candidates current-version))) (setf version (or (ask-user-for-version current-version next-versions) (die "invalid selection."))))) (git-tag-tree version) (let* ((distname (format nil "~A_~A" *project-name* version)) (tarball (format nil "~A.tar.gz" distname)) (signature (format nil "~A.asc" tarball))) ;; package things up. (create-dist version distname) (tar-and-sign distname tarball) ;; upload. (upload-tarball tarball signature *remote-directory*) (update-remote-links tarball signature *host* *release-dir* *project-name*) (when *version-file* (upload-version-file version *version-file* *host* *version-file-dir*)) ;; clean up. (maybe-clean-things-up tarball signature) ;; documentation. ;; (write-line "Building and uploading documentation...") ;; (maybe-cmd! "make -C doc upload-docs") ;; push tags and any outstanding changes. (write-line "Pushing tags and changes...") (maybe-cmd! "git push --tags origin master"))) ;;;; Do it to it (let ((force nil) (version nil) (args ext:*args*)) (loop while args do (string-case (pop args) (("-h" "--help") (write-line "No help, sorry. Read the source.") (ext:quit 0)) (("-f" "--force") (setf force t)) (("-v" "--version") (setf version (pop args))) (("-n" "--dry-run") (setf *dry-run* t)) (t (die "Unrecognized argument '~a'" it)))) (run force version))
9,875
Common Lisp
.lisp
212
37.834906
86
0.578078
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
04a80929cf156b24167540519b28e211490ebac922b286bb6a5bfc0c531864fd
42,555
[ 228841 ]
42,556
gendocs.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/trivial-garbage-20211230-git/gendocs.lisp
(in-package :cl-user) (asdf:load-system :atdoc) (asdf:load-system :trivial-garbage) (let* ((base (asdf:component-pathname (asdf:find-system :trivial-garbage))) (output-directory (merge-pathnames "doc/" base)) (css-file (merge-pathnames "doc/index.css" base))) (ensure-directories-exist output-directory) (atdoc:generate-html-documentation '(:trivial-garbage) output-directory :single-page-p t :heading "Trivial Garbage" :index-title "Trivial Garbage" :css css-file))
672
Common Lisp
.lisp
13
34.923077
75
0.537291
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
de8ce40cbd2df992da7071c17b5055d32ab95626203e30322b09f77f309034e6
42,556
[ 87919, 452885 ]
42,557
package.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/alexandria-20220707-git/alexandria-1/package.lisp
(defpackage :alexandria (:nicknames :alexandria.1.0.0 :alexandria-1) (:use :cl) #+sb-package-locks (:lock t) (:export ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; BLESSED ;; ;; Binding constructs #:if-let #:when-let #:when-let* ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; REVIEW IN PROGRESS ;; ;; Control flow ;; ;; -- no clear consensus yet -- #:cswitch #:eswitch #:switch ;; -- problem free? -- #:multiple-value-prog2 #:nth-value-or #:whichever #:xor ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; REVIEW PENDING ;; ;; Definitions #:define-constant ;; Hash tables #:alist-hash-table #:copy-hash-table #:ensure-gethash #:hash-table-alist #:hash-table-keys #:hash-table-plist #:hash-table-values #:maphash-keys #:maphash-values #:plist-hash-table ;; Functions #:compose #:conjoin #:curry #:disjoin #:ensure-function #:ensure-functionf #:multiple-value-compose #:named-lambda #:rcurry ;; Lists #:alist-plist #:appendf #:nconcf #:reversef #:nreversef #:circular-list #:circular-list-p #:circular-tree-p #:doplist #:ensure-car #:ensure-cons #:ensure-list #:flatten #:lastcar #:make-circular-list #:map-product #:mappend #:nunionf #:plist-alist #:proper-list #:proper-list-length #:proper-list-p #:remove-from-plist #:remove-from-plistf #:delete-from-plist #:delete-from-plistf #:set-equal #:setp #:unionf ;; Numbers #:binomial-coefficient #:clamp #:count-permutations #:factorial #:gaussian-random #:iota #:lerp #:map-iota #:maxf #:mean #:median #:minf #:standard-deviation #:subfactorial #:variance ;; Arrays #:array-index #:array-length #:copy-array ;; Sequences #:copy-sequence #:deletef #:emptyp #:ends-with #:ends-with-subseq #:extremum #:first-elt #:last-elt #:length= #:map-combinations #:map-derangements #:map-permutations #:proper-sequence #:random-elt #:removef #:rotate #:sequence-of-length-p #:shuffle #:starts-with #:starts-with-subseq ;; Macros #:once-only #:parse-body #:parse-ordinary-lambda-list #:with-gensyms #:with-unique-names ;; Symbols #:ensure-symbol #:format-symbol #:make-gensym #:make-gensym-list #:make-keyword ;; Strings #:string-designator ;; Types #:negative-double-float #:negative-fixnum-p #:negative-float #:negative-float-p #:negative-long-float #:negative-long-float-p #:negative-rational #:negative-rational-p #:negative-real #:negative-single-float-p #:non-negative-double-float #:non-negative-double-float-p #:non-negative-fixnum #:non-negative-fixnum-p #:non-negative-float #:non-negative-float-p #:non-negative-integer-p #:non-negative-long-float #:non-negative-rational #:non-negative-real-p #:non-negative-short-float-p #:non-negative-single-float #:non-negative-single-float-p #:non-positive-double-float #:non-positive-double-float-p #:non-positive-fixnum #:non-positive-fixnum-p #:non-positive-float #:non-positive-float-p #:non-positive-integer #:non-positive-rational #:non-positive-real #:non-positive-real-p #:non-positive-short-float #:non-positive-short-float-p #:non-positive-single-float-p #:positive-double-float #:positive-double-float-p #:positive-fixnum #:positive-fixnum-p #:positive-float #:positive-float-p #:positive-integer #:positive-rational #:positive-real #:positive-real-p #:positive-short-float #:positive-short-float-p #:positive-single-float #:positive-single-float-p #:coercef #:negative-double-float-p #:negative-fixnum #:negative-integer #:negative-integer-p #:negative-real-p #:negative-short-float #:negative-short-float-p #:negative-single-float #:non-negative-integer #:non-negative-long-float-p #:non-negative-rational-p #:non-negative-real #:non-negative-short-float #:non-positive-integer-p #:non-positive-long-float #:non-positive-long-float-p #:non-positive-rational-p #:non-positive-single-float #:of-type #:positive-integer-p #:positive-long-float #:positive-long-float-p #:positive-rational-p #:type= ;; Conditions #:required-argument #:ignore-some-conditions #:simple-style-warning #:simple-reader-error #:simple-parse-error #:simple-program-error #:unwind-protect-case ;; Features #:featurep ;; io #:with-input-from-file #:with-output-to-file #:read-stream-content-into-string #:read-file-into-string #:write-string-into-file #:read-stream-content-into-byte-vector #:read-file-into-byte-vector #:write-byte-vector-into-file #:copy-stream #:copy-file ;; new additions collected at the end (subject to removal or further changes) #:symbolicate #:assoc-value #:rassoc-value #:destructuring-case #:destructuring-ccase #:destructuring-ecase ))
5,238
Common Lisp
.lisp
243
17.588477
80
0.636036
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
62905e8f78fb57842b7b2c5da48034b060d63adcf38d7e57f349bffbdc8144cf
42,557
[ -1 ]
42,559
io.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/alexandria-20220707-git/alexandria-1/io.lisp
;; Copyright (c) 2002-2006, Edward Marco Baringer ;; All rights reserved. (in-package :alexandria) (defmacro with-open-file* ((stream filespec &key direction element-type if-exists if-does-not-exist external-format) &body body) "Just like WITH-OPEN-FILE, but NIL values in the keyword arguments mean to use the default value specified for OPEN." (once-only (direction element-type if-exists if-does-not-exist external-format) `(with-open-stream (,stream (apply #'open ,filespec (append (when ,direction (list :direction ,direction)) (list :element-type (or ,element-type (default-element-type))) (when ,if-exists (list :if-exists ,if-exists)) (when ,if-does-not-exist (list :if-does-not-exist ,if-does-not-exist)) (when ,external-format (list :external-format ,external-format))))) ,@body))) (defun default-element-type () ;; On Lispworks, ELEMENT-TYPE :DEFAULT selects the appropriate ;; subtype of CHARACTER for the given external format which can ;; represent all possible characters. #+lispworks :default ;; The spec says that OPEN's default ELEMENT-TYPE (when it is not ;; specified) is CHARACTER, but on AllegroCL it's (UNSIGNED-BYTE 8). ;; No harm done by specifying it on other implementations. #-lispworks 'character) (defmacro with-input-from-file ((stream-name file-name &rest args &key (direction nil direction-p) &allow-other-keys) &body body) "Evaluate BODY with STREAM-NAME to an input stream on the file FILE-NAME. ARGS is sent as is to the call to OPEN except EXTERNAL-FORMAT, which is only sent to WITH-OPEN-FILE when it's not NIL." (declare (ignore direction)) (when direction-p (error "Can't specify :DIRECTION for WITH-INPUT-FROM-FILE.")) `(with-open-file* (,stream-name ,file-name :direction :input ,@args) ,@body)) (defmacro with-output-to-file ((stream-name file-name &rest args &key (direction nil direction-p) &allow-other-keys) &body body) "Evaluate BODY with STREAM-NAME to an output stream on the file FILE-NAME. ARGS is sent as is to the call to OPEN except EXTERNAL-FORMAT, which is only sent to WITH-OPEN-FILE when it's not NIL." (declare (ignore direction)) (when direction-p (error "Can't specify :DIRECTION for WITH-OUTPUT-TO-FILE.")) `(with-open-file* (,stream-name ,file-name :direction :output ,@args) ,@body)) (defun read-stream-content-into-string (stream &key (buffer-size 4096)) "Return the \"content\" of STREAM as a fresh string." (check-type buffer-size positive-integer) (let ((*print-pretty* nil) (element-type (stream-element-type stream))) (with-output-to-string (datum nil :element-type element-type) (let ((buffer (make-array buffer-size :element-type element-type))) (loop :for bytes-read = (read-sequence buffer stream) :do (write-sequence buffer datum :start 0 :end bytes-read) :while (= bytes-read buffer-size)))))) (defun read-file-into-string (pathname &key (buffer-size 4096) external-format) "Return the contents of the file denoted by PATHNAME as a fresh string. The EXTERNAL-FORMAT parameter will be passed directly to WITH-OPEN-FILE unless it's NIL, which means the system default." (with-input-from-file (file-stream pathname :external-format external-format) (read-stream-content-into-string file-stream :buffer-size buffer-size))) (defun write-string-into-file (string pathname &key (if-exists :error) if-does-not-exist external-format) "Write STRING to PATHNAME. The EXTERNAL-FORMAT parameter will be passed directly to WITH-OPEN-FILE unless it's NIL, which means the system default." (with-output-to-file (file-stream pathname :if-exists if-exists :if-does-not-exist if-does-not-exist :external-format external-format) (write-sequence string file-stream))) (defun read-stream-content-into-byte-vector (stream &key ((%length length)) (initial-size 4096)) "Return \"content\" of STREAM as freshly allocated (unsigned-byte 8) vector." (check-type length (or null non-negative-integer)) (check-type initial-size positive-integer) (do ((buffer (make-array (or length initial-size) :element-type '(unsigned-byte 8))) (offset 0) (offset-wanted 0)) ((or (/= offset-wanted offset) (and length (>= offset length))) (if (= offset (length buffer)) buffer (subseq buffer 0 offset))) (unless (zerop offset) (let ((new-buffer (make-array (* 2 (length buffer)) :element-type '(unsigned-byte 8)))) (replace new-buffer buffer) (setf buffer new-buffer))) (setf offset-wanted (length buffer) offset (read-sequence buffer stream :start offset)))) (defun read-file-into-byte-vector (pathname) "Read PATHNAME into a freshly allocated (unsigned-byte 8) vector." (with-input-from-file (stream pathname :element-type '(unsigned-byte 8)) (read-stream-content-into-byte-vector stream '%length (file-length stream)))) (defun write-byte-vector-into-file (bytes pathname &key (if-exists :error) if-does-not-exist) "Write BYTES to PATHNAME." (check-type bytes (vector (unsigned-byte 8))) (with-output-to-file (stream pathname :if-exists if-exists :if-does-not-exist if-does-not-exist :element-type '(unsigned-byte 8)) (write-sequence bytes stream))) (defun copy-file (from to &key (if-to-exists :supersede) (element-type '(unsigned-byte 8)) finish-output) (with-input-from-file (input from :element-type element-type) (with-output-to-file (output to :element-type element-type :if-exists if-to-exists) (copy-stream input output :element-type element-type :finish-output finish-output)))) (defun copy-stream (input output &key (element-type (stream-element-type input)) (buffer-size 4096) (buffer (make-array buffer-size :element-type element-type)) (start 0) end finish-output) "Reads data from INPUT and writes it to OUTPUT. Both INPUT and OUTPUT must be streams, they will be passed to READ-SEQUENCE and WRITE-SEQUENCE and must have compatible element-types." (check-type start non-negative-integer) (check-type end (or null non-negative-integer)) (check-type buffer-size positive-integer) (when (and end (< end start)) (error "END is smaller than START in ~S" 'copy-stream)) (let ((output-position 0) (input-position 0)) (unless (zerop start) ;; FIXME add platform specific optimization to skip seekable streams (loop while (< input-position start) do (let ((n (read-sequence buffer input :end (min (length buffer) (- start input-position))))) (when (zerop n) (error "~@<Could not read enough bytes from the input to fulfill ~ the :START ~S requirement in ~S.~:@>" 'copy-stream start)) (incf input-position n)))) (assert (= input-position start)) (loop while (or (null end) (< input-position end)) do (let ((n (read-sequence buffer input :end (when end (min (length buffer) (- end input-position)))))) (when (zerop n) (if end (error "~@<Could not read enough bytes from the input to fulfill ~ the :END ~S requirement in ~S.~:@>" 'copy-stream end) (return))) (incf input-position n) (write-sequence buffer output :end n) (incf output-position n))) (when finish-output (finish-output output)) output-position))
8,840
Common Lisp
.lisp
167
40
87
0.589859
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
1a7e1c813eb5876e743659b1ed6af403b01e1e7577126d12779a4c81ace8f072
42,559
[ -1 ]
42,562
sequences.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/alexandria-20220707-git/alexandria-1/sequences.lisp
(in-package :alexandria) ;; Make these inlinable by declaiming them INLINE here and some of them ;; NOTINLINE at the end of the file. Exclude functions that have a compiler ;; macro, because NOTINLINE is required to prevent compiler-macro expansion. (declaim (inline copy-sequence sequence-of-length-p)) (defun sequence-of-length-p (sequence length) "Return true if SEQUENCE is a sequence of length LENGTH. Signals an error if SEQUENCE is not a sequence. Returns FALSE for circular lists." (declare (type array-index length) #-lispworks (inline length) (optimize speed)) (etypecase sequence (null (zerop length)) (cons (let ((n (1- length))) (unless (minusp n) (let ((tail (nthcdr n sequence))) (and tail (null (cdr tail))))))) (vector (= length (length sequence))) (sequence (= length (length sequence))))) (defun rotate-tail-to-head (sequence n) (declare (type (integer 1) n)) (if (listp sequence) (let ((m (mod n (proper-list-length sequence)))) (if (null (cdr sequence)) sequence (let* ((tail (last sequence (+ m 1))) (last (cdr tail))) (setf (cdr tail) nil) (nconc last sequence)))) (let* ((len (length sequence)) (m (mod n len)) (tail (subseq sequence (- len m)))) (replace sequence sequence :start1 m :start2 0) (replace sequence tail) sequence))) (defun rotate-head-to-tail (sequence n) (declare (type (integer 1) n)) (if (listp sequence) (let ((m (mod (1- n) (proper-list-length sequence)))) (if (null (cdr sequence)) sequence (let* ((headtail (nthcdr m sequence)) (tail (cdr headtail))) (setf (cdr headtail) nil) (nconc tail sequence)))) (let* ((len (length sequence)) (m (mod n len)) (head (subseq sequence 0 m))) (replace sequence sequence :start1 0 :start2 m) (replace sequence head :start1 (- len m)) sequence))) (defun rotate (sequence &optional (n 1)) "Returns a sequence of the same type as SEQUENCE, with the elements of SEQUENCE rotated by N: N elements are moved from the end of the sequence to the front if N is positive, and -N elements moved from the front to the end if N is negative. SEQUENCE must be a proper sequence. N must be an integer, defaulting to 1. If absolute value of N is greater then the length of the sequence, the results are identical to calling ROTATE with (* (signum n) (mod n (length sequence))). Note: the original sequence may be destructively altered, and result sequence may share structure with it." (if (plusp n) (rotate-tail-to-head sequence n) (if (minusp n) (rotate-head-to-tail sequence (- n)) sequence))) (defun shuffle (sequence &key (start 0) end) "Returns a random permutation of SEQUENCE bounded by START and END. Original sequence may be destructively modified. Signals an error if SEQUENCE is not a proper sequence." (declare (type fixnum start) (type (or fixnum null) end)) (etypecase sequence (list (let* ((end (or end (proper-list-length sequence))) (n (- end start)) (sublist (nthcdr start sequence)) (small-enough-threshold 100)) ;; It's fine to use a pure list shuffle if the number of items ;; to shuffle is small enough, but otherwise it's more ;; time-efficient to create an intermediate vector to work on. ;; I picked the threshold based on rudimentary benchmarks on my ;; machine, where both branches take about the same time. (if (< n small-enough-threshold) (do ((tail sublist (cdr tail))) ((zerop n)) (rotatef (car tail) (car (nthcdr (random n) tail))) (decf n)) (let ((intermediate-vector (replace (make-array n) sublist))) (replace sublist (shuffle intermediate-vector)))))) (vector (let ((end (or end (length sequence)))) (loop for i from start below end do (rotatef (aref sequence i) (aref sequence (+ i (random (- end i)))))))) (sequence (let ((end (or end (length sequence)))) (loop for i from (- end 1) downto start do (rotatef (elt sequence i) (elt sequence (+ i (random (- end i))))))))) sequence) (defun random-elt (sequence &key (start 0) end) "Returns a random element from SEQUENCE bounded by START and END. Signals an error if the SEQUENCE is not a proper non-empty sequence, or if END and START are not proper bounding index designators for SEQUENCE." (declare (sequence sequence) (fixnum start) (type (or fixnum null) end)) (let* ((size (if (listp sequence) (proper-list-length sequence) (length sequence))) (end2 (or end size))) (cond ((zerop size) (error 'type-error :datum sequence :expected-type `(and sequence (not (satisfies emptyp))))) ((not (and (<= 0 start) (< start end2) (<= end2 size))) (error 'simple-type-error :datum (cons start end) :expected-type `(cons (integer 0 (,end2)) (or null (integer (,start) ,size))) :format-control "~@<~S and ~S are not valid bounding index designators for ~ a sequence of length ~S.~:@>" :format-arguments (list start end size))) (t (let ((index (+ start (random (- end2 start))))) (elt sequence index)))))) (declaim (inline remove/swapped-arguments)) (defun remove/swapped-arguments (sequence item &rest keyword-arguments) (apply #'remove item sequence keyword-arguments)) (define-modify-macro removef (item &rest keyword-arguments) remove/swapped-arguments "Modify-macro for REMOVE. Sets place designated by the first argument to the result of calling REMOVE with ITEM, place, and the KEYWORD-ARGUMENTS.") (declaim (inline delete/swapped-arguments)) (defun delete/swapped-arguments (sequence item &rest keyword-arguments) (apply #'delete item sequence keyword-arguments)) (define-modify-macro deletef (item &rest keyword-arguments) delete/swapped-arguments "Modify-macro for DELETE. Sets place designated by the first argument to the result of calling DELETE with ITEM, place, and the KEYWORD-ARGUMENTS.") (deftype proper-sequence () "Type designator for proper sequences, that is proper lists and sequences that are not lists." `(or proper-list (and (not list) sequence))) (eval-when (:compile-toplevel :load-toplevel :execute) (when (and (find-package '#:sequence) (find-symbol (string '#:emptyp) '#:sequence)) (pushnew 'sequence-emptyp *features*))) #-alexandria::sequence-emptyp (defun emptyp (sequence) "Returns true if SEQUENCE is an empty sequence. Signals an error if SEQUENCE is not a sequence." (etypecase sequence (list (null sequence)) (sequence (zerop (length sequence))))) #+alexandria::sequence-emptyp (declaim (ftype (function (sequence) (values boolean &optional)) emptyp)) #+alexandria::sequence-emptyp (setf (symbol-function 'emptyp) (symbol-function 'sequence:emptyp)) #+alexandria::sequence-emptyp (define-compiler-macro emptyp (sequence) `(sequence:emptyp ,sequence)) (defun length= (&rest sequences) "Takes any number of sequences or integers in any order. Returns true iff the length of all the sequences and the integers are equal. Hint: there's a compiler macro that expands into more efficient code if the first argument is a literal integer." (declare (dynamic-extent sequences) (inline sequence-of-length-p) (optimize speed)) (unless (cdr sequences) (error "You must call LENGTH= with at least two arguments")) ;; There's room for optimization here: multiple list arguments could be ;; traversed in parallel. (let* ((first (pop sequences)) (current (if (integerp first) first (length first)))) (declare (type array-index current)) (dolist (el sequences) (if (integerp el) (unless (= el current) (return-from length= nil)) (unless (sequence-of-length-p el current) (return-from length= nil))))) t) (define-compiler-macro length= (&whole form length &rest sequences) (cond ((zerop (length sequences)) form) (t (let ((optimizedp (integerp length))) (with-unique-names (tmp current) (declare (ignorable current)) `(locally (declare (inline sequence-of-length-p)) (let ((,tmp) ,@(unless optimizedp `((,current ,length)))) ,@(unless optimizedp `((unless (integerp ,current) (setf ,current (length ,current))))) (and ,@(loop :for sequence :in sequences :collect `(progn (setf ,tmp ,sequence) (if (integerp ,tmp) (= ,tmp ,(if optimizedp length current)) (sequence-of-length-p ,tmp ,(if optimizedp length current))))))))))))) (defun copy-sequence (type sequence) "Returns a fresh sequence of TYPE, which has the same elements as SEQUENCE." (if (typep sequence type) (copy-seq sequence) (coerce sequence type))) (defun first-elt (sequence) "Returns the first element of SEQUENCE. Signals a type-error if SEQUENCE is not a sequence, or is an empty sequence." ;; Can't just directly use ELT, as it is not guaranteed to signal the ;; type-error. (cond ((consp sequence) (car sequence)) ((and (typep sequence 'sequence) (not (emptyp sequence))) (elt sequence 0)) (t (error 'type-error :datum sequence :expected-type '(and sequence (not (satisfies emptyp))))))) (defun (setf first-elt) (object sequence) "Sets the first element of SEQUENCE. Signals a type-error if SEQUENCE is not a sequence, is an empty sequence, or if OBJECT cannot be stored in SEQUENCE." ;; Can't just directly use ELT, as it is not guaranteed to signal the ;; type-error. (cond ((consp sequence) (setf (car sequence) object)) ((and (typep sequence 'sequence) (not (emptyp sequence))) (setf (elt sequence 0) object)) (t (error 'type-error :datum sequence :expected-type '(and sequence (not (satisfies emptyp))))))) (defun last-elt (sequence) "Returns the last element of SEQUENCE. Signals a type-error if SEQUENCE is not a proper sequence, or is an empty sequence." ;; Can't just directly use ELT, as it is not guaranteed to signal the ;; type-error. (let ((len 0)) (cond ((consp sequence) (lastcar sequence)) ((and (typep sequence '(and sequence (not list))) (plusp (setf len (length sequence)))) (elt sequence (1- len))) (t (error 'type-error :datum sequence :expected-type '(and proper-sequence (not (satisfies emptyp)))))))) (defun (setf last-elt) (object sequence) "Sets the last element of SEQUENCE. Signals a type-error if SEQUENCE is not a proper sequence, is an empty sequence, or if OBJECT cannot be stored in SEQUENCE." (let ((len 0)) (cond ((consp sequence) (setf (lastcar sequence) object)) ((and (typep sequence '(and sequence (not list))) (plusp (setf len (length sequence)))) (setf (elt sequence (1- len)) object)) (t (error 'type-error :datum sequence :expected-type '(and proper-sequence (not (satisfies emptyp)))))))) (defun starts-with-subseq (prefix sequence &rest args &key (return-suffix nil return-suffix-supplied-p) &allow-other-keys) "Test whether the first elements of SEQUENCE are the same (as per TEST) as the elements of PREFIX. If RETURN-SUFFIX is T the function returns, as a second value, a sub-sequence or displaced array pointing to the sequence after PREFIX." (declare (dynamic-extent args)) (let ((sequence-length (length sequence)) (prefix-length (length prefix))) (when (< sequence-length prefix-length) (return-from starts-with-subseq (values nil nil))) (flet ((make-suffix (start) (when return-suffix (cond ((not (arrayp sequence)) (if start (subseq sequence start) (subseq sequence 0 0))) ((not start) (make-array 0 :element-type (array-element-type sequence) :adjustable nil)) (t (make-array (- sequence-length start) :element-type (array-element-type sequence) :displaced-to sequence :displaced-index-offset start :adjustable nil)))))) (let ((mismatch (apply #'mismatch prefix sequence (if return-suffix-supplied-p (remove-from-plist args :return-suffix) args)))) (cond ((not mismatch) (values t (make-suffix nil))) ((= mismatch prefix-length) (values t (make-suffix mismatch))) (t (values nil nil))))))) (defun ends-with-subseq (suffix sequence &key (test #'eql)) "Test whether SEQUENCE ends with SUFFIX. In other words: return true if the last (length SUFFIX) elements of SEQUENCE are equal to SUFFIX." (let ((sequence-length (length sequence)) (suffix-length (length suffix))) (when (< sequence-length suffix-length) ;; if SEQUENCE is shorter than SUFFIX, then SEQUENCE can't end with SUFFIX. (return-from ends-with-subseq nil)) (loop for sequence-index from (- sequence-length suffix-length) below sequence-length for suffix-index from 0 below suffix-length when (not (funcall test (elt sequence sequence-index) (elt suffix suffix-index))) do (return-from ends-with-subseq nil) finally (return t)))) (defun starts-with (object sequence &key (test #'eql) (key #'identity)) "Returns true if SEQUENCE is a sequence whose first element is EQL to OBJECT. Returns NIL if the SEQUENCE is not a sequence or is an empty sequence." (let ((first-elt (typecase sequence (cons (car sequence)) (sequence (if (emptyp sequence) (return-from starts-with nil) (elt sequence 0))) (t (return-from starts-with nil))))) (funcall test (funcall key first-elt) object))) (defun ends-with (object sequence &key (test #'eql) (key #'identity)) "Returns true if SEQUENCE is a sequence whose last element is EQL to OBJECT. Returns NIL if the SEQUENCE is not a sequence or is an empty sequence. Signals an error if SEQUENCE is an improper list." (let ((last-elt (typecase sequence (cons (lastcar sequence)) ; signals for improper lists (sequence ;; Can't use last-elt, as that signals an error ;; for empty sequences (let ((len (length sequence))) (if (plusp len) (elt sequence (1- len)) (return-from ends-with nil)))) (t (return-from ends-with nil))))) (funcall test (funcall key last-elt) object))) (defun map-combinations (function sequence &key (start 0) end length (copy t)) "Calls FUNCTION with each combination of LENGTH constructable from the elements of the subsequence of SEQUENCE delimited by START and END. START defaults to 0, END to length of SEQUENCE, and LENGTH to the length of the delimited subsequence. (So unless LENGTH is specified there is only a single combination, which has the same elements as the delimited subsequence.) If COPY is true (the default) each combination is freshly allocated. If COPY is false all combinations are EQ to each other, in which case consequences are unspecified if a combination is modified by FUNCTION." (let* ((end (or end (length sequence))) (size (- end start)) (length (or length size)) (combination (subseq sequence 0 length)) (function (ensure-function function))) (if (= length size) (funcall function combination) (flet ((call () (funcall function (if copy (copy-seq combination) combination)))) (etypecase sequence ;; When dealing with lists we prefer walking back and ;; forth instead of using indexes. (list (labels ((combine-list (c-tail o-tail) (if (not c-tail) (call) (do ((tail o-tail (cdr tail))) ((not tail)) (setf (car c-tail) (car tail)) (combine-list (cdr c-tail) (cdr tail)))))) (combine-list combination (nthcdr start sequence)))) (vector (labels ((combine (count start) (if (zerop count) (call) (loop for i from start below end do (let ((j (- count 1))) (setf (aref combination j) (aref sequence i)) (combine j (+ i 1))))))) (combine length start))) (sequence (labels ((combine (count start) (if (zerop count) (call) (loop for i from start below end do (let ((j (- count 1))) (setf (elt combination j) (elt sequence i)) (combine j (+ i 1))))))) (combine length start))))))) sequence) (defun map-permutations (function sequence &key (start 0) end length (copy t)) "Calls function with each permutation of LENGTH constructable from the subsequence of SEQUENCE delimited by START and END. START defaults to 0, END to length of the sequence, and LENGTH to the length of the delimited subsequence." (let* ((end (or end (length sequence))) (size (- end start)) (length (or length size))) (labels ((permute (seq n) (let ((n-1 (- n 1))) (if (zerop n-1) (funcall function (if copy (copy-seq seq) seq)) (loop for i from 0 upto n-1 do (permute seq n-1) (if (evenp n-1) (rotatef (elt seq 0) (elt seq n-1)) (rotatef (elt seq i) (elt seq n-1))))))) (permute-sequence (seq) (permute seq length))) (if (= length size) ;; Things are simple if we need to just permute the ;; full START-END range. (permute-sequence (subseq sequence start end)) ;; Otherwise we need to generate all the combinations ;; of LENGTH in the START-END range, and then permute ;; a copy of the result: can't permute the combination ;; directly, as they share structure with each other. (let ((permutation (subseq sequence 0 length))) (flet ((permute-combination (combination) (permute-sequence (replace permutation combination)))) (declare (dynamic-extent #'permute-combination)) (map-combinations #'permute-combination sequence :start start :end end :length length :copy nil))))))) (defun map-derangements (function sequence &key (start 0) end (copy t)) "Calls FUNCTION with each derangement of the subsequence of SEQUENCE denoted by the bounding index designators START and END. Derangement is a permutation of the sequence where no element remains in place. SEQUENCE is not modified, but individual derangements are EQ to each other. Consequences are unspecified if calling FUNCTION modifies either the derangement or SEQUENCE." (let* ((end (or end (length sequence))) (size (- end start)) ;; We don't really care about the elements here. (derangement (subseq sequence 0 size)) ;; Bitvector that has 1 for elements that have been deranged. (mask (make-array size :element-type 'bit :initial-element 0))) (declare (dynamic-extent mask)) ;; ad hoc algorith (labels ((derange (place n) ;; Perform one recursive step in deranging the ;; sequence: PLACE is index of the original sequence ;; to derange to another index, and N is the number of ;; indexes not yet deranged. (if (zerop n) (funcall function (if copy (copy-seq derangement) derangement)) ;; Itarate over the indexes I of the subsequence to ;; derange: if I != PLACE and I has not yet been ;; deranged by an earlier call put the element from ;; PLACE to I, mark I as deranged, and recurse, ;; finally removing the mark. (loop for i from 0 below size do (unless (or (= place (+ i start)) (not (zerop (bit mask i)))) (setf (elt derangement i) (elt sequence place) (bit mask i) 1) (derange (1+ place) (1- n)) (setf (bit mask i) 0)))))) (derange start size) sequence))) (declaim (notinline sequence-of-length-p)) (defun extremum (sequence predicate &key key (start 0) end) "Returns the element of SEQUENCE that would appear first if the subsequence bounded by START and END was sorted using PREDICATE and KEY. EXTREMUM determines the relationship between two elements of SEQUENCE by using the PREDICATE function. PREDICATE should return true if and only if the first argument is strictly less than the second one (in some appropriate sense). Two arguments X and Y are considered to be equal if (FUNCALL PREDICATE X Y) and (FUNCALL PREDICATE Y X) are both false. The arguments to the PREDICATE function are computed from elements of SEQUENCE using the KEY function, if supplied. If KEY is not supplied or is NIL, the sequence element itself is used. If SEQUENCE is empty, NIL is returned." (let* ((pred-fun (ensure-function predicate)) (key-fun (unless (or (not key) (eq key 'identity) (eq key #'identity)) (ensure-function key))) (real-end (or end (length sequence)))) (cond ((> real-end start) (if key-fun (flet ((reduce-keys (a b) (if (funcall pred-fun (funcall key-fun a) (funcall key-fun b)) a b))) (declare (dynamic-extent #'reduce-keys)) (reduce #'reduce-keys sequence :start start :end real-end)) (flet ((reduce-elts (a b) (if (funcall pred-fun a b) a b))) (declare (dynamic-extent #'reduce-elts)) (reduce #'reduce-elts sequence :start start :end real-end)))) ((= real-end start) nil) (t (error "Invalid bounding indexes for sequence of length ~S: ~S ~S, ~S ~S" (length sequence) :start start :end end)))))
25,124
Common Lisp
.lisp
526
35.591255
100
0.57443
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
98322e42cdb7bba1c612669c6451862d41de5705cbc843b6e9b4651c4e091493
42,562
[ -1 ]
42,563
tests.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/alexandria-20220707-git/alexandria-1/tests.lisp
(in-package :cl-user) (defpackage :alexandria/tests (:use :cl :alexandria #+sbcl :sb-rt #-sbcl :rtest) (:import-from #+sbcl :sb-rt #-sbcl :rtest #:*compile-tests* #:*expected-failures*)) (in-package :alexandria/tests) (defun run-tests (&key ((:compiled *compile-tests*))) (do-tests)) (defun hash-table-test-name (name) ;; Workaround for Clisp calling EQL in a hash-table FASTHASH-EQL. (hash-table-test (make-hash-table :test name))) ;;;; Arrays (deftest copy-array.1 (let* ((orig (vector 1 2 3)) (copy (copy-array orig))) (values (eq orig copy) (equalp orig copy))) nil t) (deftest copy-array.2 (let ((orig (make-array 1024 :fill-pointer 0 :initial-element nil))) (vector-push-extend 1 orig) (vector-push-extend 2 orig) (vector-push-extend 3 orig) (let ((copy (copy-array orig))) (values (eq orig copy) (equalp orig copy) (array-has-fill-pointer-p copy) (eql (fill-pointer orig) (fill-pointer copy))))) nil t t t) (deftest copy-array.3 (let* ((orig (vector 1 2 3)) (copy (copy-array orig))) (typep copy 'simple-array)) t) (deftest copy-array.4 (let ((orig (make-array 21 :adjustable t :fill-pointer 0))) (dotimes (n 42) (vector-push-extend n orig)) (let ((copy (copy-array orig :adjustable nil :fill-pointer nil))) (typep copy 'simple-array))) t) (deftest array-index.1 (typep 0 'array-index) t) ;;;; Conditions (deftest unwind-protect-case.1 (let (result) (unwind-protect-case () (random 10) (:normal (push :normal result)) (:abort (push :abort result)) (:always (push :always result))) result) (:always :normal)) (deftest unwind-protect-case.2 (let (result) (unwind-protect-case () (random 10) (:always (push :always result)) (:normal (push :normal result)) (:abort (push :abort result))) result) (:normal :always)) (deftest unwind-protect-case.3 (let (result1 result2 result3) (ignore-errors (unwind-protect-case () (error "FOOF!") (:normal (push :normal result1)) (:abort (push :abort result1)) (:always (push :always result1)))) (catch 'foof (unwind-protect-case () (throw 'foof 42) (:normal (push :normal result2)) (:abort (push :abort result2)) (:always (push :always result2)))) (block foof (unwind-protect-case () (return-from foof 42) (:normal (push :normal result3)) (:abort (push :abort result3)) (:always (push :always result3)))) (values result1 result2 result3)) (:always :abort) (:always :abort) (:always :abort)) (deftest unwind-protect-case.4 (let (result) (unwind-protect-case (aborted-p) (random 42) (:always (setq result aborted-p))) result) nil) (deftest unwind-protect-case.5 (let (result) (block foof (unwind-protect-case (aborted-p) (return-from foof) (:always (setq result aborted-p)))) result) t) ;;;; Control flow (deftest switch.1 (switch (13 :test =) (12 :oops) (13.0 :yay)) :yay) (deftest switch.2 (switch (13) ((+ 12 2) :oops) ((- 13 1) :oops2) (t :yay)) :yay) (deftest eswitch.1 (let ((x 13)) (eswitch (x :test =) (12 :oops) (13.0 :yay))) :yay) (deftest eswitch.2 (let ((x 13)) (eswitch (x :key 1+) (11 :oops) (14 :yay))) :yay) (deftest cswitch.1 (cswitch (13 :test =) (12 :oops) (13.0 :yay)) :yay) (deftest cswitch.2 (cswitch (13 :key 1-) (12 :yay) (13.0 :oops)) :yay) (deftest multiple-value-prog2.1 (multiple-value-prog2 (values 1 1 1) (values 2 20 200) (values 3 3 3)) 2 20 200) (deftest nth-value-or.1 (multiple-value-bind (a b c) (nth-value-or 1 (values 1 nil 1) (values 2 2 2)) (= a b c 2)) t) (deftest whichever.1 (let ((x (whichever 1 2 3))) (and (member x '(1 2 3)) t)) t) (deftest whichever.2 (let* ((a 1) (b 2) (c 3) (x (whichever a b c))) (and (member x '(1 2 3)) t)) t) ;; https://gitlab.common-lisp.net/alexandria/alexandria/issues/13 (deftest whichever.3 (multiple-value-bind (code warnings?) (compile nil `(lambda (x) (whichever (1+ x)))) (and (not warnings?) (= 6 (funcall code 5)))) t) (deftest xor.1 (xor nil nil 1 nil) 1 t) (deftest xor.2 (xor nil nil 1 2) nil nil) (deftest xor.3 (xor nil nil nil) nil t) ;;;; Definitions (deftest define-constant.1 (let ((name (gensym))) (eval `(define-constant ,name "FOO" :test 'equal)) (eval `(define-constant ,name "FOO" :test 'equal)) (values (equal "FOO" (symbol-value name)) (constantp name))) t t) (deftest define-constant.2 (let ((name (gensym))) (eval `(define-constant ,name 13)) (eval `(define-constant ,name 13)) (values (eql 13 (symbol-value name)) (constantp name))) t t) ;;;; Errors ;;; TYPEP is specified to return a generalized boolean and, for ;;; example, ECL exploits this by returning the superclasses of ERROR ;;; in this case. (defun errorp (x) (not (null (typep x 'error)))) (deftest required-argument.1 (multiple-value-bind (res err) (ignore-errors (required-argument)) (errorp err)) t) ;;;; Hash tables (deftest ensure-gethash.1 (let ((table (make-hash-table)) (x (list 1))) (multiple-value-bind (value already-there) (ensure-gethash x table 42) (and (= value 42) (not already-there) (= 42 (gethash x table)) (multiple-value-bind (value2 already-there2) (ensure-gethash x table 13) (and (= value2 42) already-there2 (= 42 (gethash x table))))))) t) (deftest ensure-gethash.2 (let ((table (make-hash-table)) (count 0)) (multiple-value-call #'values (ensure-gethash (progn (incf count) :foo) (progn (incf count) table) (progn (incf count) :bar)) (gethash :foo table) count)) :bar nil :bar t 3) (deftest copy-hash-table.1 (let ((orig (make-hash-table :test 'eq :size 123)) (foo "foo")) (setf (gethash orig orig) t (gethash foo orig) t) (let ((eq-copy (copy-hash-table orig)) (eql-copy (copy-hash-table orig :test 'eql)) (equal-copy (copy-hash-table orig :test 'equal)) (equalp-copy (copy-hash-table orig :test 'equalp))) (list (eql (hash-table-size eq-copy) (hash-table-size orig)) (eql (hash-table-rehash-size eq-copy) (hash-table-rehash-size orig)) (hash-table-count eql-copy) (gethash orig eq-copy) (gethash (copy-seq foo) eql-copy) (gethash foo eql-copy) (gethash (copy-seq foo) equal-copy) (gethash "FOO" equal-copy) (gethash "FOO" equalp-copy)))) (t t 2 t nil t t nil t)) (deftest copy-hash-table.2 (let ((ht (make-hash-table)) (list (list :list (vector :A :B :C)))) (setf (gethash 'list ht) list) (let* ((shallow-copy (copy-hash-table ht)) (deep1-copy (copy-hash-table ht :key 'copy-list)) (list (gethash 'list ht)) (shallow-list (gethash 'list shallow-copy)) (deep1-list (gethash 'list deep1-copy))) (list (eq ht shallow-copy) (eq ht deep1-copy) (eq list shallow-list) (eq list deep1-list) ; outer list was copied. (eq (second list) (second shallow-list)) (eq (second list) (second deep1-list)) ; inner vector wasn't copied. ))) (nil nil t nil t t)) (deftest maphash-keys.1 (let ((keys nil) (table (make-hash-table))) (declare (notinline maphash-keys)) (dotimes (i 10) (setf (gethash i table) t)) (maphash-keys (lambda (k) (push k keys)) table) (set-equal keys '(0 1 2 3 4 5 6 7 8 9))) t) (deftest maphash-values.1 (let ((vals nil) (table (make-hash-table))) (declare (notinline maphash-values)) (dotimes (i 10) (setf (gethash i table) (- i))) (maphash-values (lambda (v) (push v vals)) table) (set-equal vals '(0 -1 -2 -3 -4 -5 -6 -7 -8 -9))) t) (deftest hash-table-keys.1 (let ((table (make-hash-table))) (dotimes (i 10) (setf (gethash i table) t)) (set-equal (hash-table-keys table) '(0 1 2 3 4 5 6 7 8 9))) t) (deftest hash-table-values.1 (let ((table (make-hash-table))) (dotimes (i 10) (setf (gethash (gensym) table) i)) (set-equal (hash-table-values table) '(0 1 2 3 4 5 6 7 8 9))) t) (deftest hash-table-alist.1 (let ((table (make-hash-table))) (dotimes (i 10) (setf (gethash i table) (- i))) (let ((alist (hash-table-alist table))) (list (length alist) (assoc 0 alist) (assoc 3 alist) (assoc 9 alist) (assoc nil alist)))) (10 (0 . 0) (3 . -3) (9 . -9) nil)) (deftest hash-table-plist.1 (let ((table (make-hash-table))) (dotimes (i 10) (setf (gethash i table) (- i))) (let ((plist (hash-table-plist table))) (list (length plist) (getf plist 0) (getf plist 2) (getf plist 7) (getf plist nil)))) (20 0 -2 -7 nil)) (deftest alist-hash-table.1 (let* ((alist '((0 a) (1 b) (2 c))) (table (alist-hash-table alist))) (list (hash-table-count table) (gethash 0 table) (gethash 1 table) (gethash 2 table) (eq (hash-table-test-name 'eql) (hash-table-test table)))) (3 (a) (b) (c) t)) (deftest alist-hash-table.duplicate-keys (let* ((alist '((0 a) (1 b) (0 c) (1 d) (2 e))) (table (alist-hash-table alist))) (list (hash-table-count table) (gethash 0 table) (gethash 1 table) (gethash 2 table))) (3 (a) (b) (e))) (deftest plist-hash-table.1 (let* ((plist '(:a 1 :b 2 :c 3)) (table (plist-hash-table plist :test 'eq))) (list (hash-table-count table) (gethash :a table) (gethash :b table) (gethash :c table) (gethash 2 table) (gethash nil table) (eq (hash-table-test-name 'eq) (hash-table-test table)))) (3 1 2 3 nil nil t)) (deftest plist-hash-table.duplicate-keys (let* ((plist '(:a 1 :b 2 :a 3 :b 4 :c 5)) (table (plist-hash-table plist))) (list (hash-table-count table) (gethash :a table) (gethash :b table) (gethash :c table))) (3 1 2 5)) ;;;; Functions (deftest disjoin.1 (let ((disjunction (disjoin (lambda (x) (and (consp x) :cons)) (lambda (x) (and (stringp x) :string))))) (list (funcall disjunction 'zot) (funcall disjunction '(foo bar)) (funcall disjunction "test"))) (nil :cons :string)) (deftest disjoin.2 (let ((disjunction (disjoin #'zerop))) (list (funcall disjunction 0) (funcall disjunction 1))) (t nil)) (deftest conjoin.1 (let ((conjunction (conjoin #'consp (lambda (x) (stringp (car x))) (lambda (x) (char (car x) 0))))) (list (funcall conjunction 'zot) (funcall conjunction '(foo)) (funcall conjunction '("foo")))) (nil nil #\f)) (deftest conjoin.2 (let ((conjunction (conjoin #'zerop))) (list (funcall conjunction 0) (funcall conjunction 1))) (t nil)) (deftest compose.1 (let ((composite (compose '1+ (lambda (x) (* x 2)) #'read-from-string))) (funcall composite "1")) 3) (deftest compose.2 (let ((composite (locally (declare (notinline compose)) (compose '1+ (lambda (x) (* x 2)) #'read-from-string)))) (funcall composite "2")) 5) (deftest compose.3 (let ((compose-form (funcall (compiler-macro-function 'compose) '(compose '1+ (lambda (x) (* x 2)) #'read-from-string) nil))) (let ((fun (funcall (compile nil `(lambda () ,compose-form))))) (funcall fun "3"))) 7) (deftest compose.4 (let ((composite (compose #'zerop))) (list (funcall composite 0) (funcall composite 1))) (t nil)) (deftest multiple-value-compose.1 (let ((composite (multiple-value-compose #'truncate (lambda (x y) (values y x)) (lambda (x) (with-input-from-string (s x) (values (read s) (read s))))))) (multiple-value-list (funcall composite "2 7"))) (3 1)) (deftest multiple-value-compose.2 (let ((composite (locally (declare (notinline multiple-value-compose)) (multiple-value-compose #'truncate (lambda (x y) (values y x)) (lambda (x) (with-input-from-string (s x) (values (read s) (read s)))))))) (multiple-value-list (funcall composite "2 11"))) (5 1)) (deftest multiple-value-compose.3 (let ((compose-form (funcall (compiler-macro-function 'multiple-value-compose) '(multiple-value-compose #'truncate (lambda (x y) (values y x)) (lambda (x) (with-input-from-string (s x) (values (read s) (read s))))) nil))) (let ((fun (funcall (compile nil `(lambda () ,compose-form))))) (multiple-value-list (funcall fun "2 9")))) (4 1)) (deftest multiple-value-compose.4 (let ((composite (multiple-value-compose #'truncate))) (multiple-value-list (funcall composite 9 2))) (4 1)) (deftest curry.1 (let ((curried (curry '+ 3))) (funcall curried 1 5)) 9) (deftest curry.2 (let ((curried (locally (declare (notinline curry)) (curry '* 2 3)))) (funcall curried 7)) 42) (deftest curry.3 (let ((curried-form (funcall (compiler-macro-function 'curry) '(curry '/ 8) nil))) (let ((fun (funcall (compile nil `(lambda () ,curried-form))))) (funcall fun 2))) 4) (deftest curry.4 (let* ((x 1) (curried (curry (progn (incf x) (lambda (y z) (* x y z))) 3))) (list (funcall curried 7) (funcall curried 7) x)) (42 42 2)) (deftest rcurry.1 (let ((r (rcurry '/ 2))) (funcall r 8)) 4) (deftest rcurry.2 (let* ((x 1) (curried (rcurry (progn (incf x) (lambda (y z) (* x y z))) 3))) (list (funcall curried 7) (funcall curried 7) x)) (42 42 2)) (deftest named-lambda.1 (let ((fac (named-lambda fac (x) (if (> x 1) (* x (fac (- x 1))) x)))) (funcall fac 5)) 120) (deftest named-lambda.2 (let ((fac (named-lambda fac (&key x) (if (> x 1) (* x (fac :x (- x 1))) x)))) (funcall fac :x 5)) 120) ;;;; Lists (deftest alist-plist.1 (alist-plist '((a . 1) (b . 2) (c . 3))) (a 1 b 2 c 3)) (deftest plist-alist.1 (plist-alist '(a 1 b 2 c 3)) ((a . 1) (b . 2) (c . 3))) (deftest unionf.1 (let* ((list (list 1 2 3)) (orig list)) (unionf list (list 1 2 4)) (values (equal orig (list 1 2 3)) (eql (length list) 4) (set-difference list (list 1 2 3 4)) (set-difference (list 1 2 3 4) list))) t t nil nil) (deftest nunionf.1 (let ((list (list 1 2 3))) (nunionf list (list 1 2 4)) (values (eql (length list) 4) (set-difference (list 1 2 3 4) list) (set-difference list (list 1 2 3 4)))) t nil nil) (deftest appendf.1 (let* ((list (list 1 2 3)) (orig list)) (appendf list '(4 5 6) '(7 8)) (list list (eq list orig))) ((1 2 3 4 5 6 7 8) nil)) (deftest nconcf.1 (let ((list1 (list 1 2 3)) (list2 (list 4 5 6))) (nconcf list1 list2 (list 7 8 9)) list1) (1 2 3 4 5 6 7 8 9)) (deftest circular-list.1 (let ((circle (circular-list 1 2 3))) (list (first circle) (second circle) (third circle) (fourth circle) (eq circle (nthcdr 3 circle)))) (1 2 3 1 t)) (deftest circular-list-p.1 (let* ((circle (circular-list 1 2 3 4)) (tree (list circle circle)) (dotted (cons circle t)) (proper (list 1 2 3 circle)) (tailcirc (list* 1 2 3 circle))) (list (circular-list-p circle) (circular-list-p tree) (circular-list-p dotted) (circular-list-p proper) (circular-list-p tailcirc))) (t nil nil nil t)) (deftest circular-list-p.2 (circular-list-p 'foo) nil) (deftest circular-tree-p.1 (let* ((circle (circular-list 1 2 3 4)) (tree1 (list circle circle)) (tree2 (let* ((level2 (list 1 nil 2)) (level1 (list level2))) (setf (second level2) level1) level1)) (dotted (cons circle t)) (proper (list 1 2 3 circle)) (tailcirc (list* 1 2 3 circle)) (quite-proper (list 1 2 3)) (quite-dotted (list 1 (cons 2 3)))) (list (circular-tree-p circle) (circular-tree-p tree1) (circular-tree-p tree2) (circular-tree-p dotted) (circular-tree-p proper) (circular-tree-p tailcirc) (circular-tree-p quite-proper) (circular-tree-p quite-dotted))) (t t t t t t nil nil)) (deftest circular-tree-p.2 (alexandria:circular-tree-p '#1=(#1#)) t) (deftest proper-list-p.1 (let ((l1 (list 1)) (l2 (list 1 2)) (l3 (cons 1 2)) (l4 (list (cons 1 2) 3)) (l5 (circular-list 1 2))) (list (proper-list-p l1) (proper-list-p l2) (proper-list-p l3) (proper-list-p l4) (proper-list-p l5))) (t t nil t nil)) (deftest proper-list-p.2 (proper-list-p '(1 2 . 3)) nil) (deftest proper-list.type.1 (let ((l1 (list 1)) (l2 (list 1 2)) (l3 (cons 1 2)) (l4 (list (cons 1 2) 3)) (l5 (circular-list 1 2))) (list (typep l1 'proper-list) (typep l2 'proper-list) (typep l3 'proper-list) (typep l4 'proper-list) (typep l5 'proper-list))) (t t nil t nil)) (deftest proper-list-length.1 (values (proper-list-length nil) (proper-list-length (list 1)) (proper-list-length (list 2 2)) (proper-list-length (list 3 3 3)) (proper-list-length (list 4 4 4 4)) (proper-list-length (list 5 5 5 5 5)) (proper-list-length (list 6 6 6 6 6 6)) (proper-list-length (list 7 7 7 7 7 7 7)) (proper-list-length (list 8 8 8 8 8 8 8 8)) (proper-list-length (list 9 9 9 9 9 9 9 9 9))) 0 1 2 3 4 5 6 7 8 9) (deftest proper-list-length.2 (flet ((plength (x) (handler-case (proper-list-length x) (type-error () :ok)))) (values (plength (list* 1)) (plength (list* 2 2)) (plength (list* 3 3 3)) (plength (list* 4 4 4 4)) (plength (list* 5 5 5 5 5)) (plength (list* 6 6 6 6 6 6)) (plength (list* 7 7 7 7 7 7 7)) (plength (list* 8 8 8 8 8 8 8 8)) (plength (list* 9 9 9 9 9 9 9 9 9)))) :ok :ok :ok :ok :ok :ok :ok :ok :ok) (deftest lastcar.1 (let ((l1 (list 1)) (l2 (list 1 2))) (list (lastcar l1) (lastcar l2))) (1 2)) (deftest lastcar.error.2 (handler-case (progn (lastcar (circular-list 1 2 3)) nil) (error () t)) t) (deftest setf-lastcar.1 (let ((l (list 1 2 3 4))) (values (lastcar l) (progn (setf (lastcar l) 42) (lastcar l)))) 4 42) (deftest setf-lastcar.2 (let ((l (circular-list 1 2 3))) (multiple-value-bind (res err) (ignore-errors (setf (lastcar l) 4)) (typep err 'type-error))) t) (deftest make-circular-list.1 (let ((l (make-circular-list 3 :initial-element :x))) (setf (car l) :y) (list (eq l (nthcdr 3 l)) (first l) (second l) (third l) (fourth l))) (t :y :x :x :y)) (deftest circular-list.type.1 (let* ((l1 (list 1 2 3)) (l2 (circular-list 1 2 3)) (l3 (list* 1 2 3 l2))) (list (typep l1 'circular-list) (typep l2 'circular-list) (typep l3 'circular-list))) (nil t t)) (deftest ensure-list.1 (let ((x (list 1)) (y 2)) (list (ensure-list x) (ensure-list y))) ((1) (2))) (deftest ensure-cons.1 (let ((x (cons 1 2)) (y nil) (z "foo")) (values (ensure-cons x) (ensure-cons y) (ensure-cons z))) (1 . 2) (nil) ("foo")) (deftest setp.1 (setp '(1)) t) (deftest setp.2 (setp nil) t) (deftest setp.3 (setp "foo") nil) (deftest setp.4 (setp '(1 2 3 1)) nil) (deftest setp.5 (setp '(1 2 3)) t) (deftest setp.6 (setp '(a :a)) t) (deftest setp.7 (setp '(a :a) :key 'character) nil) (deftest setp.8 (setp '(a :a) :key 'character :test (constantly nil)) t) (deftest set-equal.1 (set-equal '(1 2 3) '(3 1 2)) t) (deftest set-equal.2 (set-equal '("Xa") '("Xb") :test (lambda (a b) (eql (char a 0) (char b 0)))) t) (deftest set-equal.3 (set-equal '(1 2) '(4 2)) nil) (deftest set-equal.4 (set-equal '(a b c) '(:a :b :c) :key 'string :test 'equal) t) (deftest set-equal.5 (set-equal '(a d c) '(:a :b :c) :key 'string :test 'equal) nil) (deftest set-equal.6 (set-equal '(a b c) '(a b c d)) nil) (deftest map-product.1 (map-product 'cons '(2 3) '(1 4)) ((2 . 1) (2 . 4) (3 . 1) (3 . 4))) (deftest map-product.2 (map-product #'cons '(2 3) '(1 4)) ((2 . 1) (2 . 4) (3 . 1) (3 . 4))) (deftest flatten.1 (flatten '((1) 2 (((3 4))) ((((5)) 6)) 7)) (1 2 3 4 5 6 7)) (deftest remove-from-plist.1 (let ((orig '(a 1 b 2 c 3 d 4))) (list (remove-from-plist orig 'a 'c) (remove-from-plist orig 'b 'd) (remove-from-plist orig 'b) (remove-from-plist orig 'a) (remove-from-plist orig 'd 42 "zot") (remove-from-plist orig 'a 'b 'c 'd) (remove-from-plist orig 'a 'b 'c 'd 'x) (equal orig '(a 1 b 2 c 3 d 4)))) ((b 2 d 4) (a 1 c 3) (a 1 c 3 d 4) (b 2 c 3 d 4) (a 1 b 2 c 3) nil nil t)) (deftest delete-from-plist.1 (let ((orig '(a 1 b 2 c 3 d 4 d 5))) (list (delete-from-plist (copy-list orig) 'a 'c) (delete-from-plist (copy-list orig) 'b 'd) (delete-from-plist (copy-list orig) 'b) (delete-from-plist (copy-list orig) 'a) (delete-from-plist (copy-list orig) 'd 42 "zot") (delete-from-plist (copy-list orig) 'a 'b 'c 'd) (delete-from-plist (copy-list orig) 'a 'b 'c 'd 'x) (equal orig (delete-from-plist orig)) (eq orig (delete-from-plist orig)))) ((b 2 d 4 d 5) (a 1 c 3) (a 1 c 3 d 4 d 5) (b 2 c 3 d 4 d 5) (a 1 b 2 c 3) nil nil t t)) (deftest mappend.1 (mappend (compose 'list '*) '(1 2 3) '(1 2 3)) (1 4 9)) (deftest assoc-value.1 (let ((key1 '(complex key)) (key2 'simple-key) (alist '()) (result '())) (push 1 (assoc-value alist key1 :test #'equal)) (push 2 (assoc-value alist key1 :test 'equal)) (push 42 (assoc-value alist key2)) (push 43 (assoc-value alist key2 :test 'eq)) (push (assoc-value alist key1 :test #'equal) result) (push (assoc-value alist key2) result) (push 'very (rassoc-value alist (list 2 1) :test #'equal)) (push (cdr (assoc '(very complex key) alist :test #'equal)) result) result) ((2 1) (43 42) (2 1))) ;;;; Numbers (deftest clamp.1 (list (clamp 1.5 1 2) (clamp 2.0 1 2) (clamp 1.0 1 2) (clamp 3 1 2) (clamp 0 1 2)) (1.5 2.0 1.0 2 1)) (deftest gaussian-random.1 (let ((min -0.2) (max +0.2)) (multiple-value-bind (g1 g2) (gaussian-random min max) (values (<= min g1 max) (<= min g2 max) (/= g1 g2) ;uh ))) t t t) #+sbcl (deftest gaussian-random.2 (handler-case (sb-ext:with-timeout 2 (progn (loop :repeat 10000 :do (gaussian-random 0 nil)) 'done)) (sb-ext:timeout () 'timed-out)) done) (deftest iota.1 (iota 3) (0 1 2)) (deftest iota.2 (iota 3 :start 0.0d0) (0.0d0 1.0d0 2.0d0)) (deftest iota.3 (iota 3 :start 2 :step 3.0) (2.0 5.0 8.0)) (deftest map-iota.1 (let (all) (declare (notinline map-iota)) (values (map-iota (lambda (x) (push x all)) 3 :start 2 :step 1.1d0) all)) 3 (4.2d0 3.1d0 2.0d0)) (deftest lerp.1 (lerp 0.5 1 2) 1.5) (deftest lerp.2 (lerp 0.1 1 2) 1.1) (deftest lerp.3 (lerp 0.1 4 25) 6.1) (deftest mean.1 (mean '(1 2 3)) 2) (deftest mean.2 (mean '(1 2 3 4)) 5/2) (deftest mean.3 (mean '(1 2 10)) 13/3) (deftest median.1 (median '(100 0 99 1 98 2 97)) 97) (deftest median.2 (median '(100 0 99 1 98 2 97 96)) 193/2) (deftest variance.1 (variance (list 1 2 3)) 2/3) (deftest standard-deviation.1 (< 0 (standard-deviation (list 1 2 3)) 1) t) (deftest maxf.1 (let ((x 1)) (maxf x 2) x) 2) (deftest maxf.2 (let ((x 1)) (maxf x 0) x) 1) (deftest maxf.3 (let ((x 1) (c 0)) (maxf x (incf c)) (list x c)) (1 1)) (deftest maxf.4 (let ((xv (vector 0 0 0)) (p 0)) (maxf (svref xv (incf p)) (incf p)) (list p xv)) (2 #(0 2 0))) (deftest minf.1 (let ((y 1)) (minf y 0) y) 0) (deftest minf.2 (let ((xv (vector 10 10 10)) (p 0)) (minf (svref xv (incf p)) (incf p)) (list p xv)) (2 #(10 2 10))) (deftest subfactorial.1 (mapcar #'subfactorial (iota 22)) (1 0 1 2 9 44 265 1854 14833 133496 1334961 14684570 176214841 2290792932 32071101049 481066515734 7697064251745 130850092279664 2355301661033953 44750731559645106 895014631192902121 18795307255050944540)) ;;;; Arrays #+nil (deftest array-index.type) #+nil (deftest copy-array) ;;;; Sequences (deftest rotate.1 (list (rotate (list 1 2 3) 0) (rotate (list 1 2 3) 1) (rotate (list 1 2 3) 2) (rotate (list 1 2 3) 3) (rotate (list 1 2 3) 4)) ((1 2 3) (3 1 2) (2 3 1) (1 2 3) (3 1 2))) (deftest rotate.2 (list (rotate (vector 1 2 3 4) 0) (rotate (vector 1 2 3 4)) (rotate (vector 1 2 3 4) 2) (rotate (vector 1 2 3 4) 3) (rotate (vector 1 2 3 4) 4) (rotate (vector 1 2 3 4) 5)) (#(1 2 3 4) #(4 1 2 3) #(3 4 1 2) #(2 3 4 1) #(1 2 3 4) #(4 1 2 3))) (deftest rotate.3 (list (rotate (list 1 2 3) 0) (rotate (list 1 2 3) -1) (rotate (list 1 2 3) -2) (rotate (list 1 2 3) -3) (rotate (list 1 2 3) -4)) ((1 2 3) (2 3 1) (3 1 2) (1 2 3) (2 3 1))) (deftest rotate.4 (list (rotate (vector 1 2 3 4) 0) (rotate (vector 1 2 3 4) -1) (rotate (vector 1 2 3 4) -2) (rotate (vector 1 2 3 4) -3) (rotate (vector 1 2 3 4) -4) (rotate (vector 1 2 3 4) -5)) (#(1 2 3 4) #(2 3 4 1) #(3 4 1 2) #(4 1 2 3) #(1 2 3 4) #(2 3 4 1))) (deftest rotate.5 (values (rotate (list 1) 17) (rotate (list 1) -5)) (1) (1)) (deftest shuffle.1 (let ((s (shuffle (iota 100)))) (list (equal s (iota 100)) (every (lambda (x) (member x s)) (iota 100)) (every (lambda (x) (typep x '(integer 0 99))) s))) (nil t t)) (deftest shuffle.2 (let ((s (shuffle (coerce (iota 100) 'vector)))) (list (equal s (coerce (iota 100) 'vector)) (every (lambda (x) (find x s)) (iota 100)) (every (lambda (x) (typep x '(integer 0 99))) s))) (nil t t)) (deftest shuffle.3 (let* ((orig (coerce (iota 21) 'vector)) (copy (copy-seq orig))) (shuffle copy :start 10 :end 15) (list (every #'eql (subseq copy 0 10) (subseq orig 0 10)) (every #'eql (subseq copy 15) (subseq orig 15)))) (t t)) (deftest random-elt.1 (let ((s1 #(1 2 3 4)) (s2 '(1 2 3 4))) (list (dotimes (i 1000 nil) (unless (member (random-elt s1) s2) (return nil)) (when (/= (random-elt s1) (random-elt s1)) (return t))) (dotimes (i 1000 nil) (unless (member (random-elt s2) s2) (return nil)) (when (/= (random-elt s2) (random-elt s2)) (return t))))) (t t)) (deftest removef.1 (let* ((x '(1 2 3)) (x* x) (y #(1 2 3)) (y* y)) (removef x 1) (removef y 3) (list x x* y y*)) ((2 3) (1 2 3) #(1 2) #(1 2 3))) (deftest deletef.1 (let* ((x (list 1 2 3)) (x* x) (y (vector 1 2 3))) (deletef x 2) (deletef y 1) (list x x* y)) ((1 3) (1 3) #(2 3))) (deftest map-permutations.1 (let ((seq (list 1 2 3)) (seen nil) (ok t)) (map-permutations (lambda (s) (unless (set-equal s seq) (setf ok nil)) (when (member s seen :test 'equal) (setf ok nil)) (push s seen)) seq :copy t) (values ok (length seen))) t 6) (deftest proper-sequence.type.1 (mapcar (lambda (x) (typep x 'proper-sequence)) (list (list 1 2 3) (vector 1 2 3) #2a((1 2) (3 4)) (circular-list 1 2 3 4))) (t t nil nil)) (deftest emptyp.1 (mapcar #'emptyp (list (list 1) (circular-list 1) nil (vector) (vector 1))) (nil nil t t nil)) (deftest sequence-of-length-p.1 (mapcar #'sequence-of-length-p (list nil #() (list 1) (vector 1) (list 1 2) (vector 1 2) (list 1 2) (vector 1 2) (list 1 2) (vector 1 2)) (list 0 0 1 1 2 2 1 1 4 4)) (t t t t t t nil nil nil nil)) (deftest length=.1 (mapcar #'length= (list nil #() (list 1) (vector 1) (list 1 2) (vector 1 2) (list 1 2) (vector 1 2) (list 1 2) (vector 1 2)) (list 0 0 1 1 2 2 1 1 4 4)) (t t t t t t nil nil nil nil)) (deftest length=.2 ;; test the compiler macro (macrolet ((x (&rest args) (funcall (compile nil `(lambda () (length= ,@args)))))) (list (x 2 '(1 2)) (x '(1 2) '(3 4)) (x '(1 2) 2) (x '(1 2) 2 '(3 4)) (x 1 2 3))) (t t t t nil)) (deftest copy-sequence.1 (let ((l (list 1 2 3)) (v (vector #\a #\b #\c))) (declare (notinline copy-sequence)) (let ((l.list (copy-sequence 'list l)) (l.vector (copy-sequence 'vector l)) (l.spec-v (copy-sequence '(vector fixnum) l)) (v.vector (copy-sequence 'vector v)) (v.list (copy-sequence 'list v)) (v.string (copy-sequence 'string v))) (list (member l (list l.list l.vector l.spec-v)) (member v (list v.vector v.list v.string)) (equal l.list l) (equalp l.vector #(1 2 3)) (type= (upgraded-array-element-type 'fixnum) (array-element-type l.spec-v)) (equalp v.vector v) (equal v.list '(#\a #\b #\c)) (equal "abc" v.string)))) (nil nil t t t t t t)) (deftest first-elt.1 (mapcar #'first-elt (list (list 1 2 3) "abc" (vector :a :b :c))) (1 #\a :a)) (deftest first-elt.error.1 (mapcar (lambda (x) (handler-case (first-elt x) (type-error () :type-error))) (list nil #() 12 :zot)) (:type-error :type-error :type-error :type-error)) (deftest setf-first-elt.1 (let ((l (list 1 2 3)) (s (copy-seq "foobar")) (v (vector :a :b :c))) (setf (first-elt l) -1 (first-elt s) #\x (first-elt v) 'zot) (values l s v)) (-1 2 3) "xoobar" #(zot :b :c)) (deftest setf-first-elt.error.1 (let ((l 'foo)) (multiple-value-bind (res err) (ignore-errors (setf (first-elt l) 4)) (typep err 'type-error))) t) (deftest last-elt.1 (mapcar #'last-elt (list (list 1 2 3) (vector :a :b :c) "FOOBAR" #*001 #*010)) (3 :c #\R 1 0)) (deftest last-elt.error.1 (mapcar (lambda (x) (handler-case (last-elt x) (type-error () :type-error))) (list nil #() 12 :zot (circular-list 1 2 3) (list* 1 2 3 (circular-list 4 5)))) (:type-error :type-error :type-error :type-error :type-error :type-error)) (deftest setf-last-elt.1 (let ((l (list 1 2 3)) (s (copy-seq "foobar")) (b (copy-seq #*010101001))) (setf (last-elt l) '??? (last-elt s) #\? (last-elt b) 0) (values l s b)) (1 2 ???) "fooba?" #*010101000) (deftest setf-last-elt.error.1 (handler-case (setf (last-elt 'foo) 13) (type-error () :type-error)) :type-error) (deftest starts-with.1 (list (starts-with 1 '(1 2 3)) (starts-with 1 #(1 2 3)) (starts-with #\x "xyz") (starts-with 2 '(1 2 3)) (starts-with 3 #(1 2 3)) (starts-with 1 1) (starts-with nil nil)) (t t t nil nil nil nil)) (deftest starts-with.2 (values (starts-with 1 '(-1 2 3) :key '-) (starts-with "foo" '("foo" "bar") :test 'equal) (starts-with "f" '(#\f) :key 'string :test 'equal) (starts-with -1 '(0 1 2) :key #'1+) (starts-with "zot" '("ZOT") :test 'equal)) t t t nil nil) (deftest ends-with.1 (list (ends-with 3 '(1 2 3)) (ends-with 3 #(1 2 3)) (ends-with #\z "xyz") (ends-with 2 '(1 2 3)) (ends-with 1 #(1 2 3)) (ends-with 1 1) (ends-with nil nil)) (t t t nil nil nil nil)) (deftest ends-with.2 (values (ends-with 2 '(0 13 1) :key '1+) (ends-with "foo" (vector "bar" "foo") :test 'equal) (ends-with "X" (vector 1 2 #\X) :key 'string :test 'equal) (ends-with "foo" "foo" :test 'equal)) t t t nil) (deftest ends-with.error.1 (handler-case (ends-with 3 (circular-list 3 3 3 1 3 3)) (type-error () :type-error)) :type-error) (deftest sequences.passing-improper-lists (macrolet ((signals-error-p (form) `(handler-case (progn ,form nil) (type-error (e) t))) (cut (fn &rest args) (with-gensyms (arg) (print`(lambda (,arg) (apply ,fn (list ,@(substitute arg '_ args)))))))) (let ((circular-list (make-circular-list 5 :initial-element :foo)) (dotted-list (list* 'a 'b 'c 'd))) (loop for nth from 0 for fn in (list (cut #'lastcar _) (cut #'rotate _ 3) (cut #'rotate _ -3) (cut #'shuffle _) (cut #'random-elt _) (cut #'last-elt _) (cut #'ends-with :foo _)) nconcing (let ((on-circular-p (signals-error-p (funcall fn circular-list))) (on-dotted-p (signals-error-p (funcall fn dotted-list)))) (when (or (not on-circular-p) (not on-dotted-p)) (append (unless on-circular-p (let ((*print-circle* t)) (list (format nil "No appropriate error signalled when passing ~S to ~Ath entry." circular-list nth)))) (unless on-dotted-p (list (format nil "No appropriate error signalled when passing ~S to ~Ath entry." dotted-list nth))))))))) nil) ;;;; IO (deftest read-stream-content-into-string.1 (values (with-input-from-string (stream "foo bar") (read-stream-content-into-string stream)) (with-input-from-string (stream "foo bar") (read-stream-content-into-string stream :buffer-size 1)) (with-input-from-string (stream "foo bar") (read-stream-content-into-string stream :buffer-size 6)) (with-input-from-string (stream "foo bar") (read-stream-content-into-string stream :buffer-size 7))) "foo bar" "foo bar" "foo bar" "foo bar") (deftest read-stream-content-into-string.1-umlauts (values (with-input-from-string (stream "föö βαρ") (read-stream-content-into-string stream)) (with-input-from-string (stream "föö βαρ") (read-stream-content-into-string stream :buffer-size 1)) (with-input-from-string (stream "föö βαρ") (read-stream-content-into-string stream :buffer-size 6)) (with-input-from-string (stream "föö βαρ") (read-stream-content-into-string stream :buffer-size 7))) "föö βαρ" "föö βαρ" "föö βαρ" "föö βαρ") (deftest read-stream-content-into-string.2 (handler-case (let ((stream (make-broadcast-stream))) (read-stream-content-into-string stream :buffer-size 0)) (type-error () :type-error)) :type-error) #+(or) (defvar *octets* (map '(simple-array (unsigned-byte 8) (7)) #'char-code "foo bar")) #+(or) (deftest read-stream-content-into-byte-vector.1 (values (with-input-from-byte-vector (stream *octets*) (read-stream-content-into-byte-vector stream)) (with-input-from-byte-vector (stream *octets*) (read-stream-content-into-byte-vector stream :initial-size 1)) (with-input-from-byte-vector (stream *octets*) (read-stream-content-into-byte-vector stream 'alexandria::%length 6)) (with-input-from-byte-vector (stream *octets*) (read-stream-content-into-byte-vector stream 'alexandria::%length 3))) *octets* *octets* *octets* (subseq *octets* 0 3)) (deftest read-stream-content-into-byte-vector.2 (handler-case (let ((stream (make-broadcast-stream))) (read-stream-content-into-byte-vector stream :initial-size 0)) (type-error () :type-error)) :type-error) ;;;; Macros (deftest with-unique-names.1 (let ((*gensym-counter* 0)) (let ((syms (with-unique-names (foo bar quux) (list foo bar quux)))) (list (find-if #'symbol-package syms) (equal '("FOO0" "BAR1" "QUUX2") (mapcar #'symbol-name syms))))) (nil t)) (deftest with-unique-names.2 (let ((*gensym-counter* 0)) (let ((syms (with-unique-names ((foo "_foo_") (bar -bar-) (quux #\q)) (list foo bar quux)))) (list (find-if #'symbol-package syms) (equal '("_foo_0" "-BAR-1" "q2") (mapcar #'symbol-name syms))))) (nil t)) (deftest with-unique-names.3 (let ((*gensym-counter* 0) (*error-output* (make-broadcast-stream))) (multiple-value-bind (res err) (ignore-errors (eval '(let ((syms (with-unique-names ((foo "_foo_") (bar -bar-) (quux 42)) (list foo bar quux)))) (list (find-if #'symbol-package syms) (equal '("_foo_0" "-BAR-1" "q2") (mapcar #'symbol-name syms)))))) (errorp err))) t) (deftest once-only.1 (macrolet ((cons1.good (x) (once-only (x) `(cons ,x ,x))) (cons1.bad (x) `(cons ,x ,x))) (let ((y 0)) (list (cons1.good (incf y)) y (cons1.bad (incf y)) y))) ((1 . 1) 1 (2 . 3) 3)) (deftest once-only.2 (macrolet ((cons1 (x) (once-only ((y x)) `(cons ,y ,y)))) (let ((z 0)) (list (cons1 (incf z)) z (cons1 (incf z))))) ((1 . 1) 1 (2 . 2))) (deftest parse-body.1 (parse-body '("doc" "body") :documentation t) ("body") nil "doc") (deftest parse-body.2 (parse-body '("body") :documentation t) ("body") nil nil) (deftest parse-body.3 (parse-body '("doc" "body")) ("doc" "body") nil nil) (deftest parse-body.4 (parse-body '((declare (foo)) "doc" (declare (bar)) body) :documentation t) (body) ((declare (foo)) (declare (bar))) "doc") (deftest parse-body.5 (parse-body '((declare (foo)) "doc" (declare (bar)) body)) ("doc" (declare (bar)) body) ((declare (foo))) nil) (deftest parse-body.6 (multiple-value-bind (res err) (ignore-errors (parse-body '("foo" "bar" "quux") :documentation t)) (errorp err)) t) ;;;; Symbols (deftest ensure-symbol.1 (ensure-symbol :cons :cl) cons :external) (deftest ensure-symbol.2 (ensure-symbol "CONS" :alexandria) cons :inherited) (deftest ensure-symbol.3 (ensure-symbol 'foo :keyword) :foo :external) (deftest ensure-symbol.4 (ensure-symbol #\* :alexandria) * :inherited) (deftest format-symbol.1 (let ((s (format-symbol nil '#:x-~d 13))) (list (symbol-package s) (string= (string '#:x-13) (symbol-name s)))) (nil t)) (deftest format-symbol.2 (format-symbol :keyword '#:sym-~a (string :bolic)) :sym-bolic) (deftest format-symbol.3 (let ((*package* (find-package :cl))) (format-symbol t '#:find-~a (string 'package))) find-package) (deftest make-keyword.1 (list (make-keyword 'zot) (make-keyword "FOO") (make-keyword #\Q)) (:zot :foo :q)) (deftest make-gensym-list.1 (let ((*gensym-counter* 0)) (let ((syms (make-gensym-list 3 "FOO"))) (list (find-if 'symbol-package syms) (equal '("FOO0" "FOO1" "FOO2") (mapcar 'symbol-name syms))))) (nil t)) (deftest make-gensym-list.2 (let ((*gensym-counter* 0)) (let ((syms (make-gensym-list 3))) (list (find-if 'symbol-package syms) (equal '("G0" "G1" "G2") (mapcar 'symbol-name syms))))) (nil t)) ;;;; Type-system (deftest of-type.1 (locally (declare (notinline of-type)) (let ((f (of-type 'string))) (list (funcall f "foo") (funcall f 'bar)))) (t nil)) (deftest type=.1 (type= 'string 'string) t t) (deftest type=.2 (type= 'list '(or null cons)) t t) (deftest type=.3 (type= 'null '(and symbol list)) t t) (deftest type=.4 (type= 'string '(satisfies emptyp)) nil nil) (deftest type=.5 (type= 'string 'list) nil t) (macrolet ((test (type numbers) `(deftest ,(format-symbol t '#:cdr5.~a (string type)) (let ((numbers ,numbers)) (values (mapcar (of-type ',(format-symbol t '#:negative-~a (string type))) numbers) (mapcar (of-type ',(format-symbol t '#:non-positive-~a (string type))) numbers) (mapcar (of-type ',(format-symbol t '#:non-negative-~a (string type))) numbers) (mapcar (of-type ',(format-symbol t '#:positive-~a (string type))) numbers))) (t t t nil nil nil nil) (t t t t nil nil nil) (nil nil nil t t t t) (nil nil nil nil t t t)))) (test fixnum (list most-negative-fixnum -42 -1 0 1 42 most-positive-fixnum)) (test integer (list (1- most-negative-fixnum) -42 -1 0 1 42 (1+ most-positive-fixnum))) (test rational (list (1- most-negative-fixnum) -42/13 -1 0 1 42/13 (1+ most-positive-fixnum))) (test real (list most-negative-long-float -42/13 -1 0 1 42/13 most-positive-long-float)) (test float (list most-negative-short-float -42.02 -1.0 0.0 1.0 42.02 most-positive-short-float)) (test short-float (list most-negative-short-float -42.02s0 -1.0s0 0.0s0 1.0s0 42.02s0 most-positive-short-float)) (test single-float (list most-negative-single-float -42.02f0 -1.0f0 0.0f0 1.0f0 42.02f0 most-positive-single-float)) (test double-float (list most-negative-double-float -42.02d0 -1.0d0 0.0d0 1.0d0 42.02d0 most-positive-double-float)) (test long-float (list most-negative-long-float -42.02l0 -1.0l0 0.0l0 1.0l0 42.02l0 most-positive-long-float))) ;;;; Bindings (declaim (notinline opaque)) (defun opaque (x) x) (deftest if-let.1 (if-let (x (opaque :ok)) x :bad) :ok) (deftest if-let.2 (if-let (x (opaque nil)) :bad (and (not x) :ok)) :ok) (deftest if-let.3 (let ((x 1)) (if-let ((x 2) (y x)) (+ x y) :oops)) 3) (deftest if-let.4 (if-let ((x 1) (y nil)) :oops (and (not y) x)) 1) (deftest if-let.5 (if-let (x) :oops (not x)) t) (deftest if-let.error.1 (handler-case (eval '(if-let x :oops :oops)) (type-error () :type-error)) :type-error) (deftest when-let.1 (when-let (x (opaque :ok)) (setf x (cons x x)) x) (:ok . :ok)) (deftest when-let.2 (when-let ((x 1) (y nil) (z 3)) :oops) nil) (deftest when-let.3 (let ((x 1)) (when-let ((x 2) (y x)) (+ x y))) 3) (deftest when-let.error.1 (handler-case (eval '(when-let x :oops)) (type-error () :type-error)) :type-error) (deftest when-let*.1 (let ((x 1)) (when-let* ((x 2) (y x)) (+ x y))) 4) (deftest when-let*.2 (let ((y 1)) (when-let* (x y) (1+ x))) 2) (deftest when-let*.3 (when-let* ((x t) (y (consp x)) (z (error "OOPS"))) t) nil) (deftest when-let*.error.1 (handler-case (eval '(when-let* x :oops)) (type-error () :type-error)) :type-error) (deftest doplist.1 (let (keys values) (doplist (k v '(a 1 b 2 c 3) (values t (reverse keys) (reverse values) k v)) (push k keys) (push v values))) t (a b c) (1 2 3) nil nil) (deftest count-permutations.1 (values (count-permutations 31 7) (count-permutations 1 1) (count-permutations 2 1) (count-permutations 2 2) (count-permutations 3 2) (count-permutations 3 1)) 13253058000 1 2 2 6 3) (deftest binomial-coefficient.1 (alexandria:binomial-coefficient 1239 139) 28794902202288970200771694600561826718847179309929858835480006683522184441358211423695124921058123706380656375919763349913245306834194782172712255592710204598527867804110129489943080460154) ;; Exercise bignum case (at least on x86). (deftest binomial-coefficient.2 (alexandria:binomial-coefficient 2000000000000 20) 430998041177272843950422879590338454856322722740402365741730748431530623813012487773080486408378680853987520854296499536311275320016878730999689934464711239072435565454954447356845336730100919970769793030177499999999900000000000) (deftest copy-stream.1 (let ((data "sdkfjhsakfh weior763495ewofhsdfk sdfadlkfjhsadf woif sdlkjfhslkdfh sdklfjh")) (values (equal data (with-input-from-string (in data) (with-output-to-string (out) (alexandria:copy-stream in out)))) (equal (subseq data 10 20) (with-input-from-string (in data) (with-output-to-string (out) (alexandria:copy-stream in out :start 10 :end 20)))) (equal (subseq data 10) (with-input-from-string (in data) (with-output-to-string (out) (alexandria:copy-stream in out :start 10)))) (equal (subseq data 0 20) (with-input-from-string (in data) (with-output-to-string (out) (alexandria:copy-stream in out :end 20)))))) t t t t) (deftest extremum.1 (let ((n 0)) (dotimes (i 10) (let ((data (shuffle (coerce (iota 10000 :start i) 'vector))) (ok t)) (unless (eql i (extremum data #'<)) (setf ok nil)) (unless (eql i (extremum (coerce data 'list) #'<)) (setf ok nil)) (unless (eql (+ 9999 i) (extremum data #'>)) (setf ok nil)) (unless (eql (+ 9999 i) (extremum (coerce data 'list) #'>)) (setf ok nil)) (when ok (incf n)))) (when (eql 10 (extremum #(100 1 10 1000) #'> :start 1 :end 3)) (incf n)) (when (eql -1000 (extremum #(100 1 10 -1000) #'> :key 'abs)) (incf n)) (when (eq nil (extremum "" (lambda (a b) (error "wtf? ~S, ~S" a b)))) (incf n)) n) 13) (deftest starts-with-subseq.string (starts-with-subseq "f" "foo" :return-suffix t) t "oo") (deftest starts-with-subseq.vector (starts-with-subseq #(1) #(1 2 3) :return-suffix t) t #(2 3)) (deftest starts-with-subseq.list (starts-with-subseq '(1) '(1 2 3) :return-suffix t) t (2 3)) (deftest starts-with-subseq.start1 (starts-with-subseq "foo" "oop" :start1 1) t nil) (deftest starts-with-subseq.start2 (starts-with-subseq "foo" "xfoop" :start2 1) t nil) (deftest format-symbol.print-case-bound (let ((upper (intern "FOO-BAR")) (lower (intern "foo-bar")) (*print-escape* nil)) (values (let ((*print-case* :downcase)) (and (eq upper (format-symbol t "~A" upper)) (eq lower (format-symbol t "~A" lower)))) (let ((*print-case* :upcase)) (and (eq upper (format-symbol t "~A" upper)) (eq lower (format-symbol t "~A" lower)))) (let ((*print-case* :capitalize)) (and (eq upper (format-symbol t "~A" upper)) (eq lower (format-symbol t "~A" lower)))))) t t t) ;; In CLISP, (eql #C(2 0) 2) => T ;; but (eql #C(2 0) 2.0) => NIL ;; so we need a complex start point (deftest iota.fp-start-and-complex-integer-step (equal '(#C(0.0 0.0) #C(0.0 2.0) #C(0.0 4.0)) (iota 3 :start #C(0.0 0.0) :step #C(0 2))) t) (deftest parse-ordinary-lambda-list.1 (multiple-value-bind (req opt rest keys allowp aux keyp) (parse-ordinary-lambda-list '(a b c &optional o1 (o2 42) (o3 42 o3-supplied?) &key (k1) ((:key k2)) (k3 42 k3-supplied?)) :normalize t) (and (equal '(a b c) req) (equal '((o1 nil nil) (o2 42 nil) (o3 42 o3-supplied?)) opt) (equal '(((:k1 k1) nil nil) ((:key k2) nil nil) ((:k3 k3) 42 k3-supplied?)) keys) (not allowp) (not aux) (eq t keyp))) t)
55,346
Common Lisp
.lisp
1,825
21.511233
231
0.500986
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
16e9990985f78e827885f7af0d3265110f46907a19a4f8537b40a3cdd729e80f
42,563
[ -1 ]
42,564
control-flow.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/alexandria-20220707-git/alexandria-1/control-flow.lisp
(in-package :alexandria) (defun extract-function-name (spec) "Useful for macros that want to mimic the functional interface for functions like #'eq and 'eq." (if (and (consp spec) (member (first spec) '(quote function))) (second spec) spec)) (defun generate-switch-body (whole object clauses test key &optional default) (with-gensyms (value) (setf test (extract-function-name test)) (setf key (extract-function-name key)) (when (and (consp default) (member (first default) '(error cerror))) (setf default `(,@default "No keys match in SWITCH. Testing against ~S with ~S." ,value ',test))) `(let ((,value (,key ,object))) (cond ,@(mapcar (lambda (clause) (if (member (first clause) '(t otherwise)) (progn (when default (error "Multiple default clauses or illegal use of a default clause in ~S." whole)) (setf default `(progn ,@(rest clause))) '(())) (destructuring-bind (key-form &body forms) clause `((,test ,value ,key-form) ,@forms)))) clauses) (t ,default))))) (defmacro switch (&whole whole (object &key (test 'eql) (key 'identity)) &body clauses) "Evaluates first matching clause, returning its values, or evaluates and returns the values of T or OTHERWISE if no keys match." (generate-switch-body whole object clauses test key)) (defmacro eswitch (&whole whole (object &key (test 'eql) (key 'identity)) &body clauses) "Like SWITCH, but signals an error if no key matches." (generate-switch-body whole object clauses test key '(error))) (defmacro cswitch (&whole whole (object &key (test 'eql) (key 'identity)) &body clauses) "Like SWITCH, but signals a continuable error if no key matches." (generate-switch-body whole object clauses test key '(cerror "Return NIL from CSWITCH."))) (defmacro whichever (&rest possibilities &environment env) "Evaluates exactly one of POSSIBILITIES, chosen at random." (setf possibilities (mapcar (lambda (p) (macroexpand p env)) possibilities)) (let ((length (length possibilities))) (cond ((= 1 length) (first possibilities)) ((every #'constantp possibilities) `(svref (load-time-value (vector ,@possibilities)) (random ,length))) (T (labels ((expand (possibilities position random-number) (if (null (cdr possibilities)) (car possibilities) (let* ((length (length possibilities)) (half (truncate length 2)) (second-half (nthcdr half possibilities)) (first-half (butlast possibilities (- length half)))) `(if (< ,random-number ,(+ position half)) ,(expand first-half position random-number) ,(expand second-half (+ position half) random-number)))))) (with-gensyms (random-number) `(let ((,random-number (random ,length))) ,(expand possibilities 0 random-number)))))))) (defmacro xor (&rest datums) "Evaluates its arguments one at a time, from left to right. If more than one argument evaluates to a true value no further DATUMS are evaluated, and NIL is returned as both primary and secondary value. If exactly one argument evaluates to true, its value is returned as the primary value after all the arguments have been evaluated, and T is returned as the secondary value. If no arguments evaluate to true NIL is returned as primary, and T as secondary value." (with-gensyms (xor tmp true) `(let (,tmp ,true) (declare (ignorable ,tmp)) (block ,xor ,@(mapcar (lambda (datum) `(if (setf ,tmp ,datum) (if ,true (return-from ,xor (values nil nil)) (setf ,true ,tmp)))) datums) (return-from ,xor (values ,true t)))))) (defmacro nth-value-or (nth-value &body forms) "Evaluates FORM arguments one at a time, until the NTH-VALUE returned by one of the forms is true. It then returns all the values returned by evaluating that form. If none of the forms return a true nth value, this form returns NIL." (once-only (nth-value) (with-gensyms (values) `(let ((,values (multiple-value-list ,(first forms)))) (if (nth ,nth-value ,values) (values-list ,values) ,(if (rest forms) `(nth-value-or ,nth-value ,@(rest forms)) nil)))))) (defmacro multiple-value-prog2 (first-form second-form &body forms) "Evaluates FIRST-FORM, then SECOND-FORM, and then FORMS. Yields as its value all the value returned by SECOND-FORM." `(progn ,first-form (multiple-value-prog1 ,second-form ,@forms)))
5,220
Common Lisp
.lisp
103
38.864078
107
0.587706
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
a994b1a96e17501d63b21f1ed32163b3d0c3c7581b4f5c4e4f6a98d3afc8dc07
42,564
[ -1 ]
42,566
numbers.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/alexandria-20220707-git/alexandria-1/numbers.lisp
(in-package :alexandria) (declaim (inline clamp)) (defun clamp (number min max) "Clamps the NUMBER into [min, max] range. Returns MIN if NUMBER is lesser then MIN and MAX if NUMBER is greater then MAX, otherwise returns NUMBER." (if (< number min) min (if (> number max) max number))) (defun gaussian-random (&optional min max) "Returns two gaussian random double floats as the primary and secondary value, optionally constrained by MIN and MAX. Gaussian random numbers form a standard normal distribution around 0.0d0. Sufficiently positive MIN or negative MAX will cause the algorithm used to take a very long time. If MIN is positive it should be close to zero, and similarly if MAX is negative it should be close to zero." (macrolet ((valid (x) `(<= (or min ,x) ,x (or max ,x)) )) (labels ((gauss () (loop for x1 = (- (random 2.0d0) 1.0d0) for x2 = (- (random 2.0d0) 1.0d0) for w = (+ (expt x1 2) (expt x2 2)) when (< w 1.0d0) do (let ((v (sqrt (/ (* -2.0d0 (log w)) w)))) (return (values (* x1 v) (* x2 v)))))) (guard (x) (unless (valid x) (tagbody :retry (multiple-value-bind (x1 x2) (gauss) (when (valid x1) (setf x x1) (go :done)) (when (valid x2) (setf x x2) (go :done)) (go :retry)) :done)) x)) (multiple-value-bind (g1 g2) (gauss) (values (guard g1) (guard g2)))))) (declaim (inline iota)) (defun iota (n &key (start 0) (step 1)) "Return a list of n numbers, starting from START (with numeric contagion from STEP applied), each consequtive number being the sum of the previous one and STEP. START defaults to 0 and STEP to 1. Examples: (iota 4) => (0 1 2 3) (iota 3 :start 1 :step 1.0) => (1.0 2.0 3.0) (iota 3 :start -1 :step -1/2) => (-1 -3/2 -2) " (declare (type (integer 0) n) (number start step)) (loop ;; KLUDGE: get numeric contagion right for the first element too for i = (+ (- (+ start step) step)) then (+ i step) repeat n collect i)) (declaim (inline map-iota)) (defun map-iota (function n &key (start 0) (step 1)) "Calls FUNCTION with N numbers, starting from START (with numeric contagion from STEP applied), each consequtive number being the sum of the previous one and STEP. START defaults to 0 and STEP to 1. Returns N. Examples: (map-iota #'print 3 :start 1 :step 1.0) => 3 ;;; 1.0 ;;; 2.0 ;;; 3.0 " (declare (type (integer 0) n) (number start step)) (loop ;; KLUDGE: get numeric contagion right for the first element too for i = (+ start (- step step)) then (+ i step) repeat n do (funcall function i)) n) (declaim (inline lerp)) (defun lerp (v a b) "Returns the result of linear interpolation between A and B, using the interpolation coefficient V." ;; The correct version is numerically stable, at the expense of an ;; extra multiply. See (lerp 0.1 4 25) with (+ a (* v (- b a))). The ;; unstable version can often be converted to a fast instruction on ;; a lot of machines, though this is machine/implementation ;; specific. As alexandria is more about correct code, than ;; efficiency, and we're only talking about a single extra multiply, ;; many would prefer the stable version (+ (* (- 1.0 v) a) (* v b))) (declaim (inline mean)) (defun mean (sample) "Returns the mean of SAMPLE. SAMPLE must be a sequence of numbers." (/ (reduce #'+ sample) (length sample))) (defun median (sample) "Returns median of SAMPLE. SAMPLE must be a sequence of real numbers." ;; Implements and uses the quick-select algorithm to find the median ;; https://en.wikipedia.org/wiki/Quickselect (labels ((randint-in-range (start-int end-int) "Returns a random integer in the specified range, inclusive" (+ start-int (random (1+ (- end-int start-int))))) (partition (vec start-i end-i) "Implements the partition function, which performs a partial sort of vec around the (randomly) chosen pivot. Returns the index where the pivot element would be located in a correctly-sorted array" (if (= start-i end-i) start-i (let ((pivot-i (randint-in-range start-i end-i))) (rotatef (aref vec start-i) (aref vec pivot-i)) (let ((swap-i end-i)) (loop for i from swap-i downto (1+ start-i) do (when (>= (aref vec i) (aref vec start-i)) (rotatef (aref vec i) (aref vec swap-i)) (decf swap-i))) (rotatef (aref vec swap-i) (aref vec start-i)) swap-i))))) (let* ((vector (copy-sequence 'vector sample)) (len (length vector)) (mid-i (ash len -1)) (i 0) (j (1- len))) (loop for correct-pos = (partition vector i j) while (/= correct-pos mid-i) do (if (< correct-pos mid-i) (setf i (1+ correct-pos)) (setf j (1- correct-pos)))) (if (oddp len) (aref vector mid-i) (* 1/2 (+ (aref vector mid-i) (reduce #'max (make-array mid-i :displaced-to vector)))))))) (declaim (inline variance)) (defun variance (sample &key (biased t)) "Variance of SAMPLE. Returns the biased variance if BIASED is true (the default), and the unbiased estimator of variance if BIASED is false. SAMPLE must be a sequence of numbers." (let ((mean (mean sample))) (/ (reduce (lambda (a b) (+ a (expt (- b mean) 2))) sample :initial-value 0) (- (length sample) (if biased 0 1))))) (declaim (inline standard-deviation)) (defun standard-deviation (sample &key (biased t)) "Standard deviation of SAMPLE. Returns the biased standard deviation if BIASED is true (the default), and the square root of the unbiased estimator for variance if BIASED is false (which is not the same as the unbiased estimator for standard deviation). SAMPLE must be a sequence of numbers." (sqrt (variance sample :biased biased))) (define-modify-macro maxf (&rest numbers) max "Modify-macro for MAX. Sets place designated by the first argument to the maximum of its original value and NUMBERS.") (define-modify-macro minf (&rest numbers) min "Modify-macro for MIN. Sets place designated by the first argument to the minimum of its original value and NUMBERS.") ;;;; Factorial ;;; KLUDGE: This is really dependant on the numbers in question: for ;;; small numbers this is larger, and vice versa. Ideally instead of a ;;; constant we would have RANGE-FAST-TO-MULTIPLY-DIRECTLY-P. (defconstant +factorial-bisection-range-limit+ 8) ;;; KLUDGE: This is really platform dependant: ideally we would use ;;; (load-time-value (find-good-direct-multiplication-limit)) instead. (defconstant +factorial-direct-multiplication-limit+ 13) (defun %multiply-range (i j) ;; We use a a bit of cleverness here: ;; ;; 1. For large factorials we bisect in order to avoid expensive bignum ;; multiplications: 1 x 2 x 3 x ... runs into bignums pretty soon, ;; and once it does that all further multiplications will be with bignums. ;; ;; By instead doing the multiplication in a tree like ;; ((1 x 2) x (3 x 4)) x ((5 x 6) x (7 x 8)) ;; we manage to get less bignums. ;; ;; 2. Division isn't exactly free either, however, so we don't bisect ;; all the way down, but multiply ranges of integers close to each ;; other directly. ;; ;; For even better results it should be possible to use prime ;; factorization magic, but Nikodemus ran out of steam. ;; ;; KLUDGE: We support factorials of bignums, but it seems quite ;; unlikely anyone would ever be able to use them on a modern lisp, ;; since the resulting numbers are unlikely to fit in memory... but ;; it would be extremely unelegant to define FACTORIAL only on ;; fixnums, _and_ on lisps with 16 bit fixnums this can actually be ;; needed. (labels ((bisect (j k) (declare (type (integer 1 #.most-positive-fixnum) j k)) (if (< (- k j) +factorial-bisection-range-limit+) (multiply-range j k) (let ((middle (+ j (truncate (- k j) 2)))) (* (bisect j middle) (bisect (+ middle 1) k))))) (bisect-big (j k) (declare (type (integer 1) j k)) (if (= j k) j (let ((middle (+ j (truncate (- k j) 2)))) (* (if (<= middle most-positive-fixnum) (bisect j middle) (bisect-big j middle)) (bisect-big (+ middle 1) k))))) (multiply-range (j k) (declare (type (integer 1 #.most-positive-fixnum) j k)) (do ((f k (* f m)) (m (1- k) (1- m))) ((< m j) f) (declare (type (integer 0 (#.most-positive-fixnum)) m) (type unsigned-byte f))))) (if (and (typep i 'fixnum) (typep j 'fixnum)) (bisect i j) (bisect-big i j)))) (declaim (inline factorial)) (defun %factorial (n) (if (< n 2) 1 (%multiply-range 1 n))) (defun factorial (n) "Factorial of non-negative integer N." (check-type n (integer 0)) (%factorial n)) ;;;; Combinatorics (defun binomial-coefficient (n k) "Binomial coefficient of N and K, also expressed as N choose K. This is the number of K element combinations given N choises. N must be equal to or greater then K." (check-type n (integer 0)) (check-type k (integer 0)) (assert (>= n k)) (if (or (zerop k) (= n k)) 1 (let ((n-k (- n k))) ;; Swaps K and N-K if K < N-K because the algorithm ;; below is faster for bigger K and smaller N-K (when (< k n-k) (rotatef k n-k)) (if (= 1 n-k) n ;; General case, avoid computing the 1x...xK twice: ;; ;; N! 1x...xN (K+1)x...xN ;; -------- = ---------------- = ------------, N>1 ;; K!(N-K)! 1x...xK x (N-K)! (N-K)! (/ (%multiply-range (+ k 1) n) (%factorial n-k)))))) (defun subfactorial (n) "Subfactorial of the non-negative integer N." (check-type n (integer 0)) (if (zerop n) 1 (do ((x 1 (1+ x)) (a 0 (* x (+ a b))) (b 1 a)) ((= n x) a)))) (defun count-permutations (n &optional (k n)) "Number of K element permutations for a sequence of N objects. K defaults to N" (check-type n (integer 0)) (check-type k (integer 0)) (assert (>= n k)) (%multiply-range (1+ (- n k)) n))
11,218
Common Lisp
.lisp
265
34.245283
83
0.580976
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
41cd9c7305cb931cce95eef81348022d963a4bdde3008fc8df7d26de76451c52
42,566
[ 203646 ]
42,567
hash-tables.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/alexandria-20220707-git/alexandria-1/hash-tables.lisp
(in-package :alexandria) (defmacro ensure-gethash (key hash-table &optional default) "Like GETHASH, but if KEY is not found in the HASH-TABLE saves the DEFAULT under key before returning it. Secondary return value is true if key was already in the table." (once-only (key hash-table) (with-unique-names (value presentp) `(multiple-value-bind (,value ,presentp) (gethash ,key ,hash-table) (if ,presentp (values ,value ,presentp) (values (setf (gethash ,key ,hash-table) ,default) nil)))))) (defun copy-hash-table (table &key key test size rehash-size rehash-threshold) "Returns a copy of hash table TABLE, with the same keys and values as the TABLE. The copy has the same properties as the original, unless overridden by the keyword arguments. Before each of the original values is set into the new hash-table, KEY is invoked on the value. As KEY defaults to CL:IDENTITY, a shallow copy is returned by default." (setf key (or key 'identity)) (setf test (or test (hash-table-test table))) (setf size (or size (hash-table-size table))) (setf rehash-size (or rehash-size (hash-table-rehash-size table))) (setf rehash-threshold (or rehash-threshold (hash-table-rehash-threshold table))) (let ((copy (make-hash-table :test test :size size :rehash-size rehash-size :rehash-threshold rehash-threshold))) (maphash (lambda (k v) (setf (gethash k copy) (funcall key v))) table) copy)) (declaim (inline maphash-keys)) (defun maphash-keys (function table) "Like MAPHASH, but calls FUNCTION with each key in the hash table TABLE." (maphash (lambda (k v) (declare (ignore v)) (funcall function k)) table)) (declaim (inline maphash-values)) (defun maphash-values (function table) "Like MAPHASH, but calls FUNCTION with each value in the hash table TABLE." (maphash (lambda (k v) (declare (ignore k)) (funcall function v)) table)) (defun hash-table-keys (table) "Returns a list containing the keys of hash table TABLE." (let ((keys nil)) (maphash-keys (lambda (k) (push k keys)) table) keys)) (defun hash-table-values (table) "Returns a list containing the values of hash table TABLE." (let ((values nil)) (maphash-values (lambda (v) (push v values)) table) values)) (defun hash-table-alist (table) "Returns an association list containing the keys and values of hash table TABLE." (let ((alist nil)) (maphash (lambda (k v) (push (cons k v) alist)) table) alist)) (defun hash-table-plist (table) "Returns a property list containing the keys and values of hash table TABLE." (let ((plist nil)) (maphash (lambda (k v) (setf plist (list* k v plist))) table) plist)) (defun alist-hash-table (alist &rest hash-table-initargs) "Returns a hash table containing the keys and values of the association list ALIST. Hash table is initialized using the HASH-TABLE-INITARGS." (let ((table (apply #'make-hash-table hash-table-initargs))) (dolist (cons alist) (ensure-gethash (car cons) table (cdr cons))) table)) (defun plist-hash-table (plist &rest hash-table-initargs) "Returns a hash table containing the keys and values of the property list PLIST. Hash table is initialized using the HASH-TABLE-INITARGS." (let ((table (apply #'make-hash-table hash-table-initargs))) (do ((tail plist (cddr tail))) ((not tail)) (ensure-gethash (car tail) table (cadr tail))) table))
3,755
Common Lisp
.lisp
90
34.977778
83
0.657362
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
5956e0659b6e40081df02111e6f3450bc087bc0cb75ed501c2f3897adc59ee21
42,567
[ 191494 ]
42,569
functions.lisp
NailykSturm_Info805-TP/src/Import/quicklisp/dists/quicklisp/software/alexandria-20220707-git/alexandria-1/functions.lisp
(in-package :alexandria) ;;; To propagate return type and allow the compiler to eliminate the IF when ;;; it is known if the argument is function or not. (declaim (inline ensure-function)) (declaim (ftype (function (t) (values function &optional)) ensure-function)) (defun ensure-function (function-designator) "Returns the function designated by FUNCTION-DESIGNATOR: if FUNCTION-DESIGNATOR is a function, it is returned, otherwise it must be a function name and its FDEFINITION is returned." (if (functionp function-designator) function-designator (fdefinition function-designator))) (define-modify-macro ensure-functionf/1 () ensure-function) (defmacro ensure-functionf (&rest places) "Multiple-place modify macro for ENSURE-FUNCTION: ensures that each of PLACES contains a function." `(progn ,@(mapcar (lambda (x) `(ensure-functionf/1 ,x)) places))) (defun disjoin (predicate &rest more-predicates) "Returns a function that applies each of PREDICATE and MORE-PREDICATE functions in turn to its arguments, returning the primary value of the first predicate that returns true, without calling the remaining predicates. If none of the predicates returns true, NIL is returned." (declare (optimize (speed 3) (safety 1) (debug 1))) (let ((predicate (ensure-function predicate)) (more-predicates (mapcar #'ensure-function more-predicates))) (lambda (&rest arguments) (or (apply predicate arguments) (some (lambda (p) (declare (type function p)) (apply p arguments)) more-predicates))))) (defun conjoin (predicate &rest more-predicates) "Returns a function that applies each of PREDICATE and MORE-PREDICATE functions in turn to its arguments, returning NIL if any of the predicates returns false, without calling the remaining predicates. If none of the predicates returns false, returns the primary value of the last predicate." (if (null more-predicates) predicate (lambda (&rest arguments) (and (apply predicate arguments) ;; Cannot simply use CL:EVERY because we want to return the ;; non-NIL value of the last predicate if all succeed. (do ((tail (cdr more-predicates) (cdr tail)) (head (car more-predicates) (car tail))) ((not tail) (apply head arguments)) (unless (apply head arguments) (return nil))))))) (defun compose (function &rest more-functions) "Returns a function composed of FUNCTION and MORE-FUNCTIONS that applies its arguments to to each in turn, starting from the rightmost of MORE-FUNCTIONS, and then calling the next one with the primary value of the last." (declare (optimize (speed 3) (safety 1) (debug 1))) (reduce (lambda (f g) (let ((f (ensure-function f)) (g (ensure-function g))) (lambda (&rest arguments) (declare (dynamic-extent arguments)) (funcall f (apply g arguments))))) more-functions :initial-value function)) (define-compiler-macro compose (function &rest more-functions) (labels ((compose-1 (funs) (if (cdr funs) `(funcall ,(car funs) ,(compose-1 (cdr funs))) `(apply ,(car funs) arguments)))) (let* ((args (cons function more-functions)) (funs (make-gensym-list (length args) "COMPOSE"))) `(let ,(loop for f in funs for arg in args collect `(,f (ensure-function ,arg))) (declare (optimize (speed 3) (safety 1) (debug 1))) (lambda (&rest arguments) (declare (dynamic-extent arguments)) ,(compose-1 funs)))))) (defun multiple-value-compose (function &rest more-functions) "Returns a function composed of FUNCTION and MORE-FUNCTIONS that applies its arguments to each in turn, starting from the rightmost of MORE-FUNCTIONS, and then calling the next one with all the return values of the last." (declare (optimize (speed 3) (safety 1) (debug 1))) (reduce (lambda (f g) (let ((f (ensure-function f)) (g (ensure-function g))) (lambda (&rest arguments) (declare (dynamic-extent arguments)) (multiple-value-call f (apply g arguments))))) more-functions :initial-value function)) (define-compiler-macro multiple-value-compose (function &rest more-functions) (labels ((compose-1 (funs) (if (cdr funs) `(multiple-value-call ,(car funs) ,(compose-1 (cdr funs))) `(apply ,(car funs) arguments)))) (let* ((args (cons function more-functions)) (funs (make-gensym-list (length args) "MV-COMPOSE"))) `(let ,(mapcar #'list funs args) (declare (optimize (speed 3) (safety 1) (debug 1))) (lambda (&rest arguments) (declare (dynamic-extent arguments)) ,(compose-1 funs)))))) (declaim (inline curry rcurry)) (defun curry (function &rest arguments) "Returns a function that applies ARGUMENTS and the arguments it is called with to FUNCTION." (declare (optimize (speed 3) (safety 1))) (let ((fn (ensure-function function))) (lambda (&rest more) (declare (dynamic-extent more)) ;; Using M-V-C we don't need to append the arguments. (multiple-value-call fn (values-list arguments) (values-list more))))) (define-compiler-macro curry (function &rest arguments) (let ((curries (make-gensym-list (length arguments) "CURRY")) (fun (gensym "FUN"))) `(let ((,fun (ensure-function ,function)) ,@(mapcar #'list curries arguments)) (declare (optimize (speed 3) (safety 1))) (lambda (&rest more) (declare (dynamic-extent more)) (apply ,fun ,@curries more))))) (defun rcurry (function &rest arguments) "Returns a function that applies the arguments it is called with and ARGUMENTS to FUNCTION." (declare (optimize (speed 3) (safety 1))) (let ((fn (ensure-function function))) (lambda (&rest more) (declare (dynamic-extent more)) (multiple-value-call fn (values-list more) (values-list arguments))))) (define-compiler-macro rcurry (function &rest arguments) (let ((rcurries (make-gensym-list (length arguments) "RCURRY")) (fun (gensym "FUN"))) `(let ((,fun (ensure-function ,function)) ,@(mapcar #'list rcurries arguments)) (declare (optimize (speed 3) (safety 1))) (lambda (&rest more) (declare (dynamic-extent more)) (multiple-value-call ,fun (values-list more) ,@rcurries))))) (declaim (notinline curry rcurry)) (defmacro named-lambda (name lambda-list &body body) "Expands into a lambda-expression within whose BODY NAME denotes the corresponding function." `(labels ((,name ,lambda-list ,@body)) #',name))
6,645
Common Lisp
.lisp
143
41.041958
78
0.687384
NailykSturm/Info805-TP
0
0
0
GPL-3.0
9/19/2024, 11:51:23 AM (Europe/Amsterdam)
05fc9a92246d8a1340c97e7006e37e07694a49a4a924dac8fc9785c07a734917
42,569
[ 394939 ]