Otok public index

apotocki/zxing-cpp

apotocki/zxing-cpp 3.1.1 (r1, apple)

Library
zxing-cpp
Variant
apple, target apple
Channel
stable
Published
2026-11-07
Recipe source
https://github.com/otok-dev/recipes
32756a87cf5bd189ca4c9825159bf0713ea8cf5e in recipes/zxing-cpp/3.1/apple/
Recipe SHA-256
2c570ebfff69fe3e283eb6152aab1e8eb0b29526ae172e9226d129db1e0c9098

Recipe files changed

Inputs

source.commit287c85df6f961c8efbfb5ffd736cd9457b8b890e
source.githttps://github.com/zxing-cpp/zxing-cpp
source.submodulestrue
source.tagv3.1.1

Platforms

ios, iossim, macosx, catalyst, tvos, tvossim, watchos, watchossim, xros, xrossim

Options

OptionTypeDefaultDescription
writers bool false The writer of the new backend (ZXING_WRITERS = NEW: CreateBarcode.h, WriteBarcode.h), built from the bundled libzint into the ZXing library.

Toolchains

Recipe files

LICENSE-libzueci 1569 bytes · raw
libzueci (core/src/libzueci of zxing-cpp), an open source UTF-8 ECI library adapted from libzint

Copyright (C) 2022 gitlost

Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions
   and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice, this list of
   conditions and the following disclaimer in the documentation and/or other materials provided
   with the distribution.

3. Neither the name of the copyright holder nor the names of its contributors may be used to
   endorse or promote products derived from this software without specific prior written
   permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
LICENSE-zint 1535 bytes · raw
libzint - the open source barcode library
Copyright (C) 2008-2025 Robin Stuart <rstuart114@gmail.com>

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.
3. Neither the name of the project nor the names of its contributors
   may be used to endorse or promote products derived from this software
   without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
PrivacyInfo.xcprivacy 929 bytes · raw
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<!-- The privacy manifest of zxing-cpp, from its otok recipe. libzint's output.c calls stat() to check that a directory
     of an output file exists (zint_out_fopen); zxing-cpp writes into memory (BARCODE_MEMORY_FILE) and never calls it,
     but the code is linked: the metadata of files inside the app's container, C617.1. -->
<plist version="1.0">
<dict>
	<key>NSPrivacyTracking</key>
	<false/>
	<key>NSPrivacyTrackingDomains</key>
	<array/>
	<key>NSPrivacyCollectedDataTypes</key>
	<array/>
	<key>NSPrivacyAccessedAPITypes</key>
	<array>
		<dict>
			<key>NSPrivacyAccessedAPIType</key>
			<string>NSPrivacyAccessedAPICategoryFileTimestamp</string>
			<key>NSPrivacyAccessedAPITypeReasons</key>
			<array>
				<string>C617.1</string>
			</array>
		</dict>
	</array>
</dict>
</plist>
build.lua 1054 bytes · raw
-- The CMake project of the reader (with `writers`, the writer too): libZXing.a and include/ZXing/, with the module map
-- of the C API.
function build(slice, options, deps)
    -- the project of core/, as the wrappers build it: the top one adds, with the C API, the C wrapper's test
    -- program, for which it fetches stb; the writer's libzint is the submodule zint/ beside core/
    otok.cmake{
        source = slice.source .. "/core",
        defines = { ZXING_READERS = true, ZXING_WRITERS = options.writers and "NEW" or "OFF", ZXING_C_API = true },
    }
    local p = slice.prefix
    -- the module of the Swift API (wrappers/ZXingSwift): the C API and the headers it includes in C, the
    -- other headers are C++
    otok.write(p .. "/module.modulemap", 'module CZXing {\n    header "../ZXing/Version.h"\n    header "../ZXing/BarcodeFormat.h"\n'
        .. '    header "../ZXing/ZXingC.h"\n    export *\n}\n')
    return { libraries = { ZXing = p .. "/lib/libZXing.a" }, headers = p .. "/include", module_map = p .. "/module.modulemap" }
