bytevector-utils.scm 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. (library (bytevector-utils)
  2. (export ascii-string->bytevector
  3. integer->bytevector)
  4. (import (except (rnrs base) let-values vector-for-each)
  5. (only (guile)
  6. lambda* λ)
  7. (rnrs bytevectors))
  8. (define ascii-string->bytevector
  9. (lambda* (string len #:key (endianness 'big))
  10. "Assuming, that string contains only ASCII characters."
  11. (cond
  12. [(eq? endianness 'big)
  13. (string->utf8 string)]
  14. [else
  15. (let ([bv (make-bytevector len 0)])
  16. (let iter
  17. ([index 0]
  18. [°char-nums (map char->integer (string->list string))])
  19. (cond
  20. [(null? °char-nums) bv]
  21. [else
  22. (bytevector-uint-set! bv
  23. (- (- len 1) index)
  24. (car °char-nums)
  25. endianness
  26. 1)
  27. (iter (+ index 1) (cdr °char-nums))])))])))
  28. (define integer->bytevector
  29. (lambda* (int num-bytes #:key (endianness 'big) (index 0) (signed #t))
  30. (let ([bv (make-bytevector num-bytes)])
  31. (cond
  32. [signed
  33. (bytevector-sint-set! bv 0 int endianness num-bytes)]
  34. [else
  35. (bytevector-uint-set! bv 0 int endianness num-bytes)])
  36. bv))))
  37. ;; syntax:
  38. ;; SRFI-4: https://www.gnu.org/software/guile/manual/html_node/SRFI_002d4.html
  39. ;; BYTEVECTORS: https://www.gnu.org/software/guile/manual/html_node/Bytevectors.html
  40. ;; bitvector: #*1111000, (bitvector->list #*101010101010) -> (#t #f #t #f #t #f #t #f #t #f #t #f)
  41. ;; bytevector: #vu8(0-255 0-255 ...)
  42. ;; vector: #(1 2 3)
  43. ;; vector of hexadecimal digits -> integer: #xdeadbeef
  44. ;; other uniform number vectors:
  45. ;; https://www.gnu.org/software/guile/manual/html_node/SRFI_002d4-Overview.html
  46. ;; #s8(-10 1 3)
  47. ;; #s16(-10 1 3)
  48. ;; #s32(-10 1 3)
  49. ;; ...
  50. ;; equality:
  51. ;; (equal? #vu8(1 2 3) #u8(1 2 3))
  52. ;; (eqv? #vu8(1 2 3) #u8(1 2 3))
  53. ;; (eq? #vu8(1 2 3) #u8(1 2 3))
  54. ;; Big-endian means storing the most significant byte FIRST, not LAST, as the name would seem to suggest.
  55. ;; Little-endian means storing the least significant byte FIRST, not LAST, as the name would seem to suggest.