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
- func AlphanumericValue(b byte) (int, bool)
- func ApplyMask(matrix [][]bool, maskPattern, version int)
- func BestEncodingMode(data []byte) int
- func BestMaskPattern(baseMatrix [][]bool, ecLevel, version int) int
- func BlockCount(version, ecLevel int) (group1Blocks, group2Blocks int)
- func BuildMatrix(version int) [][]bool
- func Capacity(version, ecLevel, mode int) int
- func CloneMatrix(matrix [][]bool) [][]bool
- func DataCapacity(version, ecLevel int) int
- func DataCodewords(version, ecLevel int) int
- func ECCodewords(version, ecLevel int) int
- func EncodeEC(data []byte, ecCount int) []byte
- func EncodeECBlocks(dataBlocks [][]byte, ecPerBlock int) [][]byte
- func GeneratorPoly(degree int) []int
- func IsAlphanumeric(b byte) bool
- func IsNumeric(b byte) bool
- func MatrixSize(version int) int
- func MinVersionForData(dataLen, ecLevel int) (int, error)
- func NewMatrix(version int) [][]bool
- func PenaltyScore(matrix [][]bool, _ int) int
- func PlaceAlignmentPattern(matrix [][]bool, _, row, col int)
- func PlaceAllAlignmentPatterns(matrix [][]bool, version int)
- func PlaceAllFinderPatterns(matrix [][]bool, version int)
- func PlaceDarkModule(matrix [][]bool, version int)
- func PlaceDataBits(matrix [][]bool, dataBits []bool, version int)
- func PlaceFinderPattern(matrix [][]bool, row, col int)
- func PlaceFormatInfo(matrix [][]bool, ecLevel, maskPattern int)
- func PlaceTimingPatterns(matrix [][]bool, version int)
- func PlaceVersionInfo(matrix [][]bool, version int)
- func PrintMatrix(matrix [][]bool) string
- func RemoveMask(matrix [][]bool, maskPattern, version int)
- func VerifyMatrixSize(matrix [][]bool, version int) error
- type QRCode
- type VersionInfo
Constants ¶
const ECLevelH = 3
ECLevelH is error correction level H (approximately 30% recovery).
const ECLevelL = 0
ECLevelL is error correction level L (approximately 7% recovery).
const ECLevelM = 1
ECLevelM is error correction level M (approximately 15% recovery).
const ECLevelQ = 2
ECLevelQ is error correction level Q (approximately 25% recovery).
const ModeAlphanumeric = 2
ModeAlphanumeric indicates alphanumeric data encoding (0–9, A–Z, and selected symbols).
const ModeByte = 4
ModeByte indicates 8-bit byte data encoding.
const ModeKanji = 8
ModeKanji indicates Shift JIS kanji data encoding.
const ModeNumeric = 1
ModeNumeric indicates numeric-only data encoding (digits 0–9).
Variables ¶
This section is empty.
Functions ¶
func AlphanumericValue ¶
AlphanumericValue returns the numeric code for an alphanumeric character and whether the character is valid.
func ApplyMask ¶
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 ¶
BestEncodingMode returns the most compact encoding mode for the given data.
func BestMaskPattern ¶
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 ¶
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 ¶
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 ¶
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 ¶
CloneMatrix creates a deep copy of the given module matrix.
func DataCapacity ¶
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 ¶
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 ¶
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 ¶
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 ¶
EncodeECBlocks computes error correction bytes for each data block using EncodeEC. The returned slice is aligned by index with the input blocks.
func GeneratorPoly ¶
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 ¶
IsAlphanumeric reports whether b is in the QR alphanumeric character set.
func MatrixSize ¶
MatrixSize returns the width and height of the module matrix for the given version, calculated as version*4 + 17.
func MinVersionForData ¶
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 ¶
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 ¶
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 ¶
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 ¶
PlaceAllAlignmentPatterns places alignment patterns for the given version. No alignment patterns are placed for version 1.
func PlaceAllFinderPatterns ¶
PlaceAllFinderPatterns places the three finder patterns at the top-left, top-right, and bottom-left corners of the matrix.
func PlaceDarkModule ¶
PlaceDarkModule sets the always-on dark module at its canonical position (row = version*4+9, column 8).
func PlaceDataBits ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
RemoveMask removes (toggles) a previously applied mask pattern by applying the same XOR operation again. Equivalent to ApplyMask with the same pattern.
func VerifyMatrixSize ¶
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 ¶
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 ¶
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.