end
recipe.toml 2159 bytes · raw
# The otok recipe of zxing-cpp (https://github.com/apotocki/otok): the barcode reader library, with `writers`
# also the writer of its new backend, the bundled libzint (the submodule zint/), for every Apple platform, with the Swift
# API of this recipe (wrappers/ZXingSwift: BarcodeReader, BarcodeWriter) over zxing-cpp's C API.
[recipe]
api = 1
library = "zxing-cpp"
name = "zxing-cpp"
version = "3.1.1"
revision = 1
# the reader carries libzueci (core/src/libzueci), the writer libzint (zint/backend), both BSD-3-Clause; the source has
# neither text: zint/LICENSE only says which part of zint is BSD, the text is in the headers of its files. The code of
# android/ and wrappers/ is this recipe's own, CC0-1.0.
license = "Apache-2.0 AND BSD-3-Clause AND CC0-1.0"
license-files = ["LICENSE", { recipe = "LICENSE-libzueci" }, "zint/LICENSE", { recipe = "LICENSE-zint" }]
homepage = "https://github.com/zxing-cpp/zxing-cpp"
description = "zxing-cpp, a barcode reader and writer for linear and matrix formats: QR Code, Micro QR, rMQR, Aztec, DataMatrix, PDF417, MaxiCode, EAN/UPC, Code 39/93/128, ITF, Codabar, DataBar and others."
keywords = ["barcode", "qrcode", "scanner", "zxing"]
linkage = ["static"]
cxx-standard = ">= 20"

[source]
git = "https://github.com/zxing-cpp/zxing-cpp"
commit = "287c85df6f961c8efbfb5ffd736cd9457b8b890e"
tag = "v3.1.1"
# zint/, the writer's backend
submodules = true

[platforms]
supported = ["ios", "iossim", "macosx", "catalyst", "tvos", "tvossim", "watchos", "watchossim", "xros", "xrossim"]
build-on = ["macos/xcode"]

[options.writers]
type = "bool"
default = false
doc = "The writer of the new backend (ZXING_WRITERS = NEW: CreateBarcode.h, WriteBarcode.h), built from the bundled libzint into the ZXing library."

[toolchains]
cmake = { version = ">= 3.16", default-recipe = "apotocki/cmake" }
ninja = { version = ">= 1.10", default-recipe = "apotocki/ninja" }

[[product]]
name = "ZXing"
libraries = ["ZXing"]
link = { runtime = "c++" }
# Swift sees the C API only (module_map of build.lua): the other headers are C++
apple = { module = "CZXing", wrappers = ["ZXingSwift"], privacy-manifest = "PrivacyInfo.xcprivacy" }
wrappers/ZXingSwift/BarcodeReader.swift 12550 bytes · raw
// BarcodeReader: the reader of zxing-cpp for Swift, over its C API (ZXingC.h, the module CZXing), from the otok recipe
// of zxing-cpp. The names follow zxingcpp.BarcodeReader of zxing-cpp's Android wrapper.
// SPDX-License-Identifier: CC0-1.0

import CZXing
import Foundation
#if canImport(CoreGraphics)
import CoreGraphics
#endif
#if canImport(CoreVideo)
import CoreVideo
#endif

public struct BarcodeReadingError: Error, CustomStringConvertible {
    public let message: String
    public var description: String { "Failed to read barcode: \(message)" }
}

public final class BarcodeReader {
    // The barcode formats of zxing-cpp, with the values of its BarcodeFormat (BarcodeFormat.h).
    public enum Format: UInt32, CaseIterable, Sendable {
        case none           = 0x0000
        case all            = 0x2A2A
        case allReadable    = 0x722A
        case allCreatable   = 0x772A
        case allLinear      = 0x6C2A
        case allMatrix      = 0x6D2A
        case allGS1         = 0x472A
        case allRetail      = 0x522A
        case allIndustrial  = 0x492A
        case codabar        = 0x2046
        case code39         = 0x2041
        case code39Std      = 0x7341
        case code39Ext      = 0x6541
        case code32         = 0x3241
        case pzn            = 0x7041
        case code93         = 0x2047
        case code128        = 0x2043
        case itf            = 0x2049
        case itf14          = 0x3449
        case dataBar        = 0x2065
        case dataBarOmni    = 0x6F65
        case dataBarStk     = 0x7365
        case dataBarStkOmni = 0x4F65
        case dataBarLtd     = 0x6C65
        case dataBarExp     = 0x6565
        case dataBarExpStk  = 0x4565
        case eanUPC         = 0x2045
        case ean13          = 0x3145
        case ean8           = 0x3845
        case ean5           = 0x3545
        case ean2           = 0x3245
        case isbn           = 0x6945
        case upcA           = 0x6145
        case upcE           = 0x6545
        case telepen        = 0x2042
        case telepenAlpha   = 0x3042
        case telepenNumeric = 0x3142
        case otherBarcode   = 0x2058
        case dxFilmEdge     = 0x7858
        case pdf417         = 0x204C
        case compactPDF417  = 0x634C
        case microPDF417    = 0x6D4C
        case aztec          = 0x207A
        case aztecCode      = 0x637A
        case aztecRune      = 0x727A
        case qrCode         = 0x2051
        case qrCodeModel1   = 0x3151
        case qrCodeModel2   = 0x3251
        case microQRCode    = 0x6D51
        case rmqrCode       = 0x7251
        case dataMatrix     = 0x2064
        case maxiCode       = 0x2055

        var cValue: ZXing_BarcodeFormat { ZXing_BarcodeFormat(rawValue: numericCast(rawValue)) }
    }

    // the cases in the order of the C API's enums
    public enum ContentType: Int, Sendable { case text, binary, mixed, gs1, iso15434, unknownECI }
    public enum Binarizer: Int, Sendable { case localAverage, globalHistogram, fixedThreshold, boolCast }
    public enum EanAddOnSymbol: Int, Sendable { case ignore, read, require }
    public enum TextMode: Int, Sendable { case plain, eci, hri, escaped, hex, hexECI }
    public enum ErrorType: Int, Sendable { case none, format, checksum, unsupported }

    public struct Options: Sendable {
        public var formats: Set<Format> = []  // empty: all
        public var tryHarder = false
        public var tryRotate = false
        public var tryInvert = false
        public var tryDownscale = false
        public var isPure = false
        public var binarizer = Binarizer.localAverage
        public var minLineCount = 2
        public var maxNumberOfSymbols = 0xff
        public var validateOptionalChecksum = false
        public var returnErrors = false
        public var eanAddOnSymbol = EanAddOnSymbol.ignore
        public var textMode = TextMode.hri

        public init() {}
    }

    public struct Error: Sendable {
        public let type: ErrorType
        public let message: String
    }

    public struct Point: Sendable, Equatable {
        public let x: Int
        public let y: Int
    }

    public struct Position: Sendable {
        public let topLeft: Point
        public let topRight: Point
        public let bottomRight: Point
        public let bottomLeft: Point
    }

    public struct Result: Sendable {
        public let format: Format
        public let bytes: Data
        public let text: String
        public let contentType: ContentType
        public let position: Position
        public let orientation: Int  // degrees
        public let symbologyIdentifier: String
        public let sequenceSize: Int
        public let sequenceIndex: Int
        public let sequenceId: String
        public let hasECI: Bool
        public let isInverted: Bool
        public let isMirrored: Bool
        public let lineCount: Int
        public let error: Error?  // with Options.returnErrors
    }

    public var options: Options

    public init(options: Options = Options()) {
        self.options = options
    }

    // A grayscale image: a byte a pixel, rows of rowStride bytes (0: width).
    public func read(luminance: UnsafeRawBufferPointer, width: Int, height: Int, rowStride: Int = 0) throws -> [Result] {
        guard let pixels = luminance.baseAddress, luminance.count >= (rowStride == 0 ? width : rowStride) * height else {
            throw BarcodeReadingError(message: "the buffer is smaller than the image")
        }
        return try read(pixels, width: width, height: height, format: ZXing_ImageFormat_Lum, rowStride: rowStride, pixStride: 1)
    }

    #if canImport(CoreGraphics)
    // An image of any pixel format, drawn into a grayscale bitmap first.
    public func read(_ image: CGImage) throws -> [Result] {
        let width = image.width, height = image.height
        var gray = [UInt8](repeating: 0, count: width * height)
        try gray.withUnsafeMutableBytes { buffer in
            guard let context = CGContext(data: buffer.baseAddress, width: width, height: height, bitsPerComponent: 8,
                                          bytesPerRow: width, space: CGColorSpaceCreateDeviceGray(),
                                          bitmapInfo: CGImageAlphaInfo.none.rawValue) else {
                throw BarcodeReadingError(message: "cannot draw the image")
            }
            context.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height))
        }
        return try gray.withUnsafeBytes { try read(luminance: $0, width: width, height: height) }
    }
    #endif

    #if canImport(CoreVideo)
    // A frame of the camera: YpCbCr (its luma plane), BGRA, ARGB or one component of 8 bits.
    public func read(_ pixelBuffer: CVPixelBuffer) throws -> [Result] {
        CVPixelBufferLockBaseAddress(pixelBuffer, .readOnly)
        defer { CVPixelBufferUnlockBaseAddress(pixelBuffer, .readOnly) }
        let format: ZXing_ImageFormat, pixStride: Int
        switch CVPixelBufferGetPixelFormatType(pixelBuffer) {
        case kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange, kCVPixelFormatType_420YpCbCr8BiPlanarFullRange,
             kCVPixelFormatType_420YpCbCr8Planar, kCVPixelFormatType_420YpCbCr8PlanarFullRange:
            guard let luma = CVPixelBufferGetBaseAddressOfPlane(pixelBuffer, 0) else {
                throw BarcodeReadingError(message: "the pixel buffer has no pixels")
            }
            return try read(luma, width: CVPixelBufferGetWidthOfPlane(pixelBuffer, 0),
                            height: CVPixelBufferGetHeightOfPlane(pixelBuffer, 0), format: ZXing_ImageFormat_Lum,
                            rowStride: CVPixelBufferGetBytesPerRowOfPlane(pixelBuffer, 0), pixStride: 1)
        case kCVPixelFormatType_32BGRA: (format, pixStride) = (ZXing_ImageFormat_BGRA, 4)
        case kCVPixelFormatType_32ARGB: (format, pixStride) = (ZXing_ImageFormat_ARGB, 4)
        case kCVPixelFormatType_OneComponent8: (format, pixStride) = (ZXing_ImageFormat_Lum, 1)
        default:
            throw BarcodeReadingError(message: "unsupported pixel format of the pixel buffer")
        }
        guard let pixels = CVPixelBufferGetBaseAddress(pixelBuffer) else {
            throw BarcodeReadingError(message: "the pixel buffer has no pixels")
        }
        return try read(pixels, width: CVPixelBufferGetWidth(pixelBuffer), height: CVPixelBufferGetHeight(pixelBuffer),
                        format: format, rowStride: CVPixelBufferGetBytesPerRow(pixelBuffer), pixStride: pixStride)
    }
    #endif

    private func read(_ pixels: UnsafeRawPointer, width: Int, height: Int, format: ZXing_ImageFormat, rowStride: Int,
                      pixStride: Int) throws -> [Result] {
        guard let view = ZXing_ImageView_new(pixels.assumingMemoryBound(to: UInt8.self), CInt(width), CInt(height), format,
                                             CInt(rowStride), CInt(pixStride)) else {
            throw BarcodeReadingError(message: lastErrorMessage())
        }
        defer { ZXing_ImageView_delete(view) }
        let readerOptions = makeOptions()
        defer { ZXing_ReaderOptions_delete(readerOptions) }
        guard let barcodes = ZXing_ReadBarcodes(view, readerOptions) else {
            throw BarcodeReadingError(message: lastErrorMessage())
        }
        defer { ZXing_Barcodes_delete(barcodes) }
        return (0..<ZXing_Barcodes_size(barcodes)).compactMap { i in ZXing_Barcodes_at(barcodes, i).map(Result.init) }
    }

    private func makeOptions() -> OpaquePointer? {
        let o = ZXing_ReaderOptions_new()
        ZXing_ReaderOptions_setTryHarder(o, options.tryHarder)
        ZXing_ReaderOptions_setTryRotate(o, options.tryRotate)
        ZXing_ReaderOptions_setTryInvert(o, options.tryInvert)
        ZXing_ReaderOptions_setTryDownscale(o, options.tryDownscale)
        ZXing_ReaderOptions_setIsPure(o, options.isPure)
        ZXing_ReaderOptions_setBinarizer(o, ZXing_Binarizer(rawValue: numericCast(options.binarizer.rawValue)))
        ZXing_ReaderOptions_setMinLineCount(o, CInt(options.minLineCount))
        ZXing_ReaderOptions_setMaxNumberOfSymbols(o, CInt(options.maxNumberOfSymbols))
        ZXing_ReaderOptions_setValidateOptionalChecksum(o, options.validateOptionalChecksum)
        ZXing_ReaderOptions_setReturnErrors(o, options.returnErrors)
        ZXing_ReaderOptions_setEanAddOnSymbol(o, ZXing_EanAddOnSymbol(rawValue: numericCast(options.eanAddOnSymbol.rawValue)))
        ZXing_ReaderOptions_setTextMode(o, ZXing_TextMode(rawValue: numericCast(options.textMode.rawValue)))
        let formats = options.formats.map(\.cValue)
        ZXing_ReaderOptions_setFormats(o, formats, CInt(formats.count))
        return o
    }
}

