1
Fork 0
mirror of https://git.savannah.gnu.org/git/guile.git synced 2025-05-20 11:40:18 +02:00

uri-encode fast path

* module/web/uri.scm (uri-encode): Add a fast-path for the common case
  in which the string does not contain any reserved characters.
This commit is contained in:
Andy Wingo 2011-01-02 10:07:54 -05:00
parent 7d6b8b75fc
commit 91b320fe16

View file

@ -330,27 +330,29 @@ bytes are not valid for the given encoding. Pass @code{#f} for
;; ;;
(define* (uri-encode str #:key (encoding "utf-8") (define* (uri-encode str #:key (encoding "utf-8")
(unescaped-chars unreserved-chars)) (unescaped-chars unreserved-chars))
"Percent-encode any character not in @var{unescaped-chars}. "Percent-encode any character not in the character set, @var{unescaped-chars}.
Percent-encoding first writes out the given character to a bytevector Percent-encoding first writes out the given character to a bytevector
within the given @var{encoding}, then encodes each byte as within the given @var{encoding}, then encodes each byte as
@code{%@var{HH}}, where @var{HH} is the hexadecimal representation of @code{%@var{HH}}, where @var{HH} is the hexadecimal representation of
the byte." the byte."
(call-with-output-string (if (string-index str unescaped-chars)
(lambda (port) (call-with-output-string
(string-for-each (lambda (port)
(lambda (ch) (string-for-each
(if (char-set-contains? unescaped-chars ch) (lambda (ch)
(display ch port) (if (char-set-contains? unescaped-chars ch)
(let* ((bv (encode-string (string ch) encoding)) (display ch port)
(len (bytevector-length bv))) (let* ((bv (encode-string (string ch) encoding))
(let lp ((i 0)) (len (bytevector-length bv)))
(if (< i len) (let lp ((i 0))
(let ((byte (bytevector-u8-ref bv i))) (if (< i len)
(display #\% port) (let ((byte (bytevector-u8-ref bv i)))
(display (number->string byte 16) port) (display #\% port)
(lp (1+ i)))))))) (display (number->string byte 16) port)
str)))) (lp (1+ i))))))))
str)))
str))
(define (split-and-decode-uri-path path) (define (split-and-decode-uri-path path)
"Split @var{path} into its components, and decode each "Split @var{path} into its components, and decode each