summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDavid Thompson <dthompson2@worcester.edu>2024-11-09 13:03:36 -0500
committerDavid Thompson <dthompson2@worcester.edu>2024-11-09 13:03:36 -0500
commit37f3fabc6e699622320c7baa2b7e9b4c466d1c82 (patch)
treea73f0f0e89bc936ec0855dec9dfe108ac052f1a2
parentc19ba72fc241b19423e5dd54b02d7b2f441ced97 (diff)
base64: Factorize memoization.
-rw-r--r--chickadee/base64.scm41
1 files 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