From 37f3fabc6e699622320c7baa2b7e9b4c466d1c82 Mon Sep 17 00:00:00 2001 From: David Thompson Date: Sat, 9 Nov 2024 13:03:36 -0500 Subject: base64: Factorize memoization. --- chickadee/base64.scm | 41 +++++++++++++++++++++-------------------- 1 file changed, 21 insertions(+), 20 deletions(-) diff --git a/chickadee/base64.scm b/chickadee/base64.scm index c12fa39..9397f9f 100644 --- a/chickadee/base64.scm +++ b/chickadee/base64.scm @@ -41,16 +41,21 @@ (lp (1+ i) (cdr chars))))) (error "invalid base64 alphabet" alphabet))) -(define alphabet->decoder - (let ((cache (make-hash-table))) - (lambda (alphabet) - (or (hash-ref cache alphabet) - (let ((bv (make-bytevector 128 -1))) - (alphabet-for-each (lambda (i x) - (bytevector-s8-set! bv x i)) - alphabet) - (hash-set! cache alphabet bv) - bv))))) +(define-syntax-rule (define/memoize1 (name arg) body ...) + (define name + (let ((cache (make-hash-table))) + (lambda (arg) + (or (hash-ref cache arg) + (let ((val (begin body ...))) + (hash-set! cache arg val) + val)))))) + +(define/memoize1 (alphabet->decoder alphabet) + (let ((bv (make-bytevector 128 -1))) + (alphabet-for-each (lambda (i x) + (bytevector-s8-set! bv x i)) + alphabet) + bv)) (define* (base64-decode str #:optional (alphabet base64-alphabet)) "Decode the base64 encoded string @var{str} using @var{alphabet} and @@ -96,16 +101,12 @@ return a bytevector containing the decoded data." (put-u8 out (logand x #x0000ff)) (lp)))))))))))) -(define alphabet->encoder - (let ((cache (make-hash-table))) - (lambda (alphabet) - (or (hash-ref cache alphabet) - (let ((bv (make-bytevector 64))) - (alphabet-for-each (lambda (i x) - (bytevector-u8-set! bv i x)) - alphabet) - (hash-set! cache alphabet bv) - bv))))) +(define/memoize1 (alphabet->encoder alphabet) + (let ((bv (make-bytevector 64))) + (alphabet-for-each (lambda (i x) + (bytevector-u8-set! bv i x)) + alphabet) + bv)) (define* (base64-encode bv #:optional (alphabet base64-alphabet)) "Encode the bytevector @var{bv} to a base64 using -- cgit v1.2.3