encoding

package
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 19, 2026 License: MIT Imports: 1 Imported by: 0

Documentation

Overview

Package encoding implements the core QR code encoding pipeline including mode selection, data bitstream construction, Reed–Solomon error correction, mask pattern selection, and module matrix construction.

The primary entry points are Encode and EncodeWithMask, which accept raw data bytes and return a fully encoded QRCode struct containing the module matrix and metadata. Helper functions like Capacity, DataCodewords, and MinVersionForData allow callers to query encoding limits.

qr, err := encoding.Encode([]byte("hello world"), encoding.ECLevelM, 0)
// qr.Modules contains the boolean module matrix
// qr.Version, qr.Size, qr.MaskPattern contain metadata

Package encoding provides Reed–Solomon error correction encoding over GF(2⁸) for QR code data blocks.

Package encoding provides Galois Field GF(2⁸) arithmetic operations used by the Reed–Solomon error correction encoder.

Package encoding implements QR code data masking and penalty scoring to select the optimal mask pattern for readability.

Package encoding provides QR code module matrix construction, including finder patterns, alignment patterns, timing patterns, format/version information, and data bit placement.

Index

Constants

View Source
const ECLevelH = 3

ECLevelH is error correction level H (approximately 30% recovery).

View Source
const ECLevelL = 0

ECLevelL is error correction level L (approximately 7% recovery).

View Source
const ECLevelM = 1

ECLevelM is error correction level M (approximately 15% recovery).

View Source
const ECLevelQ = 2

ECLevelQ is error correction level Q (approximately 25% recovery).

View Source
const ModeAlphanumeric = 2

ModeAlphanumeric indicates alphanumeric data encoding (0–9, A–Z, and selected symbols).

View Source
const ModeByte = 4

ModeByte indicates 8-bit byte data encoding.

View Source
const ModeKanji = 8

ModeKanji indicates Shift JIS kanji data encoding.

View Source
const ModeNumeric = 1

ModeNumeric indicates numeric-only data encoding (digits 0–9).

Variables

This section is empty.

Functions

func AlphanumericValue

func AlphanumericValue(b byte) (int, bool)

AlphanumericValue returns the numeric code for an alphanumeric character and whether the character is valid.

func ApplyMask

func ApplyMask(matrix [][]bool, maskPattern, version int)

ApplyMask XORs data modules with the specified mask pattern (0–7). Function-pattern modules (finders, alignment, timing, format/version info) are left unchanged. Modifies the matrix in place.

func BestEncodingMode

func BestEncodingMode(data []byte) int

BestEncodingMode returns the most compact encoding mode for the given data.

func BestMaskPattern

func BestMaskPattern(baseMatrix [][]bool, ecLevel, version int) int

BestMaskPattern evaluates all eight mask patterns (0–7) and returns the one with the lowest total penalty score. For each candidate, it clones the base matrix, applies the mask, writes format/version info, and scores the result. The matrix passed in is not modified.

func BlockCount

func BlockCount(version, ecLevel int) (group1Blocks, group2Blocks int)

BlockCount returns the number of data blocks in each group for the given version and error correction level. Most versions use a single group; larger versions split into two groups with different data codeword counts. Returns (0, 0) if version or ecLevel is invalid.

func BuildMatrix

func BuildMatrix(version int) [][]bool

BuildMatrix creates a new matrix and places all fixed patterns (finder patterns, alignment patterns, timing patterns, and the dark module), leaving data modules unset.

func Capacity

func Capacity(version, ecLevel, mode int) int

Capacity returns the maximum number of data characters that can be encoded in a QR code of the given version, error correction level, and encoding mode. The mode must be one of ModeNumeric, ModeAlphanumeric, ModeByte, or ModeKanji. Returns 0 if version or ecLevel is invalid.

func CloneMatrix

func CloneMatrix(matrix [][]bool) [][]bool

CloneMatrix creates a deep copy of the given module matrix.

func DataCapacity

func DataCapacity(version, ecLevel int) int

DataCapacity returns the number of data codeword bytes available for the given version and error correction level. Returns 0 if version or ecLevel is invalid.

