001/* 002 * Copyright 2008 ZXing authors 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package com.itextpdf.text.pdf.qrcode; 018 019import java.util.ArrayList; 020 021/** 022 * <p>Implements Reed-Solomon enbcoding, as the name implies.</p> 023 * 024 * @author Sean Owen 025 * @author William Rucklidge 026 * @since 5.0.2 027 */ 028public final class ReedSolomonEncoder { 029 030 private final GF256 field; 031 private final ArrayList<GF256Poly> cachedGenerators; 032 033 public ReedSolomonEncoder(GF256 field) { 034 if (!GF256.QR_CODE_FIELD.equals(field)) { 035 throw new IllegalArgumentException("Only QR Code is supported at this time"); 036 } 037 this.field = field; 038 this.cachedGenerators = new ArrayList<GF256Poly>(); 039 cachedGenerators.add(new GF256Poly(field, new int[] { 1 })); 040 } 041 042 private GF256Poly buildGenerator(int degree) { 043 if (degree >= cachedGenerators.size()) { 044 GF256Poly lastGenerator = cachedGenerators.get(cachedGenerators.size() - 1); 045 for (int d = cachedGenerators.size(); d <= degree; d++) { 046 GF256Poly nextGenerator = lastGenerator.multiply(new GF256Poly(field, new int[] { 1, field.exp(d - 1) })); 047 cachedGenerators.add(nextGenerator); 048 lastGenerator = nextGenerator; 049 } 050 } 051 return (GF256Poly) cachedGenerators.get(degree); 052 } 053 054 public void encode(int[] toEncode, int ecBytes) { 055 if (ecBytes == 0) { 056 throw new IllegalArgumentException("No error correction bytes"); 057 } 058 int dataBytes = toEncode.length - ecBytes; 059 if (dataBytes <= 0) { 060 throw new IllegalArgumentException("No data bytes provided"); 061 } 062 GF256Poly generator = buildGenerator(ecBytes); 063 int[] infoCoefficients = new int[dataBytes]; 064 System.arraycopy(toEncode, 0, infoCoefficients, 0, dataBytes); 065 GF256Poly info = new GF256Poly(field, infoCoefficients); 066 info = info.multiplyByMonomial(ecBytes, 1); 067 GF256Poly remainder = info.divide(generator)[1]; 068 int[] coefficients = remainder.getCoefficients(); 069 int numZeroCoefficients = ecBytes - coefficients.length; 070 for (int i = 0; i < numZeroCoefficients; i++) { 071 toEncode[dataBytes + i] = 0; 072 } 073 System.arraycopy(coefficients, 0, toEncode, dataBytes + numZeroCoefficients, coefficients.length); 074 } 075 076}