1
mirror of https://gitlab.com/jessieh/qrprinter.git synced 2025-05-22 10:41:46 +00:00
qrprinter/src/ffi/qrencode.fnl

88 lines
2.6 KiB
Fennel

;; ffi/qrencode.fnl
;; Provides function wrappers for the libqrencode C library
;; -------------------------------------------------------------------------- ;;
;; License
;; Copyright (C) 2021 Jessie Hildebrandt
;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see <https://www.gnu.org/licenses/>.
;; -------------------------------------------------------------------------- ;;
;; Dependencies
(local ffi (require :ffi))
;; -------------------------------------------------------------------------- ;;
;; FFI libraries
;; ---------------------------------- ;;
;; C definitions
(ffi.cdef "
/* QR code object */
typedef struct {
int version;
int width;
unsigned char *data;
} QRcode;
/* QR code error correction level */
typedef enum {
QR_ECLEVEL_L = 0,
QR_ECLEVEL_M,
QR_ECLEVEL_Q,
QR_ECLEVEL_H
} QRecLevel;
/* Encode 8-bit string as QR code object */
QRcode* QRcode_encodeString8bit( const char* string, int version, QRecLevel level );
/* Free QR code object from memory */
void QRcode_free( QRcode* qrcode );
")
;; ---------------------------------- ;;
;; C libraries
(local ffi_qrencode (ffi.load :qrencode))
;; -------------------------------------------------------------------------- ;;
;; qrencode module
{
:encode_string_8_bit
(fn [string]
"Encode 8-bit string `string` into a table representing a QR code.
Wrapper for qrencode's QRcode_encodeString8bit.
Returns a 2D sequential table of true/false values representing black/white QR modules."
(let [qr_version 0
qrcode_table []
qrcode (ffi_qrencode.QRcode_encodeString8bit string qr_version :QR_ECLEVEL_L)]
(for [row 0 (- qrcode.width 1)]
(let [row_table []]
(for [column 0 (- qrcode.width 1)]
(let [module_index (+ (* row qrcode.width) column)
module_data (. qrcode.data module_index)
module_black? (= (% module_data 2) 1)]
(table.insert row_table module_black?)))
(table.insert qrcode_table row_table)))
(ffi_qrencode.QRcode_free qrcode)
qrcode_table))
}