func DataCodewords

func DataCodewords(version, ecLevel int) int

DataCodewords returns the number of data codewords available for the given version and error correction level. Returns 0 if version or ecLevel is invalid.

func ECCodewords

func ECCodewords(version, ecLevel int) int

ECCodewords returns the total number of error correction codewords for the given version and error correction level (summed across all blocks). Returns 0 if version or ecLevel is invalid.

func EncodeEC

func EncodeEC(data []byte, ecCount int) []byte

EncodeEC computes ecCount error correction bytes for the given data block using polynomial long division over GF(2⁸). The returned slice has length ecCount. Returns nil if ecCount is zero or data is empty.

func EncodeECBlocks

func EncodeECBlocks(dataBlocks [][]byte, ecPerBlock int) [][]byte

EncodeECBlocks computes error correction bytes for each data block using EncodeEC. The returned slice is aligned by index with the input blocks.

func GeneratorPoly

func GeneratorPoly(degree int) []int

GeneratorPoly returns the Reed–Solomon generator polynomial of the given degree over GF(2⁸) with primitive polynomial 0x11D. The polynomial is computed by iteratively multiplying (x - α^i) for i = 0 to degree-1. A degree of 0 or less returns the trivial polynomial {1}.

func IsAlphanumeric

func IsAlphanumeric(b byte) bool

IsAlphanumeric reports whether b is in the QR alphanumeric character set.

func IsNumeric

func IsNumeric(b byte) bool

IsNumeric reports whether b is a decimal digit.

func MatrixSize

func MatrixSize(version int) int

MatrixSize returns the width and height of the module matrix for the given version, calculated as version*4 + 17.

func MinVersionForData

func MinVersionForData(dataLen, ecLevel int) (int, error)

MinVersionForData returns the smallest QR code version (1–40) that can hold dataLen bytes at the given error correction level. Returns an error if ecLevel is out of range, dataLen is negative, or the data exceeds the maximum capacity of version 40.

func NewMatrix

func NewMatrix(version int) [][]bool

NewMatrix creates a blank (all false) module matrix for the given QR version. The matrix has dimensions (version*4 + 17) × (version*4 + 17).

func PenaltyScore

func PenaltyScore(matrix [][]bool, _ int) int

PenaltyScore computes the total mask penalty score for the matrix using the four standard QR code penalty rules (N1–N4):

  • N1: runs of same-color modules in rows/columns
  • N2: 2×2 blocks of same-color modules
  • N3: finder-like patterns
  • N4: deviation from 50% dark-module ratio

func PlaceAlignmentPattern

func PlaceAlignmentPattern(matrix [][]bool, _, row, col int)

PlaceAlignmentPattern draws a 5×5 alignment pattern centered at (row, col). Alignment patterns help scanners correct for perspective distortion. The version parameter is unused but retained for API consistency.

func PlaceAllAlignmentPatterns

func PlaceAllAlignmentPatterns(matrix [][]bool, version int)

PlaceAllAlignmentPatterns places alignment patterns for the given version. No alignment patterns are placed for version 1.

func PlaceAllFinderPatterns

func PlaceAllFinderPatterns(matrix [][]bool, version int)

PlaceAllFinderPatterns places the three finder patterns at the top-left, top-right, and bottom-left corners of the matrix.

func PlaceDarkModule

func PlaceDarkModule(matrix [][]bool, version int)

PlaceDarkModule sets the always-on dark module at its canonical position (row = version*4+9, column 8).

func PlaceDataBits

func PlaceDataBits(matrix [][]bool, dataBits []bool, version int)

PlaceDataBits writes the interleaved data and EC bits into the matrix using the standard two-column zig-zag placement order, skipping any positions occupied by function patterns.

func PlaceFinderPattern

func PlaceFinderPattern(matrix [][]bool, row, col int)

PlaceFinderPattern draws a 7×7 finder pattern with the top-left corner at (row, col). Finder patterns consist of three concentric squares and are used by QR scanners to locate and orient the symbol.

func PlaceFormatInfo

func PlaceFormatInfo(matrix [][]bool, ecLevel, maskPattern int)