extension BarcodeReader.Result {
    init(_ barcode: OpaquePointer) {
        format = BarcodeReader.Format(rawValue: numericCast(ZXing_Barcode_format(barcode).rawValue)) ?? .none
        var count: CInt = 0
        if let chars = ZXing_Barcode_bytes(barcode, &count) {
            bytes = Data(bytes: chars, count: Int(count))
            ZXing_free(chars)
        } else {
            bytes = Data()
        }
        text = string(taking: ZXing_Barcode_text(barcode))
        contentType = BarcodeReader.ContentType(rawValue: numericCast(ZXing_Barcode_contentType(barcode).rawValue)) ?? .unknownECI
        let p = ZXing_Barcode_position(barcode)
        position = BarcodeReader.Position(topLeft: .init(p.topLeft), topRight: .init(p.topRight),
                                          bottomRight: .init(p.bottomRight), bottomLeft: .init(p.bottomLeft))
        orientation = Int(ZXing_Barcode_orientation(barcode))
        symbologyIdentifier = string(taking: ZXing_Barcode_symbologyIdentifier(barcode))
        sequenceSize = Int(ZXing_Barcode_sequenceSize(barcode))
        sequenceIndex = Int(ZXing_Barcode_sequenceIndex(barcode))
        sequenceId = string(taking: ZXing_Barcode_sequenceId(barcode))
        hasECI = ZXing_Barcode_hasECI(barcode)
        isInverted = ZXing_Barcode_isInverted(barcode)
        isMirrored = ZXing_Barcode_isMirrored(barcode)
        lineCount = Int(ZXing_Barcode_lineCount(barcode))
        let errorType = BarcodeReader.ErrorType(rawValue: numericCast(ZXing_Barcode_errorType(barcode).rawValue)) ?? .none
        error = errorType == .none ? nil
            : BarcodeReader.Error(type: errorType, message: string(taking: ZXing_Barcode_errorMsg(barcode)))
    }
}

extension BarcodeReader.Point {
    init(_ p: ZXing_PointI) {
        self.init(x: Int(p.x), y: Int(p.y))
    }
}
wrappers/ZXingSwift/BarcodeWriter.swift 6221 bytes · raw
// BarcodeWriter: the writer of zxing-cpp's new backend for Swift, over its C API (ZXingC.h, the module CZXing), from
// the otok recipe of zxing-cpp. The names follow zxingcpp.BarcodeWriter of the recipe's Android writer (android/) and
// the writer of zxing-cpp's Kotlin/Native wrapper.
// SPDX-License-Identifier: CC0-1.0

import CZXing
import Foundation
#if canImport(CoreGraphics)
import CoreGraphics
#endif

// only with the option writers: the C API of a library without the writer fails every call
#if OTOK_OPTION_WRITERS

public struct BarcodeWritingError: Error, CustomStringConvertible {
    public let message: String
    public var description: String { "Failed to write barcode: \(message)" }
}

// What to create: the format, one that zxing-cpp can create, and options of that format as zxing-cpp's CreatorOptions
// takes them: "key=value" pairs separated by commas, or a JSON object ("ecLevel=30%, gs1"; ecLevel, eci, gs1,
// readerInit, forceSquare, columns, rows, version, dataMask).
public struct CreatorOptions: Sendable {
    public var format: BarcodeReader.Format
    public var options: String

    public init(format: BarcodeReader.Format, options: String = "") {
        self.format = format
        self.options = options
    }
}

// How to draw it: scale, the size of a module in pixels (negative: the barcode fits abs(scale) pixels as close as
// possible); rotate, by 0, 90, 180 or 270 degrees; addHRT, the human readable text below a linear barcode;
// addQuietZones, the margins the format requires.
public struct WriterOptions: Sendable {
    public var scale: Int
    public var rotate: Int
    public var addHRT: Bool
    public var addQuietZones: Bool

    public init(scale: Int = 1, rotate: Int = 0, addHRT: Bool = false, addQuietZones: Bool = true) {
        self.scale = scale
        self.rotate = rotate
        self.addHRT = addHRT
        self.addQuietZones = addQuietZones
    }
}

public enum BarcodeWriter {
    #if canImport(CoreGraphics)
    // A barcode of the bytes, as a grayscale image (black modules on white).
    public static func write(_ bytes: Data, creator: CreatorOptions, writer: WriterOptions = WriterOptions()) throws -> CGImage {
        try withBarcode(bytes, text: false, creator) { try image(of: $0, writer) }
    }

    // A barcode of the text (encoded as UTF-8, with the ECI the format needs for it).
    public static func write(_ text: String, creator: CreatorOptions, writer: WriterOptions = WriterOptions()) throws -> CGImage {
        try withBarcode(Data(text.utf8), text: true, creator) { try image(of: $0, writer) }
    }
    #endif

    // The barcode of the bytes as an SVG document.
    public static func writeSVG(_ bytes: Data, creator: CreatorOptions, writer: WriterOptions = WriterOptions()) throws -> String {
        try withBarcode(bytes, text: false, creator) { try svg(of: $0, writer) }
    }

    // The barcode of the text as an SVG document.
    public static func writeSVG(_ text: String, creator: CreatorOptions, writer: WriterOptions = WriterOptions()) throws -> String {
        try withBarcode(Data(text.utf8), text: true, creator) { try svg(of: $0, writer) }
    }

    private static func withBarcode<R>(_ contents: Data, text: Bool, _ creator: CreatorOptions,
                                       _ body: (OpaquePointer) throws -> R) throws -> R {
        let creatorOptions = ZXing_CreatorOptions_new(creator.format.cValue)
        defer { ZXing_CreatorOptions_delete(creatorOptions) }
        ZXing_CreatorOptions_setOptions(creatorOptions, creator.options)
        let barcode = contents.withUnsafeBytes { buffer in
            text ? ZXing_CreateBarcodeFromText(buffer.baseAddress?.assumingMemoryBound(to: CChar.self), CInt(buffer.count), creatorOptions)
                 : ZXing_CreateBarcodeFromBytes(buffer.baseAddress, CInt(buffer.count), creatorOptions)
        }
        guard let barcode else { throw BarcodeWritingError(message: lastErrorMessage()) }
        defer { ZXing_Barcode_delete(barcode) }
        return try body(barcode)
    }

    private static func withWriterOptions<R>(_ writer: WriterOptions, _ body: (OpaquePointer?) throws -> R) rethrows -> R {
        let o = ZXing_WriterOptions_new()
        defer { ZXing_WriterOptions_delete(o) }
        ZXing_WriterOptions_setScale(o, CInt(writer.scale))
        ZXing_WriterOptions_setRotate(o, CInt(writer.rotate))
        ZXing_WriterOptions_setAddHRT(o, writer.addHRT)
        ZXing_WriterOptions_setAddQuietZones(o, writer.addQuietZones)
        return try body(o)
    }

    #if canImport(CoreGraphics)
    private static func image(of barcode: OpaquePointer, _ writer: WriterOptions) throws -> CGImage {
        guard let image = withWriterOptions(writer, { ZXing_WriteBarcodeToImage(barcode, $0) }) else {
            throw BarcodeWritingError(message: lastErrorMessage())
        }
        defer { ZXing_Image_delete(image) }
        let width = Int(ZXing_Image_width(image)), height = Int(ZXing_Image_height(image))
        guard ZXing_Image_format(image) == ZXing_ImageFormat_Lum, let pixels = ZXing_Image_data(image) else {
            throw BarcodeWritingError(message: "the writer made an image that is not grayscale")
        }
        // a copy: the image of the C API is freed here
        guard let provider = CGDataProvider(data: Data(bytes: pixels, count: width * height) as CFData),
              let result = CGImage(width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 8, bytesPerRow: width,
                                   space: CGColorSpaceCreateDeviceGray(), bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue),
                                   provider: provider, decode: nil, shouldInterpolate: false, intent: .defaultIntent) else {
            throw BarcodeWritingError(message: "cannot make the image")
        }
        return result
    }
    #endif

    private static func svg(of barcode: OpaquePointer, _ writer: WriterOptions) throws -> String {
        guard let chars = withWriterOptions(writer, { ZXing_WriteBarcodeToSVG(barcode, $0) }) else {
            throw BarcodeWritingError(message: lastErrorMessage())
        }
        return string(taking: chars)
    }
}

#endif
wrappers/ZXingSwift/Support.swift 651 bytes · raw
// What BarcodeReader and BarcodeWriter share: the strings the C API of zxing-cpp gives away, its last error.
// From the otok recipe of zxing-cpp.
// SPDX-License-Identifier: CC0-1.0

import CZXing

// a string the C API returned, which the caller frees ("" for none)
func string(taking chars: UnsafeMutablePointer<CChar>?) -> String {
    guard let chars else { return "" }
    defer { ZXing_free(chars) }
    return String(cString: chars)
}

// the message of the C API's last failure on this thread
func lastErrorMessage() -> String {
    let message = string(taking: ZXing_LastErrorMsg())
    return message.isEmpty ? "unknown error" : message
}