base16.scm 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2012, 2014, 2017 Ludovic Courtès <ludo@gnu.org>
  3. ;;; Copyright © 2021 Maxime Devos <maximedevos@telenet.be>
  4. ;;;
  5. ;;; This file is part of GNU Guix.
  6. ;;;
  7. ;;; GNU Guix is free software; you can redistribute it and/or modify it
  8. ;;; under the terms of the GNU General Public License as published by
  9. ;;; the Free Software Foundation; either version 3 of the License, or (at
  10. ;;; your option) any later version.
  11. ;;;
  12. ;;; GNU Guix is distributed in the hope that it will be useful, but
  13. ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
  14. ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. ;;; GNU General Public License for more details.
  16. ;;;
  17. ;;; You should have received a copy of the GNU General Public License
  18. ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
  19. (define-module (guix base16)
  20. #:use-module (srfi srfi-1)
  21. #:use-module (srfi srfi-26)
  22. #:use-module (srfi srfi-60)
  23. #:use-module (rnrs bytevectors)
  24. #:use-module (ice-9 vlist)
  25. #:use-module (ice-9 format)
  26. #:export (bytevector->base16-string
  27. base16-string->bytevector))
  28. ;;;
  29. ;;; Base 16.
  30. ;;;
  31. (define (bytevector->base16-string bv)
  32. "Return the hexadecimal representation of BV's contents."
  33. (define len (bytevector-length bv))
  34. (define utf8 (make-bytevector (* len 2)))
  35. (let-syntax ((base16-octet-pairs
  36. (lambda (s)
  37. (syntax-case s ()
  38. (_
  39. (string->utf8
  40. (string-concatenate
  41. (unfold (cut > <> 255)
  42. (lambda (n)
  43. (format #f "~2,'0x" n))
  44. 1+
  45. 0))))))))
  46. (define octet-pairs base16-octet-pairs)
  47. (let loop ((i 0))
  48. (when (< i len)
  49. (bytevector-u16-native-set!
  50. utf8 (* 2 i)
  51. (bytevector-u16-native-ref octet-pairs
  52. (* 2 (bytevector-u8-ref bv i))))
  53. (loop (+ i 1))))
  54. (utf8->string utf8)))
  55. (define base16-string->bytevector
  56. (let ((chars->value (fold (lambda (i r)
  57. (vhash-consv (string-ref (number->string i 16)
  58. 0)
  59. i r))
  60. vlist-null
  61. (iota 16))))
  62. (lambda (s)
  63. "Return the bytevector whose hexadecimal representation is string S."
  64. (define bv
  65. (make-bytevector (quotient (string-length s) 2) 0))
  66. (string-fold (lambda (chr i)
  67. (let ((j (quotient i 2))
  68. (v (and=> (vhash-assv chr chars->value) cdr)))
  69. (if v
  70. (if (zero? (logand i 1))
  71. (bytevector-u8-set! bv j
  72. (arithmetic-shift v 4))
  73. (let ((w (bytevector-u8-ref bv j)))
  74. (bytevector-u8-set! bv j (logior v w))))
  75. (error "invalid hexadecimal character" chr)))
  76. (+ i 1))
  77. 0
  78. s)
  79. bv)))