PlaceFormatInfo writes the 15-bit format information string (encoding the error correction level and mask pattern) into the two reserved areas of the matrix, protected by BCH error correction and a mask XOR.

func PlaceTimingPatterns

func PlaceTimingPatterns(matrix [][]bool, version int)

PlaceTimingPatterns draws the horizontal and vertical timing patterns alternating between dark and light modules, running between the finder patterns at row 6 and column 6.

func PlaceVersionInfo

func PlaceVersionInfo(matrix [][]bool, version int)

PlaceVersionInfo writes the 18-bit version information for versions 7–40 into the two reserved areas near the upper-left and lower-left finder patterns. No-op for versions 1–6.

func PrintMatrix

func PrintMatrix(matrix [][]bool) string

PrintMatrix returns a human-readable string representation of the matrix using '#' for dark modules and '.' for light modules, with newlines after each row.

func RemoveMask

func RemoveMask(matrix [][]bool, maskPattern, version int)

RemoveMask removes (toggles) a previously applied mask pattern by applying the same XOR operation again. Equivalent to ApplyMask with the same pattern.

func VerifyMatrixSize

func VerifyMatrixSize(matrix [][]bool, version int) error

VerifyMatrixSize checks that the matrix dimensions match the expected size for the given version (version*4 + 17). Returns an error if any row or column count is incorrect.

Types

type QRCode

type QRCode struct {
	// Version is the QR code version (1–40).
	Version int
	// Size is the width and height of the module matrix.
	Size int
	// Modules is the 2D boolean matrix where true represents a dark module.
	Modules [][]bool
	// ECLevel is the error correction level (0=L, 1=M, 2=Q, 3=H).
	ECLevel int
	// MaskPattern is the applied mask pattern (0–7).
	MaskPattern int
	// Data is the original input data.
	Data []byte
	// Metadata holds key-value pairs describing encoding parameters.
	Metadata map[string]string
}

QRCode represents a fully encoded QR code with its module matrix and metadata.

It is the primary output type of Encode and EncodeWithMask.

func Encode

func Encode(data []byte, ecLevel, version int) (*QRCode, error)

Encode produces a QR code from data using the specified error correction level (0=L, 1=M, 2=Q, 3=H) and version (1–40). A version of 0 triggers automatic version selection based on data length. The mask pattern is chosen automatically to minimize the penalty score.

Returns an error if ecLevel is out of range, data is empty, or the data exceeds the maximum capacity for the given error correction level.

func EncodeWithMask

func EncodeWithMask(data []byte, ecLevel, version, maskPattern int) (*QRCode, error)

EncodeWithMask produces a QR code like Encode but allows specifying a mask pattern (0–7). A maskPattern of -1 triggers automatic selection using penalty scoring, identical to Encode.

Returns an error if ecLevel or maskPattern is out of range, data is empty, or the data exceeds the maximum capacity.

type VersionInfo

type VersionInfo struct {
	// Version is the QR code version number (1–40).
	Version int
	// TotalCodewords is the total number of codeword bytes in the QR code.
	TotalCodewords int
	// DataCodewords is the number of codewords available for user data.
	DataCodewords int
	// ECBlocks is the total number of error correction blocks.
	ECBlocks int
	// ECCodewordsPerBlock is the number of EC codewords in each block.
	ECCodewordsPerBlock int
	// NumGroups is 1 or 2 depending on whether a second block group exists.
	NumGroups int
	// Group1Blocks is the number of blocks in the first block group.
	Group1Blocks int
	// Group1DataCodewords is the number of data codewords per block in the first group.
	Group1DataCodewords int
	// Group2Blocks is the number of blocks in the second block group.
	Group2Blocks int
	// Group2DataCodewords is the number of data codewords per block in the second group.
	Group2DataCodewords int
}

VersionInfo describes the structural parameters of a QR code version at a given error correction level.

func GetVersionInfo

func GetVersionInfo(version, ecLevel int) (*VersionInfo, error)

GetVersionInfo returns the VersionInfo for the given version (1–40) and error correction level (0–3). Returns an error if version or ecLevel is out of range.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL