text
stringlengths 9
39.2M
| dir
stringlengths 25
226
| lang
stringclasses 163
values | created_date
timestamp[s] | updated_date
timestamp[s] | repo_name
stringclasses 751
values | repo_full_name
stringclasses 752
values | star
int64 1.01k
183k
| len_tokens
int64 1
18.5M
|
|---|---|---|---|---|---|---|---|---|
```c++
/*
*/
#include "DMVersion.h"
namespace ZXing::DataMatrix {
const Version* VersionForDimensions(int height, int width)
{
if ((height & 0x01) != 0 || (width & 0x01) != 0 || height < 8 || height > 144)
return nullptr;
/**
* See ISO 16022:2006 5.5.1 Table 7
* See ISO 21471:2020 (DMRE) 5.5.1 Table 7
*/
static const Version allVersions[] = {
// clang-format off
{1, 10, 10, 8, 8, {5, {{1, 3 }, {0, 0}}}},
{2, 12, 12, 10, 10, {7, {{1, 5 }, {0, 0}}}},
{3, 14, 14, 12, 12, {10, {{1, 8 }, {0, 0}}}},
{4, 16, 16, 14, 14, {12, {{1, 12 }, {0, 0}}}},
{5, 18, 18, 16, 16, {14, {{1, 18 }, {0, 0}}}},
{6, 20, 20, 18, 18, {18, {{1, 22 }, {0, 0}}}},
{7, 22, 22, 20, 20, {20, {{1, 30 }, {0, 0}}}},
{8, 24, 24, 22, 22, {24, {{1, 36 }, {0, 0}}}},
{9, 26, 26, 24, 24, {28, {{1, 44 }, {0, 0}}}},
{10, 32, 32, 14, 14, {36, {{1, 62 }, {0, 0}}}},
{11, 36, 36, 16, 16, {42, {{1, 86 }, {0, 0}}}},
{12, 40, 40, 18, 18, {48, {{1, 114}, {0, 0}}}},
{13, 44, 44, 20, 20, {56, {{1, 144}, {0, 0}}}},
{14, 48, 48, 22, 22, {68, {{1, 174}, {0, 0}}}},
{15, 52, 52, 24, 24, {42, {{2, 102}, {0, 0}}}},
{16, 64, 64, 14, 14, {56, {{2, 140}, {0, 0}}}},
{17, 72, 72, 16, 16, {36, {{4, 92 }, {0, 0}}}},
{18, 80, 80, 18, 18, {48, {{4, 114}, {0, 0}}}},
{19, 88, 88, 20, 20, {56, {{4, 144}, {0, 0}}}},
{20, 96, 96, 22, 22, {68, {{4, 174}, {0, 0}}}},
{21, 104, 104, 24, 24, {56, {{6, 136}, {0, 0}}}},
{22, 120, 120, 18, 18, {68, {{6, 175}, {0, 0}}}},
{23, 132, 132, 20, 20, {62, {{8, 163}, {0, 0}}}},
{24, 144, 144, 22, 22, {62, {{8, 156}, {2, 155}}}},
{25, 8, 18, 6, 16, {7, {{1, 5 }, {0, 0}}}},
{26, 8, 32, 6, 14, {11, {{1, 10 }, {0, 0}}}},
{27, 12, 26, 10, 24, {14, {{1, 16 }, {0, 0}}}},
{28, 12, 36, 10, 16, {18, {{1, 22 }, {0, 0}}}},
{29, 16, 36, 14, 16, {24, {{1, 32 }, {0, 0}}}},
{30, 16, 48, 14, 22, {28, {{1, 49 }, {0, 0}}}},
// DMRE
{31, 8, 48, 6, 22, {15, {{1, 18 }, {0, 0}}}},
{32, 8, 64, 6, 14, {18, {{1, 24 }, {0, 0}}}},
{33, 8, 80, 6, 18, {22, {{1, 32 }, {0, 0}}}},
{34, 8, 96, 6, 22, {28, {{1, 38 }, {0, 0}}}},
{35, 8, 120, 6, 18, {32, {{1, 49 }, {0, 0}}}},
{36, 8, 144, 6, 22, {36, {{1, 63 }, {0, 0}}}},
{37, 12, 64, 10, 14, {27, {{1, 43 }, {0, 0}}}},
{38, 12, 88, 10, 20, {36, {{1, 64 }, {0, 0}}}},
{39, 16, 64, 14, 14, {36, {{1, 62 }, {0, 0}}}},
{40, 20, 36, 18, 16, {28, {{1, 44 }, {0, 0}}}},
{41, 20, 44, 18, 20, {34, {{1, 56 }, {0, 0}}}},
{42, 20, 64, 18, 14, {42, {{1, 84 }, {0, 0}}}},
{43, 22, 48, 20, 22, {38, {{1, 72 }, {0, 0}}}},
{44, 24, 48, 22, 22, {41, {{1, 80 }, {0, 0}}}},
{45, 24, 64, 22, 14, {46, {{1, 108}, {0, 0}}}},
{46, 26, 40, 24, 18, {38, {{1, 70 }, {0, 0}}}},
{47, 26, 48, 24, 22, {42, {{1, 90 }, {0, 0}}}},
{48, 26, 64, 24, 14, {50, {{1, 118}, {0, 0}}}},
// clang-format on
};
for (auto& version : allVersions)
if (version.symbolHeight == height && version.symbolWidth == width)
return &version;
return nullptr;
}
} // namespace ZXing::DataMatrix
```
|
/content/code_sandbox/core/src/datamatrix/DMVersion.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 1,823
|
```c++
/*
*/
#include "DMDataBlock.h"
#include "DMVersion.h"
#include "ZXAlgorithms.h"
#include <vector>
namespace ZXing::DataMatrix {
std::vector<DataBlock> GetDataBlocks(const ByteArray& rawCodewords, const Version& version, bool fix259)
{
// First count the total number of data blocks
// Now establish DataBlocks of the appropriate size and number of data codewords
auto& ecBlocks = version.ecBlocks;
const int numResultBlocks = ecBlocks.numBlocks();
std::vector<DataBlock> result;
result.reserve(numResultBlocks);
for (auto& ecBlock : ecBlocks.blocks)
for (int i = 0; i < ecBlock.count; i++)
result.push_back({ecBlock.dataCodewords, ByteArray(ecBlocks.codewordsPerBlock + ecBlock.dataCodewords)});
// All blocks have the same amount of data, except that the last n
// (where n may be 0) have 1 less byte. Figure out where these start.
// TODO(bbrown): There is only one case where there is a difference for Data Matrix for size 144
const int numCodewords = Size(result[0].codewords);
const int numDataCodewords = numCodewords - ecBlocks.codewordsPerBlock;
// The last elements of result may be 1 element shorter for 144 matrix
// first fill out as many elements as all of them have minus 1
int rawCodewordsOffset = 0;
for (int i = 0; i < numDataCodewords - 1; i++)
for (int j = 0; j < numResultBlocks; j++)
result[j].codewords[i] = rawCodewords[rawCodewordsOffset++];
// Fill out the last data block in the longer ones
const bool size144x144 = version.symbolHeight == 144;
const int numLongerBlocks = size144x144 ? 8 : numResultBlocks;
for (int j = 0; j < numLongerBlocks; j++)
result[j].codewords[numDataCodewords - 1] = rawCodewords[rawCodewordsOffset++];
// Now add in error correction blocks
for (int i = numDataCodewords; i < numCodewords; i++) {
for (int j = 0; j < numResultBlocks; j++) {
int jOffset = size144x144 && fix259 ? (j + 8) % numResultBlocks : j;
int iOffset = size144x144 && jOffset > 7 ? i - 1 : i;
result[jOffset].codewords[iOffset] = rawCodewords[rawCodewordsOffset++];
}
}
if (rawCodewordsOffset != Size(rawCodewords))
return {};
return result;
}
} // namespace ZXing::DataMatrix
```
|
/content/code_sandbox/core/src/datamatrix/DMDataBlock.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 632
|
```objective-c
/*
*/
#pragma once
#include "CharacterSet.h"
#include "DMSymbolShape.h"
#include <string>
namespace ZXing {
class BitMatrix;
namespace DataMatrix {
class Writer
{
public:
Writer();
Writer& setMargin(int margin) {
_quietZone = margin;
return *this;
}
Writer& setShapeHint(SymbolShape shape) {
_shapeHint = shape;
return *this;
}
Writer& setMinSize(int width, int height) {
_minWidth = width;
_minHeight = height;
return *this;
}
Writer& setMaxSize(int width, int height) {
_maxWidth = width;
_maxHeight = height;
return *this;
}
Writer& setEncoding(CharacterSet encoding) {
_encoding = encoding;
return *this;
}
BitMatrix encode(const std::wstring& contents, int width, int height) const;
BitMatrix encode(const std::string& contents, int width, int height) const;
private:
SymbolShape _shapeHint;
int _quietZone = 1, _minWidth = -1, _minHeight = -1, _maxWidth = -1, _maxHeight = -1;
CharacterSet _encoding;
};
} // DataMatrix
} // ZXing
```
|
/content/code_sandbox/core/src/datamatrix/DMWriter.h
|
objective-c
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 283
|
```objective-c
/*
*/
#pragma once
namespace ZXing::DataMatrix {
enum class SymbolShape {
NONE,
SQUARE,
RECTANGLE,
};
} // namespace ZXing::DataMatrix
```
|
/content/code_sandbox/core/src/datamatrix/DMSymbolShape.h
|
objective-c
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 38
|
```c++
/*
*/
#include "DMECEncoder.h"
#include "ByteArray.h"
#include "DMSymbolInfo.h"
#include <algorithm>
#include <array>
#include <stdexcept>
#include <string>
namespace ZXing::DataMatrix {
/**
* Precomputed polynomial factors for ECC 200.
*/
static const std::array<ByteArray, 16> FACTORS = {{
/*set 1*/ {228, 48, 15, 111, 62},
/*set 2*/ {23, 68, 144, 134, 240, 92, 254},
/*set 3*/ {28, 24, 185, 166, 223, 248, 116, 255, 110, 61},
/*set 4*/ {175, 138, 205, 12, 194, 168, 39, 245, 60, 97, 120},
/*set 5*/ {41, 153, 158, 91, 61, 42, 142, 213, 97, 178, 100, 242},
/*set 6*/ {156, 97, 192, 252, 95, 9, 157, 119, 138, 45, 18, 186, 83, 185},
/*set 7*/ {83, 195, 100, 39, 188, 75, 66, 61, 241, 213, 109, 129, 94, 254, 225, 48, 90, 188},
/*set 8*/ {15, 195, 244, 9, 233, 71, 168, 2, 188, 160, 153, 145, 253, 79, 108, 82, 27, 174, 186, 172},
/*set 9*/ {52, 190, 88, 205, 109, 39, 176, 21, 155, 197, 251, 223, 155, 21, 5, 172, 254, 124, 12, 181,
184, 96, 50, 193},
/*set 10*/ {211, 231, 43, 97, 71, 96, 103, 174, 37, 151, 170, 53, 75, 34, 249, 121, 17, 138, 110, 213,
141, 136, 120, 151, 233, 168, 93, 255},
/*set 11*/ {245, 127, 242, 218, 130, 250, 162, 181, 102, 120, 84, 179, 220, 251, 80, 182, 229, 18, 2, 4,
68, 33, 101, 137, 95, 119, 115, 44, 175, 184, 59, 25, 225, 98, 81, 112},
/*set 12*/ {77, 193, 137, 31, 19, 38, 22, 153, 247, 105, 122, 2, 245, 133, 242, 8, 175, 95, 100, 9, 167,
105, 214, 111, 57, 121, 21, 1, 253, 57, 54, 101, 248, 202, 69, 50, 150, 177, 226, 5, 9, 5},
/*set 13*/ {245, 132, 172, 223, 96, 32, 117, 22, 238, 133, 238, 231, 205, 188, 237, 87, 191, 106, 16, 147,
118, 23, 37, 90, 170, 205, 131, 88, 120, 100, 66, 138, 186, 240, 82, 44, 176, 87, 187, 147,
160, 175, 69, 213, 92, 253, 225, 19},
/*set 14*/ {175, 9, 223, 238, 12, 17, 220, 208, 100, 29, 175, 170, 230, 192, 215, 235, 150, 159, 36, 223,
38, 200, 132, 54, 228, 146, 218, 234, 117, 203, 29, 232, 144, 238, 22, 150, 201, 117, 62, 207,
164, 13, 137, 245, 127, 67, 247, 28, 155, 43, 203, 107, 233, 53, 143, 46},
/*set 15*/ {242, 93, 169, 50, 144, 210, 39, 118, 202, 188, 201, 189, 143, 108, 196, 37, 185, 112, 134, 230,
245, 63, 197, 190, 250, 106, 185, 221, 175, 64, 114, 71, 161, 44, 147, 6, 27, 218, 51, 63, 87,
10, 40, 130, 188, 17, 163, 31, 176, 170, 4, 107, 232, 7, 94, 166, 224, 124, 86, 47, 11, 204},
/*set 16*/ {220, 228, 173, 89, 251, 149, 159, 56, 89, 33, 147, 244, 154, 36, 73, 127, 213, 136, 248, 180,
234, 197, 158, 177, 68, 122, 93, 213, 15, 160, 227, 236, 66, 139, 153, 185, 202, 167, 179, 25,
220, 232, 96, 210, 231, 136, 223, 239, 181, 241, 59, 52, 172, 25, 49, 232, 211, 189, 64, 54,
108, 153, 132, 63, 96, 103, 82, 186},
}};
static const uint8_t LOG[] = {
0, 255, 1, 240, 2, 225, 241, 53, 3, 38, 226, 133, 242, 43, 54, 210,
4, 195, 39, 114, 227, 106, 134, 28, 243, 140, 44, 23, 55, 118, 211, 234,
5, 219, 196, 96, 40, 222, 115, 103, 228, 78, 107, 125, 135, 8, 29, 162,
244, 186, 141, 180, 45, 99, 24, 49, 56, 13, 119, 153, 212, 199, 235, 91,
6, 76, 220, 217, 197, 11, 97, 184, 41, 36, 223, 253, 116, 138, 104, 193,
229, 86, 79, 171, 108, 165, 126, 145, 136, 34, 9, 74, 30, 32, 163, 84,
245, 173, 187, 204, 142, 81, 181, 190, 46, 88, 100, 159, 25, 231, 50, 207,
57, 147, 14, 67, 120, 128, 154, 248, 213, 167, 200, 63, 236, 110, 92, 176,
7, 161, 77, 124, 221, 102, 218, 95, 198, 90, 12, 152, 98, 48, 185, 179,
42, 209, 37, 132, 224, 52, 254, 239, 117, 233, 139, 22, 105, 27, 194, 113,
230, 206, 87, 158, 80, 189, 172, 203, 109, 175, 166, 62, 127, 247, 146, 66,
137, 192, 35, 252, 10, 183, 75, 216, 31, 83, 33, 73, 164, 144, 85, 170,
246, 65, 174, 61, 188, 202, 205, 157, 143, 169, 82, 72, 182, 215, 191, 251,
47, 178, 89, 151, 101, 94, 160, 123, 26, 112, 232, 21, 51, 238, 208, 131,
58, 69, 148, 18, 15, 16, 68, 17, 121, 149, 129, 19, 155, 59, 249, 70,
214, 250, 168, 71, 201, 156, 64, 60, 237, 130, 111, 20, 93, 122, 177, 150,
};
static const uint8_t ALOG[] = {
1, 2, 4, 8, 16, 32, 64, 128, 45, 90, 180, 69, 138, 57, 114, 228,
229, 231, 227, 235, 251, 219, 155, 27, 54, 108, 216, 157, 23, 46, 92, 184,
93, 186, 89, 178, 73, 146, 9, 18, 36, 72, 144, 13, 26, 52, 104, 208,
141, 55, 110, 220, 149, 7, 14, 28, 56, 112, 224, 237, 247, 195, 171, 123,
246, 193, 175, 115, 230, 225, 239, 243, 203, 187, 91, 182, 65, 130, 41, 82,
164, 101, 202, 185, 95, 190, 81, 162, 105, 210, 137, 63, 126, 252, 213, 135,
35, 70, 140, 53, 106, 212, 133, 39, 78, 156, 21, 42, 84, 168, 125, 250,
217, 159, 19, 38, 76, 152, 29, 58, 116, 232, 253, 215, 131, 43, 86, 172,
117, 234, 249, 223, 147, 11, 22, 44, 88, 176, 77, 154, 25, 50, 100, 200,
189, 87, 174, 113, 226, 233, 255, 211, 139, 59, 118, 236, 245, 199, 163, 107,
214, 129, 47, 94, 188, 85, 170, 121, 242, 201, 191, 83, 166, 97, 194, 169,
127, 254, 209, 143, 51, 102, 204, 181, 71, 142, 49, 98, 196, 165, 103, 206,
177, 79, 158, 17, 34, 68, 136, 61, 122, 244, 197, 167, 99, 198, 161, 111,
222, 145, 15, 30, 60, 120, 240, 205, 183, 67, 134, 33, 66, 132, 37, 74,
148, 5, 10, 20, 40, 80, 160, 109, 218, 153, 31, 62, 124, 248, 221, 151,
3, 6, 12, 24, 48, 96, 192, 173, 119, 238, 241, 207, 179, 75, 150, 1,
};
static uint8_t mult(uint8_t a, uint8_t b)
{
if(a == 0 || b == 0)
return 0;
return ALOG[(LOG[a] + LOG[b]) % 255];
}
//TODO: replace this duplicated code with ReedSolomonEncoder
static void CreateECCBlock(ByteArray& data, int codeOffset, int codeLength, int eccOffset, int eccLength, int stride)
{
// binary search for the poly vector with length numECWords
auto iter = std::lower_bound(FACTORS.begin(), FACTORS.end(), eccLength,
[](const ByteArray& vec, size_t size) { return vec.size() < size; });
if (iter == FACTORS.end())
throw std::invalid_argument("Illegal number of error correction codewords specified: " + std::to_string(eccLength));
auto& poly = *iter;
ByteArray ecc(eccLength);
for (int i = 0; i < codeLength; ++i) {
const auto m = ecc.back() ^ data[codeOffset + i * stride];
for (size_t k = ecc.size() - 1; k > 0; k--)
ecc[k] = ecc[k - 1] ^ mult(m, poly[k]);
ecc[0] = mult(m, poly[0]);
}
for (int i = 0; i < eccLength; ++i)
data[eccOffset + i * stride] = ecc[eccLength - 1 - i];
}
void EncodeECC200(ByteArray& codewords, const SymbolInfo& symbolInfo)
{
if (codewords.size() != (size_t)symbolInfo.dataCapacity()) {
throw std::invalid_argument("The number of codewords does not match the selected symbol");
}
codewords.resize(symbolInfo.codewordCount(), 0);
int blockCount = symbolInfo.interleavedBlockCount();
if (blockCount == 1) {
CreateECCBlock(codewords, 0, symbolInfo.dataCapacity(), symbolInfo.dataCapacity(), symbolInfo.errorCodewords(), 1);
}
else {
for (int block = 0; block < blockCount; block++)
CreateECCBlock(codewords, block, symbolInfo.dataLengthForInterleavedBlock(block + 1),
symbolInfo.dataCapacity() + block, symbolInfo.errorLengthForInterleavedBlock(), blockCount);
}
}
} // namespace ZXing::DataMatrix
```
|
/content/code_sandbox/core/src/datamatrix/DMECEncoder.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 3,863
|
```objective-c
/*
*/
#pragma once
#include "DMSymbolShape.h"
namespace ZXing::DataMatrix {
class SymbolInfo
{
bool _rectangular;
int _dataCapacity;
int _errorCodewords;
int _matrixWidth;
int _matrixHeight;
int _dataRegions;
int _rsBlockData;
int _rsBlockError;
public:
constexpr SymbolInfo(bool rectangular, int dataCapacity, int errorCodewords, int matrixWidth, int matrixHeight, int dataRegions)
: SymbolInfo(rectangular, dataCapacity, errorCodewords, matrixWidth, matrixHeight, dataRegions, dataCapacity, errorCodewords)
{}
constexpr SymbolInfo(bool rectangular, int dataCapacity, int errorCodewords, int matrixWidth, int matrixHeight, int dataRegions,
int rsBlockData, int rsBlockError)
: _rectangular(rectangular),
_dataCapacity(dataCapacity),
_errorCodewords(errorCodewords),
_matrixWidth(matrixWidth),
_matrixHeight(matrixHeight),
_dataRegions(dataRegions),
_rsBlockData(rsBlockData),
_rsBlockError(rsBlockError)
{}
static const SymbolInfo* Lookup(int dataCodewords);
static const SymbolInfo* Lookup(int dataCodewords, SymbolShape shape);
static const SymbolInfo* Lookup(int dataCodewords, bool allowRectangular);
static const SymbolInfo* Lookup(int dataCodewords, SymbolShape shape, int minWidth, int minHeight, int maxWidth, int maxHeight);
int horizontalDataRegions() const;
int verticalDataRegions() const;
int symbolDataWidth() const { return horizontalDataRegions() * _matrixWidth; }
int symbolDataHeight() const { return verticalDataRegions() * _matrixHeight; }
int symbolWidth() const { return symbolDataWidth() + (horizontalDataRegions() * 2); }
int symbolHeight() const { return symbolDataHeight() + (verticalDataRegions() * 2); }
int matrixWidth() const { return _matrixWidth; }
int matrixHeight() const { return _matrixHeight; }
int codewordCount() const { return _dataCapacity + _errorCodewords; }
int interleavedBlockCount() const { return _rsBlockData > 0 ? _dataCapacity / _rsBlockData : 10; /* Symbol 144 */ }
int dataCapacity() const { return _dataCapacity; }
int errorCodewords() const { return _errorCodewords; }
int dataLengthForInterleavedBlock(int index) const
{
return _rsBlockData > 0 ? _rsBlockData : (index <= 8 ? 156 : 155); /* Symbol 144 */
}
int errorLengthForInterleavedBlock() const { return _rsBlockError; }
};
} // namespace ZXing::DataMatrix
```
|
/content/code_sandbox/core/src/datamatrix/DMSymbolInfo.h
|
objective-c
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 593
|
```objective-c
/*
*/
#pragma once
#include "Reader.h"
namespace ZXing::DataMatrix {
class Reader : public ZXing::Reader
{
public:
using ZXing::Reader::Reader;
Barcode decode(const BinaryBitmap& image) const override;
#ifdef __cpp_impl_coroutine
Barcodes decode(const BinaryBitmap& image, int maxSymbols) const override;
#endif
};
} // namespace ZXing::DataMatrix
```
|
/content/code_sandbox/core/src/datamatrix/DMReader.h
|
objective-c
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 86
|
```c++
/*
*/
#include "DMSymbolInfo.h"
#include "ZXAlgorithms.h"
#include "ZXTestSupport.h"
#include <cstddef>
#include <stdexcept>
namespace ZXing::DataMatrix {
static constexpr const SymbolInfo PROD_SYMBOLS[] = {
{ false, 3, 5, 8, 8, 1 },
{ false, 5, 7, 10, 10, 1 },
{ true, 5, 7, 16, 6, 1 },
{ false, 8, 10, 12, 12, 1 },
{ true, 10, 11, 14, 6, 2 },
{ false, 12, 12, 14, 14, 1 },
{ true, 16, 14, 24, 10, 1 },
{ false, 18, 14, 16, 16, 1 },
{ false, 22, 18, 18, 18, 1 },
{ true, 22, 18, 16, 10, 2 },
{ false, 30, 20, 20, 20, 1 },
{ true, 32, 24, 16, 14, 2 },
{ false, 36, 24, 22, 22, 1 },
{ false, 44, 28, 24, 24, 1 },
{ true, 49, 28, 22, 14, 2 },
{ false, 62, 36, 14, 14, 4 },
{ false, 86, 42, 16, 16, 4 },
{ false, 114, 48, 18, 18, 4 },
{ false, 144, 56, 20, 20, 4 },
{ false, 174, 68, 22, 22, 4 },
{ false, 204, 84, 24, 24, 4, 102, 42 },
{ false, 280, 112, 14, 14, 16, 140, 56 },
{ false, 368, 144, 16, 16, 16, 92, 36 },
{ false, 456, 192, 18, 18, 16, 114, 48 },
{ false, 576, 224, 20, 20, 16, 144, 56 },
{ false, 696, 272, 22, 22, 16, 174, 68 },
{ false, 816, 336, 24, 24, 16, 136, 56 },
{ false, 1050, 408, 18, 18, 36, 175, 68 },
{ false, 1304, 496, 20, 20, 36, 163, 62 },
{ false, 1558, 620, 22, 22, 36, -1, 62 },
};
static const SymbolInfo* s_symbols = PROD_SYMBOLS;
static ZXING_IF_NOT_TEST(const) size_t s_symbolCount = Size(PROD_SYMBOLS);
#ifdef ZXING_BUILD_FOR_TEST
ZXING_EXPORT_TEST_ONLY
void OverrideSymbolSet(const SymbolInfo* symbols, size_t count)
{
s_symbols = symbols;
s_symbolCount = count;
}
ZXING_EXPORT_TEST_ONLY
void UseDefaultSymbolSet()
{
s_symbols = PROD_SYMBOLS;
s_symbolCount = Size(PROD_SYMBOLS);
}
#endif // ZXING_BUILD_FOR_TEST
const SymbolInfo *
SymbolInfo::Lookup(int dataCodewords)
{
return Lookup(dataCodewords, SymbolShape::NONE);
}
const SymbolInfo *
SymbolInfo::Lookup(int dataCodewords, SymbolShape shape)
{
return Lookup(dataCodewords, shape, -1, -1, -1, -1);
}
const SymbolInfo *
SymbolInfo::Lookup(int dataCodewords, bool allowRectangular)
{
return Lookup(dataCodewords, allowRectangular ? SymbolShape::NONE : SymbolShape::SQUARE, -1, -1, -1, -1);
}
const SymbolInfo *
SymbolInfo::Lookup(int dataCodewords, SymbolShape shape, int minWidth, int minHeight, int maxWidth, int maxHeight)
{
for (size_t i = 0; i < s_symbolCount; ++i) {
auto& symbol = s_symbols[i];
if (shape == SymbolShape::SQUARE && symbol._rectangular) {
continue;
}
if (shape == SymbolShape::RECTANGLE && !symbol._rectangular) {
continue;
}
if (minWidth >= 0 && minHeight >= 0 && (symbol.symbolWidth() < minWidth || symbol.symbolHeight() < minHeight)) {
continue;
}
if (maxWidth >= 0 && maxHeight >= 0 && (symbol.symbolWidth() > maxWidth || symbol.symbolHeight() > maxHeight)) {
continue;
}
if (dataCodewords <= symbol._dataCapacity) {
return &symbol;
}
}
return nullptr;
}
int
SymbolInfo::horizontalDataRegions() const
{
switch (_dataRegions) {
case 1: return 1;
case 2: return 2;
case 4: return 2;
case 16: return 4;
case 36: return 6;
default: throw std::out_of_range("Cannot handle this number of data regions");
}
}
int
SymbolInfo::verticalDataRegions() const {
switch (_dataRegions) {
case 1: return 1;
case 2: return 1;
case 4: return 2;
case 16: return 4;
case 36: return 6;
default: throw std::out_of_range("Cannot handle this number of data regions");
}
}
} // namespace ZXing::DataMatrix
```
|
/content/code_sandbox/core/src/datamatrix/DMSymbolInfo.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 1,300
|
```c++
/*
*/
#include "DMWriter.h"
#include "BitMatrix.h"
#include "ByteArray.h"
#include "CharacterSet.h"
#include "DMBitLayout.h"
#include "DMECEncoder.h"
#include "DMHighLevelEncoder.h"
#include "DMSymbolInfo.h"
#include "Utf.h"
#include <stdexcept>
#include <string>
#include <utility>
namespace ZXing::DataMatrix {
/**
* Encode the given symbol info to a bit matrix.
*
* @param placement The DataMatrix placement.
* @param symbolInfo The symbol info to encode.
* @return The bit matrix generated.
*/
static BitMatrix EncodeLowLevel(const BitMatrix& placement, const SymbolInfo& symbolInfo) {
int symbolWidth = symbolInfo.symbolDataWidth();
int symbolHeight = symbolInfo.symbolDataHeight();
BitMatrix matrix(symbolInfo.symbolWidth(), symbolInfo.symbolHeight());
int matrixY = 0;
for (int y = 0; y < symbolHeight; y++) {
// Fill the top edge with alternate 0 / 1
int matrixX;
if ((y % symbolInfo.matrixHeight()) == 0) {
matrixX = 0;
for (int x = 0; x < matrix.width(); x++) {
matrix.set(matrixX, matrixY, (x % 2) == 0);
matrixX++;
}
matrixY++;
}
matrixX = 0;
for (int x = 0; x < symbolWidth; x++) {
// Fill the right edge with full 1
if ((x % symbolInfo.matrixWidth()) == 0) {
matrix.set(matrixX, matrixY, true);
matrixX++;
}
matrix.set(matrixX, matrixY, placement.get(x, y) == 1);
matrixX++;
// Fill the right edge with alternate 0 / 1
if ((x % symbolInfo.matrixWidth()) == symbolInfo.matrixWidth() - 1) {
matrix.set(matrixX, matrixY, (y % 2) == 0);
matrixX++;
}
}
matrixY++;
// Fill the bottom edge with full 1
if ((y % symbolInfo.matrixHeight()) == symbolInfo.matrixHeight() - 1) {
matrixX = 0;
for (int x = 0; x < matrix.width(); x++) {
matrix.set(matrixX, matrixY, true);
matrixX++;
}
matrixY++;
}
}
return matrix;
}
Writer::Writer() :
_shapeHint(SymbolShape::NONE),
_encoding(CharacterSet::Unknown)
{
}
BitMatrix
Writer::encode(const std::wstring& contents, int width, int height) const
{
if (contents.empty()) {
throw std::invalid_argument("Found empty contents");
}
if (width < 0 || height < 0) {
throw std::invalid_argument("Requested dimensions are invalid");
}
//1. step: Data encodation
auto encoded = Encode(contents, _encoding, _shapeHint, _minWidth, _minHeight, _maxWidth, _maxHeight);
const SymbolInfo* symbolInfo = SymbolInfo::Lookup(Size(encoded), _shapeHint, _minWidth, _minHeight, _maxWidth, _maxHeight);
if (symbolInfo == nullptr) {
throw std::invalid_argument("Can't find a symbol arrangement that matches the message. Data codewords: " + std::to_string(encoded.size()));
}
//2. step: ECC generation
EncodeECC200(encoded, *symbolInfo);
//3. step: Module placement in Matrix
BitMatrix symbolData = BitMatrixFromCodewords(encoded, symbolInfo->symbolDataWidth(), symbolInfo->symbolDataHeight());
//4. step: low-level encoding
BitMatrix result = EncodeLowLevel(symbolData, *symbolInfo);
//5. step: scale-up to requested size, minimum required quiet zone is 1
return Inflate(std::move(result), width, height, _quietZone);
}
BitMatrix Writer::encode(const std::string& contents, int width, int height) const
{
return encode(FromUtf8(contents), width, height);
}
} // namespace ZXing::DataMatrix
```
|
/content/code_sandbox/core/src/datamatrix/DMWriter.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 910
|
```c++
/*
*/
#include "BitMatrix.h"
#ifdef ZXING_EXPERIMENTAL_API
#include "WriteBarcode.h"
#else
#include "MultiFormatWriter.h"
#endif
#include <vector>
using namespace ZXing;
using namespace std::literals;
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include <stb_image_write.h>
#ifdef ZXING_EXPERIMENTAL_API
void savePng(ImageView iv, BarcodeFormat format)
{
stbi_write_png((ToString(format) + ".png"s).c_str(), iv.width(), iv.height(), iv.pixStride(), iv.data(), iv.rowStride());
}
#else
void savePng(const BitMatrix& matrix, BarcodeFormat format)
{
auto bitmap = ToMatrix<uint8_t>(matrix);
stbi_write_png((ToString(format) + ".png"s).c_str(), bitmap.width(), bitmap.height(), 1, bitmap.data(), 0);
}
#endif
int main()
{
std::string text = "path_to_url";
for (auto format : {
BarcodeFormat::Aztec,
BarcodeFormat::DataMatrix,
BarcodeFormat::PDF417,
BarcodeFormat::QRCode })
{
#ifdef ZXING_EXPERIMENTAL_API
savePng(CreateBarcodeFromText(text, format).symbol(), format);
#else
savePng(MultiFormatWriter(format).encode(text, 200, 200), format);
#endif
}
text = "012345678901234567890123456789";
using FormatSpecs = std::vector<std::pair<BarcodeFormat, size_t>>;
for (const auto& [format, length] : FormatSpecs({
// {BarcodeFormat::Codabar, 0},
{BarcodeFormat::Code39, 0},
{BarcodeFormat::Code93, 0},
{BarcodeFormat::Code128, 0},
{BarcodeFormat::EAN8, 7},
{BarcodeFormat::EAN13, 12},
{BarcodeFormat::ITF, 0},
{BarcodeFormat::UPCA, 11},
{BarcodeFormat::UPCE, 7} }))
{
auto input = length > 0 ? text.substr(0, length) : text;
#ifdef ZXING_EXPERIMENTAL_API
savePng(CreateBarcodeFromText(input, format).symbol(), format);
#else
savePng(MultiFormatWriter(format).encode(input, 100, 100), format);
#endif
}
}
```
|
/content/code_sandbox/test/blackbox/TestWriterMain.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 524
|
```objective-c
/*
*/
#pragma once
#include "ZXFilesystem.h"
#include <set>
#include <string>
namespace ZXing::Test {
int runBlackBoxTests(const fs::path& blackboxPath, const std::set<std::string>& includedTests);
} // ZXing::Test
```
|
/content/code_sandbox/test/blackbox/BlackboxTestRunner.h
|
objective-c
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 59
|
```c++
/*
*/
#include "BlackboxTestRunner.h"
#include "ImageLoader.h"
#include "ReadBarcode.h"
#include "ZXAlgorithms.h"
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <set>
using namespace ZXing;
using namespace ZXing::Test;
int getEnv(const char* name, int fallback = 0)
{
auto var = getenv(name);
return var ? atoi(var) : fallback;
}
int main(int argc, char** argv)
{
if (argc <= 1) {
std::cout << "Usage: " << argv[0] << " <test_path_prefix>" << std::endl;
return 0;
}
fs::path pathPrefix = argv[1];
if (Contains({".png", ".jpg", ".pgm", ".gif"}, pathPrefix.extension())) {
auto opts = ReaderOptions().setTryHarder(!getEnv("FAST", false)).setTryRotate(true).setIsPure(getEnv("IS_PURE"));
if (getenv("FORMATS"))
opts.setFormats(BarcodeFormatsFromString(getenv("FORMATS")));
int rotation = getEnv("ROTATION");
for (int i = 1; i < argc; ++i) {
Barcode barcode = ReadBarcode(ImageLoader::load(argv[i]).rotated(rotation), opts);
std::cout << argv[i] << ": ";
if (barcode.isValid())
std::cout << ToString(barcode.format()) << ": " << barcode.text() << "\n";
else
std::cout << "FAILED\n";
if (barcode.isValid() && getenv("WRITE_TEXT")) {
std::ofstream f(fs::path(argv[i]).replace_extension(".txt"));
f << barcode.text();
}
}
return 0;
} else {
std::set<std::string> includedTests;
for (int i = 2; i < argc; ++i) {
if (std::strlen(argv[i]) > 2 && argv[i][0] == '-' && argv[i][1] == 't') {
includedTests.insert(argv[i] + 2);
}
}
return runBlackBoxTests(pathPrefix, includedTests);
}
}
```
|
/content/code_sandbox/test/blackbox/TestReaderMain.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 472
|
```c++
/*
*/
#include "DMDetector.h"
#include "BitMatrix.h"
#include "BitMatrixCursor.h"
#include "ByteMatrix.h"
#include "DetectorResult.h"
#include "GridSampler.h"
#include "LogMatrix.h"
#include "Point.h"
#include "RegressionLine.h"
#include "ResultPoint.h"
#include "Scope.h"
#include "WhiteRectDetector.h"
#include <algorithm>
#include <array>
#include <cassert>
#include <cmath>
#include <cstdlib>
#include <map>
#include <utility>
#include <vector>
#ifndef PRINT_DEBUG
#define printf(...){}
#define printv(...){}
#else
#define printv(fmt, vec) \
for (auto v : vec) \
printf(fmt, v); \
printf("\n");
#endif
namespace ZXing::DataMatrix {
/**
* The following code is the 'old' code by Sean Owen based on the Java upstream project.
* It looks for a white rectangle, then cuts the corners until it hits a black pixel, which
* results in 4 corner points. Then it determines the dimension by counting transitions
* between the upper and right corners and samples the grid.
* This code has several limitations compared to the new code below but has one advantage:
* it works on high resolution scans with noisy/rippled black/white-edges and potentially
* on partly occluded locator patterns (the surrounding border of modules/pixels). It is
* therefore kept as a fall-back.
*/
/**
* Simply encapsulates two points and a number of transitions between them.
*/
struct ResultPointsAndTransitions
{
const ResultPoint* from;
const ResultPoint* to;
int transitions;
};
/**
* Counts the number of black/white transitions between two points, using something like Bresenham's algorithm.
*/
static ResultPointsAndTransitions TransitionsBetween(const BitMatrix& image, const ResultPoint& from,
const ResultPoint& to)
{
// See QR Code Detector, sizeOfBlackWhiteBlackRun()
int fromX = static_cast<int>(from.x());
int fromY = static_cast<int>(from.y());
int toX = static_cast<int>(to.x());
int toY = static_cast<int>(to.y());
bool steep = std::abs(toY - fromY) > std::abs(toX - fromX);
if (steep) {
std::swap(fromX, fromY);
std::swap(toX, toY);
}
int dx = std::abs(toX - fromX);
int dy = std::abs(toY - fromY);
int error = -dx / 2;
int ystep = fromY < toY ? 1 : -1;
int xstep = fromX < toX ? 1 : -1;
int transitions = 0;
bool inBlack = image.get(steep ? fromY : fromX, steep ? fromX : fromY);
for (int x = fromX, y = fromY; x != toX; x += xstep) {
bool isBlack = image.get(steep ? y : x, steep ? x : y);
if (isBlack != inBlack) {
transitions++;
inBlack = isBlack;
}
error += dy;
if (error > 0) {
if (y == toY) {
break;
}
y += ystep;
error -= dx;
}
}
return ResultPointsAndTransitions{ &from, &to, transitions };
}
static bool IsValidPoint(const ResultPoint& p, int imgWidth, int imgHeight)
{
return p.x() >= 0 && p.x() < imgWidth && p.y() > 0 && p.y() < imgHeight;
}
template <typename T>
static float RoundToNearestF(T x)
{
return static_cast<float>(std::round(x));
}
/**
* Calculates the position of the white top right module using the output of the rectangle detector
* for a rectangular matrix
*/
static bool CorrectTopRightRectangular(const BitMatrix& image, const ResultPoint& bottomLeft,
const ResultPoint& bottomRight, const ResultPoint& topLeft,
const ResultPoint& topRight, int dimensionTop, int dimensionRight,
ResultPoint& result)
{
float corr = RoundToNearestF(distance(bottomLeft, bottomRight)) / static_cast<float>(dimensionTop);
float norm = RoundToNearestF(distance(topLeft, topRight));
float cos = (topRight.x() - topLeft.x()) / norm;
float sin = (topRight.y() - topLeft.y()) / norm;
ResultPoint c1(topRight.x() + corr*cos, topRight.y() + corr*sin);
corr = RoundToNearestF(distance(bottomLeft, topLeft)) / (float)dimensionRight;
norm = RoundToNearestF(distance(bottomRight, topRight));
cos = (topRight.x() - bottomRight.x()) / norm;
sin = (topRight.y() - bottomRight.y()) / norm;
ResultPoint c2(topRight.x() + corr*cos, topRight.y() + corr*sin);
if (!IsValidPoint(c1, image.width(), image.height())) {
if (IsValidPoint(c2, image.width(), image.height())) {
result = c2;
return true;
}
return false;
}
if (!IsValidPoint(c2, image.width(), image.height())) {
result = c1;
return true;
}
int l1 = std::abs(dimensionTop - TransitionsBetween(image, topLeft, c1).transitions) +
std::abs(dimensionRight - TransitionsBetween(image, bottomRight, c1).transitions);
int l2 = std::abs(dimensionTop - TransitionsBetween(image, topLeft, c2).transitions) +
std::abs(dimensionRight - TransitionsBetween(image, bottomRight, c2).transitions);
result = l1 <= l2 ? c1 : c2;
return true;
}
/**
* Calculates the position of the white top right module using the output of the rectangle detector
* for a square matrix
*/
static ResultPoint CorrectTopRight(const BitMatrix& image, const ResultPoint& bottomLeft, const ResultPoint& bottomRight,
const ResultPoint& topLeft, const ResultPoint& topRight, int dimension)
{
float corr = RoundToNearestF(distance(bottomLeft, bottomRight)) / (float)dimension;
float norm = RoundToNearestF(distance(topLeft, topRight));
float cos = (topRight.x() - topLeft.x()) / norm;
float sin = (topRight.y() - topLeft.y()) / norm;
ResultPoint c1(topRight.x() + corr * cos, topRight.y() + corr * sin);
corr = RoundToNearestF(distance(bottomLeft, topLeft)) / (float)dimension;
norm = RoundToNearestF(distance(bottomRight, topRight));
cos = (topRight.x() - bottomRight.x()) / norm;
sin = (topRight.y() - bottomRight.y()) / norm;
ResultPoint c2(topRight.x() + corr * cos, topRight.y() + corr * sin);
if (!IsValidPoint(c1, image.width(), image.height())) {
if (!IsValidPoint(c2, image.width(), image.height()))
return topRight;
return c2;
}
if (!IsValidPoint(c2, image.width(), image.height()))
return c1;
int l1 = std::abs(TransitionsBetween(image, topLeft, c1).transitions -
TransitionsBetween(image, bottomRight, c1).transitions);
int l2 = std::abs(TransitionsBetween(image, topLeft, c2).transitions -
TransitionsBetween(image, bottomRight, c2).transitions);
return l1 <= l2 ? c1 : c2;
}
static DetectorResult SampleGrid(const BitMatrix& image, const ResultPoint& topLeft, const ResultPoint& bottomLeft,
const ResultPoint& bottomRight, const ResultPoint& topRight, int width, int height)
{
return SampleGrid(image, width, height,
{Rectangle(width, height, 0.5), {topLeft, topRight, bottomRight, bottomLeft}});
}
/**
* Returns the z component of the cross product between vectors BC and BA.
*/
static float CrossProductZ(const ResultPoint& a, const ResultPoint& b, const ResultPoint& c)
{
return (c.x() - b.x())*(a.y() - b.y()) - (c.y() - b.y())*(a.x() - b.x());
}
/**
* Orders an array of three ResultPoints in an order [A,B,C] such that AB is less than AC
* and BC is less than AC, and the angle between BC and BA is less than 180 degrees.
*/
static void OrderByBestPatterns(const ResultPoint*& p0, const ResultPoint*& p1, const ResultPoint*& p2)
{
// Find distances between pattern centers
auto zeroOneDistance = distance(*p0, *p1);
auto oneTwoDistance = distance(*p1, *p2);
auto zeroTwoDistance = distance(*p0, *p2);
const ResultPoint* pointA;
const ResultPoint* pointB;
const ResultPoint* pointC;
// Assume one closest to other two is B; A and C will just be guesses at first
if (oneTwoDistance >= zeroOneDistance && oneTwoDistance >= zeroTwoDistance) {
pointB = p0;
pointA = p1;
pointC = p2;
}
else if (zeroTwoDistance >= oneTwoDistance && zeroTwoDistance >= zeroOneDistance) {
pointB = p1;
pointA = p0;
pointC = p2;
}
else {
pointB = p2;
pointA = p0;
pointC = p1;
}
// Use cross product to figure out whether A and C are correct or flipped.
// This asks whether BC x BA has a positive z component, which is the arrangement
// we want for A, B, C. If it's negative, then we've got it flipped around and
// should swap A and C.
if (CrossProductZ(*pointA, *pointB, *pointC) < 0.0f) {
std::swap(pointA, pointC);
}
p0 = pointA;
p1 = pointB;
p2 = pointC;
}
static DetectorResult DetectOld(const BitMatrix& image)
{
ResultPoint pointA, pointB, pointC, pointD;
if (!DetectWhiteRect(image, pointA, pointB, pointC, pointD))
return {};
// Point A and D are across the diagonal from one another,
// as are B and C. Figure out which are the solid black lines
// by counting transitions
std::array transitions = {
TransitionsBetween(image, pointA, pointB),
TransitionsBetween(image, pointA, pointC),
TransitionsBetween(image, pointB, pointD),
TransitionsBetween(image, pointC, pointD),
};
std::sort(transitions.begin(), transitions.end(),
[](const auto& a, const auto& b) { return a.transitions < b.transitions; });
// Sort by number of transitions. First two will be the two solid sides; last two
// will be the two alternating black/white sides
const auto& lSideOne = transitions[0];
const auto& lSideTwo = transitions[1];
// We accept at most 4 transisions inside the L pattern (i.e. 2 corruptions) to reduce false positive FormatErrors
if (lSideTwo.transitions > 2)
return {};
// Figure out which point is their intersection by tallying up the number of times we see the
// endpoints in the four endpoints. One will show up twice.
std::map<const ResultPoint*, int> pointCount;
pointCount[lSideOne.from] += 1;
pointCount[lSideOne.to] += 1;
pointCount[lSideTwo.from] += 1;
pointCount[lSideTwo.to] += 1;
const ResultPoint* bottomRight = nullptr;
const ResultPoint* bottomLeft = nullptr;
const ResultPoint* topLeft = nullptr;
for (const auto& [point, count] : pointCount) {
if (count == 2) {
bottomLeft = point; // this is definitely the bottom left, then -- end of two L sides
}
else {
// Otherwise it's either top left or bottom right -- just assign the two arbitrarily now
if (bottomRight == nullptr) {
bottomRight = point;
}
else {
topLeft = point;
}
}
}
if (bottomRight == nullptr || bottomLeft == nullptr || topLeft == nullptr)
return {};
// Bottom left is correct but top left and bottom right might be switched
// Use the dot product trick to sort them out
OrderByBestPatterns(bottomRight, bottomLeft, topLeft);
// Which point didn't we find in relation to the "L" sides? that's the top right corner
const ResultPoint* topRight;
if (pointCount.find(&pointA) == pointCount.end()) {
topRight = &pointA;
}
else if (pointCount.find(&pointB) == pointCount.end()) {
topRight = &pointB;
}
else if (pointCount.find(&pointC) == pointCount.end()) {
topRight = &pointC;
}
else {
topRight = &pointD;
}
// Next determine the dimension by tracing along the top or right side and counting black/white
// transitions. Since we start inside a black module, we should see a number of transitions
// equal to 1 less than the code dimension. Well, actually 2 less, because we are going to
// end on a black module:
// The top right point is actually the corner of a module, which is one of the two black modules
// adjacent to the white module at the top right. Tracing to that corner from either the top left
// or bottom right should work here.
int dimensionTop = TransitionsBetween(image, *topLeft, *topRight).transitions;
int dimensionRight = TransitionsBetween(image, *bottomRight, *topRight).transitions;
if ((dimensionTop & 0x01) == 1) {
// it can't be odd, so, round... up?
dimensionTop++;
}
dimensionTop += 2;
if ((dimensionRight & 0x01) == 1) {
// it can't be odd, so, round... up?
dimensionRight++;
}
dimensionRight += 2;
if (dimensionTop < 10 || dimensionTop > 144 || dimensionRight < 8 || dimensionRight > 144 )
return {};
ResultPoint correctedTopRight;
// Rectangular symbols are 6x16, 6x28, 10x24, 10x32, 14x32, or 14x44. If one dimension is more
// than twice the other, it's certainly rectangular, but to cut a bit more slack we accept it as
// rectangular if the bigger side is at least 7/4 times the other:
if (4 * dimensionTop >= 7 * dimensionRight || 4 * dimensionRight >= 7 * dimensionTop) {
// The matrix is rectangular
if (!CorrectTopRightRectangular(image, *bottomLeft, *bottomRight, *topLeft, *topRight, dimensionTop,
dimensionRight, correctedTopRight)) {
correctedTopRight = *topRight;
}
dimensionTop = TransitionsBetween(image, *topLeft, correctedTopRight).transitions;
dimensionRight = TransitionsBetween(image, *bottomRight, correctedTopRight).transitions;
if ((dimensionTop & 0x01) == 1) {
// it can't be odd, so, round... up?
dimensionTop++;
}
if ((dimensionRight & 0x01) == 1) {
// it can't be odd, so, round... up?
dimensionRight++;
}
}
else {
// The matrix is square
int dimension = std::min(dimensionRight, dimensionTop);
// correct top right point to match the white module
correctedTopRight = CorrectTopRight(image, *bottomLeft, *bottomRight, *topLeft, *topRight, dimension);
// Redetermine the dimension using the corrected top right point
int dimensionCorrected = std::max(TransitionsBetween(image, *topLeft, correctedTopRight).transitions,
TransitionsBetween(image, *bottomRight, correctedTopRight).transitions);
dimensionCorrected++;
if ((dimensionCorrected & 0x01) == 1) {
dimensionCorrected++;
}
dimensionTop = dimensionRight = dimensionCorrected;
}
return SampleGrid(image, *topLeft, *bottomLeft, *bottomRight, correctedTopRight, dimensionTop, dimensionRight);
}
/**
* The following code is the 'new' one implemented by Axel Waggershauser and is working completely different.
* It is performing something like a (back) trace search along edges through the bit matrix, first looking for
* the 'L'-pattern, then tracing the black/white borders at the top/right. Advantages over the old code are:
* * works with lower resolution scans (around 2 pixel per module), due to sub-pixel precision grid placement
* * works with real-world codes that have just one module wide quiet-zone (which is perfectly in spec)
*/
class DMRegressionLine : public RegressionLine
{
template <typename Container, typename Filter>
static double average(const Container& c, Filter f)
{
double sum = 0;
int num = 0;
for (const auto& v : c)
if (f(v)) {
sum += v;
++num;
}
return sum / num;
}
public:
void reverse() { std::reverse(_points.begin(), _points.end()); }
double modules(PointF beg, PointF end)
{
assert(_points.size() > 3);
// re-evaluate and filter out all points too far away. required for the gapSizes calculation.
evaluate(1.2, true);
std::vector<double> gapSizes, modSizes;
gapSizes.reserve(_points.size());
// calculate the distance between the points projected onto the regression line
for (size_t i = 1; i < _points.size(); ++i)
gapSizes.push_back(distance(project(_points[i]), project(_points[i - 1])));
// calculate the (expected average) distance of two adjacent pixels
auto unitPixelDist = ZXing::length(bresenhamDirection(_points.back() - _points.front()));
// calculate the width of 2 modules (first black pixel to first black pixel)
double sumFront = distance(beg, project(_points.front())) - unitPixelDist;
double sumBack = 0; // (last black pixel to last black pixel)
for (auto dist : gapSizes) {
if (dist > 1.9 * unitPixelDist)
modSizes.push_back(std::exchange(sumBack, 0.0));
sumFront += dist;
sumBack += dist;
if (dist > 1.9 * unitPixelDist)
modSizes.push_back(std::exchange(sumFront, 0.0));
}
if (modSizes.empty())
return 0;
modSizes.push_back(sumFront + distance(end, project(_points.back())));
modSizes.front() = 0; // the first element is an invalid sumBack value, would be pop_front() if vector supported this
auto lineLength = distance(beg, end) - unitPixelDist;
auto [iMin, iMax] = std::minmax_element(modSizes.begin() + 1, modSizes.end());
auto meanModSize = average(modSizes, [](double dist){ return dist > 0; });
printf("unit pixel dist: %.1f\n", unitPixelDist);
printf("lineLength: %.1f, meanModSize: %.1f (min: %.1f, max: %.1f), gaps: %lu\n", lineLength, meanModSize, *iMin, *iMax,
modSizes.size());
printv("%.1f ", modSizes);
if (*iMax > 2 * *iMin) {
for (int i = 1; i < Size(modSizes) - 2; ++i) {
if (modSizes[i] > 0 && modSizes[i] + modSizes[i + 2] < meanModSize * 1.4)
modSizes[i] += std::exchange(modSizes[i + 2], 0);
else if (modSizes[i] > meanModSize * 1.6)
modSizes[i] = 0;
}
printv("%.1f ", modSizes);
meanModSize = average(modSizes, [](double dist) { return dist > 0; });
}
printf("post filter meanModSize: %.1f\n", meanModSize);
return lineLength / meanModSize;
}
bool truncateIfLShape()
{
auto lenThis = Size(_points);
auto lineAB = RegressionLine(_points.front(), _points.back());
if (lenThis < 16 || lineAB.distance(_points[lenThis / 2]) < 5)
return false;
auto maxP = _points.begin();
double maxD = 0.0;
for (auto p = _points.begin(); p != _points.end(); ++p) {
auto d = lineAB.distance(*p);
if (d > maxD) {
maxP = p;
maxD = d;
}
}
auto lenL = distance(_points.front(), *maxP) - 1;
auto lenB = distance(*maxP, _points.back()) - 1;
if (maxD < std::min(lenL, lenB) / 2)
return false;
setDirectionInward(_points.back() - *maxP);
_points.resize(std::distance(_points.begin(), maxP) - 1);
return true;
}
};
class EdgeTracer : public BitMatrixCursorF
{
enum class StepResult { FOUND, OPEN_END, CLOSED_END };
// force this function inline to allow the compiler optimize for the maxStepSize==1 case in traceLine()
// this can result in a 10% speedup of the falsepositive use case when build with c++20
#if defined(__clang__) || defined(__GNUC__)
inline __attribute__((always_inline))
#elif defined(_MSC_VER)
__forceinline
#endif
StepResult traceStep(PointF dEdge, int maxStepSize, bool goodDirection)
{
dEdge = mainDirection(dEdge);
for (int breadth = 1; breadth <= (maxStepSize == 1 ? 2 : (goodDirection ? 1 : 3)); ++breadth)
for (int step = 1; step <= maxStepSize; ++step)
for (int i = 0; i <= 2*(step/4+1) * breadth; ++i) {
auto pEdge = p + step * d + (i&1 ? (i+1)/2 : -i/2) * dEdge;
log(pEdge);
if (!blackAt(pEdge + dEdge))
continue;
// found black pixel -> go 'outward' until we hit the b/w border
for (int j = 0; j < std::max(maxStepSize, 3) && isIn(pEdge); ++j) {
if (whiteAt(pEdge)) {
// if we are not making any progress, we still have another endless loop bug
assert(p != centered(pEdge));
p = centered(pEdge);
if (history && maxStepSize == 1) {
if (history->get(PointI(p)) == state)
return StepResult::CLOSED_END;
history->set(PointI(p), state);
}
return StepResult::FOUND;
}
pEdge = pEdge - dEdge;
if (blackAt(pEdge - d))
pEdge = pEdge - d;
log(pEdge);
}
// no valid b/w border found within reasonable range
return StepResult::CLOSED_END;
}
return StepResult::OPEN_END;
}
public:
ByteMatrix* history = nullptr;
int state = 0;
using BitMatrixCursorF::BitMatrixCursor;
bool updateDirectionFromOrigin(PointF origin)
{
auto old_d = d;
setDirection(p - origin);
// if the new direction is pointing "backward", i.e. angle(new, old) > 90 deg -> break
if (dot(d, old_d) < 0)
return false;
// make sure d stays in the same quadrant to prevent an infinite loop
if (std::abs(d.x) == std::abs(d.y))
d = mainDirection(old_d) + 0.99f * (d - mainDirection(old_d));
else if (mainDirection(d) != mainDirection(old_d))
d = mainDirection(old_d) + 0.99f * mainDirection(d);
return true;
}
bool updateDirectionFromLine(RegressionLine& line)
{
return line.evaluate(1.5) && updateDirectionFromOrigin(p - line.project(p) + line.points().front());
}
bool updateDirectionFromLineCentroid(RegressionLine& line)
{
// Basically a faster, less accurate version of the above without the line evaluation
return updateDirectionFromOrigin(line.centroid());
}
bool traceLine(PointF dEdge, RegressionLine& line)
{
line.setDirectionInward(dEdge);
do {
log(p);
line.add(p);
if (line.points().size() % 50 == 10 && !updateDirectionFromLineCentroid(line))
return false;
auto stepResult = traceStep(dEdge, 1, line.isValid());
if (stepResult != StepResult::FOUND)
return stepResult == StepResult::OPEN_END && line.points().size() > 1 && updateDirectionFromLineCentroid(line);
} while (true);
}
bool traceGaps(PointF dEdge, RegressionLine& line, int maxStepSize, const RegressionLine& finishLine = {}, double minDist = 0)
{
line.setDirectionInward(dEdge);
int gaps = 0, steps = 0, maxStepsPerGap = maxStepSize;
PointF lastP;
do {
// detect an endless loop (lack of progress). if encountered, please report.
// this fixes a deadlock in falsepositives-1/#570.png and the regression in #574
if (p == std::exchange(lastP, p) || steps++ > (gaps == 0 ? 2 : gaps + 1) * maxStepsPerGap)
return false;
log(p);
// if we drifted too far outside of the code, break
if (line.isValid() && line.signedDistance(p) < -5 && (!line.evaluate() || line.signedDistance(p) < -5))
return false;
// if we are drifting towards the inside of the code, pull the current position back out onto the line
if (line.isValid() && line.signedDistance(p) > 3) {
// The current direction d and the line we are tracing are supposed to be roughly parallel.
// In case the 'go outward' step in traceStep lead us astray, we might end up with a line
// that is almost perpendicular to d. Then the back-projection below can result in an
// endless loop. Break if the angle between d and line is greater than 45 deg.
if (std::abs(dot(normalized(d), line.normal())) > 0.7) // thresh is approx. sin(45 deg)
return false;
// re-evaluate line with all the points up to here before projecting
if (!line.evaluate(1.5))
return false;
auto np = line.project(p);
// make sure we are making progress even when back-projecting:
// consider a 90deg corner, rotated 45deg. we step away perpendicular from the line and get
// back projected where we left off the line.
// The 'while' instead of 'if' was introduced to fix the issue with #245. It turns out that
// np can actually be behind the projection of the last line point and we need 2 steps in d
// to prevent a dead lock. see #245.png
while (distance(np, line.project(line.points().back())) < 1)
np = np + d;
p = centered(np);
}
else {
auto curStep = line.points().empty() ? PointF() : p - line.points().back();
auto stepLengthInMainDir = line.points().empty() ? 0.0 : dot(mainDirection(d), curStep);
line.add(p);
if (stepLengthInMainDir > 1 || maxAbsComponent(curStep) >= 2) {
++gaps;
if (gaps >= 2 || line.points().size() > 5) {
if (!updateDirectionFromLine(line))
return false;
// check if the first half of the top-line trace is complete.
// the minimum code size is 10x10 -> every code has at least 4 gaps
if (minDist && gaps >= 4 && distance(p, line.points().front()) > minDist) {
// undo the last insert, it will be inserted again after the restart
line.pop_back();
--gaps;
return true;
}
}
} else if (gaps == 0 && Size(line.points()) >= 2 * maxStepSize) {
return false; // no point in following a line that has no gaps
}
}
if (finishLine.isValid())
UpdateMin(maxStepSize, static_cast<int>(finishLine.signedDistance(p)));
auto stepResult = traceStep(dEdge, maxStepSize, line.isValid());
if (stepResult != StepResult::FOUND)
// we are successful iff we found an open end across a valid finishLine
return stepResult == StepResult::OPEN_END && finishLine.isValid() &&
static_cast<int>(finishLine.signedDistance(p)) <= maxStepSize + 1;
} while (true);
}
bool traceCorner(PointF dir, PointF& corner)
{
step();
log(p);
corner = p;
std::swap(d, dir);
traceStep(-1 * dir, 2, false);
printf("turn: %.0f x %.0f -> %.2f, %.2f\n", p.x, p.y, d.x, d.y);
return isIn(corner) && isIn(p);
}
bool moveToNextWhiteAfterBlack()
{
assert(std::abs(d.x + d.y) == 1);
FastEdgeToEdgeCounter e2e(BitMatrixCursorI(*img, PointI(p), PointI(d)));
int steps = e2e.stepToNextEdge(INT_MAX);
if (!steps)
return false;
step(steps);
if(isWhite())
return true;
steps = e2e.stepToNextEdge(INT_MAX);
if (!steps)
return false;
return step(steps);
}
};
static DetectorResult Scan(EdgeTracer& startTracer, std::array<DMRegressionLine, 4>& lines)
{
while (startTracer.moveToNextWhiteAfterBlack()) {
log(startTracer.p);
PointF tl, bl, br, tr;
auto& [lineL, lineB, lineR, lineT] = lines;
for (auto& l : lines)
l.reset();
#ifdef PRINT_DEBUG
SCOPE_EXIT([&] {
for (auto& l : lines)
log(l.points());
});
# define CHECK(A) if (!(A)) { printf("broke at %d\n", __LINE__); continue; }
#else
# define CHECK(A) if(!(A)) continue
#endif
auto t = startTracer;
PointF up, right;
// follow left leg upwards
t.turnRight();
t.state = 1;
CHECK(t.traceLine(t.right(), lineL));
CHECK(t.traceCorner(t.right(), tl));
lineL.reverse();
auto tlTracer = t;
// follow left leg downwards
t = startTracer;
t.state = 1;
t.setDirection(tlTracer.right());
CHECK(t.traceLine(t.left(), lineL));
// check if lineL is L-shaped -> truncate the lower leg and set t to just before the corner
if (lineL.truncateIfLShape())
t.p = lineL.points().back();
t.updateDirectionFromOrigin(tl);
up = t.back();
CHECK(t.traceCorner(t.left(), bl));
// follow bottom leg right
t.state = 2;
CHECK(t.traceLine(t.left(), lineB));
t.updateDirectionFromOrigin(bl);
right = t.front();
CHECK(t.traceCorner(t.left(), br));
auto lenL = distance(tl, bl) - 1;
auto lenB = distance(bl, br) - 1;
CHECK(lenL >= 8 && lenB >= 10 && lenB >= lenL / 4 && lenB <= lenL * 18);
auto maxStepSize = static_cast<int>(lenB / 5 + 1); // datamatrix bottom dim is at least 10
// at this point we found a plausible L-shape and are now looking for the b/w pattern at the top and right:
// follow top row right 'half way' (at least 4 gaps), see traceGaps
tlTracer.setDirection(right);
CHECK(tlTracer.traceGaps(tlTracer.right(), lineT, maxStepSize, {}, lenB / 2));
maxStepSize = std::min(lineT.length() / 3, static_cast<int>(lenL / 5)) * 2;
// follow up until we reach the top line
t.setDirection(up);
t.state = 3;
CHECK(t.traceGaps(t.left(), lineR, maxStepSize, lineT));
CHECK(t.traceCorner(t.left(), tr));
auto lenT = distance(tl, tr) - 1;
auto lenR = distance(tr, br) - 1;
CHECK(std::abs(lenT - lenB) / lenB < 0.5 && std::abs(lenR - lenL) / lenL < 0.5 &&
lineT.points().size() >= 5 && lineR.points().size() >= 5);
// continue top row right until we cross the right line
CHECK(tlTracer.traceGaps(tlTracer.right(), lineT, maxStepSize, lineR));
printf("L: %.1f, %.1f ^ %.1f, %.1f > %.1f, %.1f (%d : %d : %d : %d)\n", bl.x, bl.y,
tl.x - bl.x, tl.y - bl.y, br.x - bl.x, br.y - bl.y, (int)lenL, (int)lenB, (int)lenT, (int)lenR);
for (auto* l : {&lineL, &lineB, &lineT, &lineR})
l->evaluate(1.0);
// find the bounding box corners of the code with sub-pixel precision by intersecting the 4 border lines
bl = intersect(lineB, lineL);
tl = intersect(lineT, lineL);
tr = intersect(lineT, lineR);
br = intersect(lineB, lineR);
int dimT, dimR;
double fracT, fracR;
auto splitDouble = [](double d, int* i, double* f) {
*i = std::isnormal(d) ? static_cast<int>(d + 0.5) : 0;
*f = std::isnormal(d) ? std::abs(d - *i) : INFINITY;
};
splitDouble(lineT.modules(tl, tr), &dimT, &fracT);
splitDouble(lineR.modules(br, tr), &dimR, &fracR);
// the dimension is 2x the number of black/white transitions
dimT *= 2;
dimR *= 2;
printf("L: %.1f, %.1f ^ %.1f, %.1f > %.1f, %.1f ^> %.1f, %.1f\n", bl.x, bl.y,
tl.x - bl.x, tl.y - bl.y, br.x - bl.x, br.y - bl.y, tr.x, tr.y);
printf("dim: %d x %d\n", dimT, dimR);
// if we have an almost square (invalid rectangular) data matrix dimension, we try to parse it by assuming a
// square. we use the dimension that is closer to an integral value. all valid rectangular symbols differ in
// their dimension by at least 10. Note: this is currently not required for the black-box tests to complete.
if (std::abs(dimT - dimR) < 10)
dimT = dimR = fracR < fracT ? dimR : dimT;
CHECK(dimT >= 10 && dimT <= 144 && dimR >= 8 && dimR <= 144);
auto movedTowardsBy = [](PointF a, PointF b1, PointF b2, auto d) {
return a + d * normalized(normalized(b1 - a) + normalized(b2 - a));
};
// shrink shape by half a pixel to go from center of white pixel outside of code to the edge between white and black
QuadrilateralF sourcePoints = {
movedTowardsBy(tl, tr, bl, 0.5f),
// move the tr point a little less because the jagged top and right line tend to be statistically slightly
// inclined toward the center anyway.
movedTowardsBy(tr, br, tl, 0.3f),
movedTowardsBy(br, bl, tr, 0.5f),
movedTowardsBy(bl, tl, br, 0.5f),
};
auto res = SampleGrid(*startTracer.img, dimT, dimR, PerspectiveTransform(Rectangle(dimT, dimR, 0), sourcePoints));
CHECK(res.isValid());
return res;
}
return {};
}
static DetectorResults DetectNew(const BitMatrix& image, bool tryHarder, bool tryRotate)
{
#ifdef PRINT_DEBUG
LogMatrixWriter lmw(log, image, 1, "dm-log.pnm");
// tryRotate = tryHarder = false;
#endif
// disable expensive multi-line scan to detect off-center symbols for now
#ifndef __cpp_impl_coroutine
tryHarder = false;
#endif
// a history log to remember where the tracing already passed by to prevent a later trace from doing the same work twice
ByteMatrix history;
if (tryHarder)
history = ByteMatrix(image.width(), image.height());
// instantiate RegressionLine objects outside of Scan function to prevent repetitive std::vector allocations
std::array<DMRegressionLine, 4> lines;
constexpr int minSymbolSize = 8 * 2; // minimum realistic size in pixel: 8 modules x 2 pixels per module
for (auto dir : {PointF{-1, 0}, {1, 0}, {0, -1}, {0, 1}}) {
auto center = PointI(image.width() / 2, image.height() / 2);
auto startPos = centered(center - center * dir + minSymbolSize / 2 * dir);
history.clear();
for (int i = 1;; ++i) {
EdgeTracer tracer(image, startPos, dir);
tracer.p += i / 2 * minSymbolSize * (i & 1 ? -1 : 1) * tracer.right();
if (tryHarder)
tracer.history = &history;
if (!tracer.isIn())
break;
#ifdef __cpp_impl_coroutine
DetectorResult res;
while (res = Scan(tracer, lines), res.isValid())
co_yield std::move(res);
#else
if (auto res = Scan(tracer, lines); res.isValid())
return res;
#endif
if (!tryHarder)
break; // only test center lines
}
if (!tryRotate)
break; // only test left direction
}
#ifndef __cpp_impl_coroutine
return {};
#endif
}
/**
* This method detects a code in a "pure" image -- that is, pure monochrome image
* which contains only an unrotated, unskewed, image of a code, with some optional white border
* around it. This is a specialized method that works exceptionally fast in this special
* case.
*/
static DetectorResult DetectPure(const BitMatrix& image)
{
int left, top, width, height;
if (!image.findBoundingBox(left, top, width, height, 8))
return {};
BitMatrixCursorI cur(image, {left, top}, {0, 1});
if (cur.countEdges(height - 1) != 0)
return {};
cur.turnLeft();
if (cur.countEdges(width - 1) != 0)
return {};
cur.turnLeft();
int dimR = cur.countEdges(height - 1) + 1;
cur.turnLeft();
int dimT = cur.countEdges(width - 1) + 1;
auto modSizeX = float(width) / dimT;
auto modSizeY = float(height) / dimR;
auto modSize = (modSizeX + modSizeY) / 2;
if (dimT % 2 != 0 || dimR % 2 != 0 || dimT < 10 || dimT > 144 || dimR < 8 || dimR > 144
|| std::abs(modSizeX - modSizeY) > 1
|| !image.isIn(PointF{left + modSizeX / 2 + (dimT - 1) * modSize, top + modSizeY / 2 + (dimR - 1) * modSize}))
return {};
int right = left + width - 1;
int bottom = top + height - 1;
// Now just read off the bits (this is a crop + subsample)
return {Deflate(image, dimT, dimR, top + modSizeY / 2, left + modSizeX / 2, modSize),
{{left, top}, {right, top}, {right, bottom}, {left, bottom}}};
}
DetectorResults Detect(const BitMatrix& image, bool tryHarder, bool tryRotate, bool isPure)
{
#ifdef __cpp_impl_coroutine
// First try the very fast DetectPure() path. Also because DetectNew() generally fails with pure module size 1 symbols
// TODO: implement a tryRotate version of DetectPure, see #590.
if (auto r = DetectPure(image); r.isValid())
co_yield std::move(r);
else if (!isPure) { // If r.isValid() then there is no point in looking for more (no-pure) symbols
bool found = false;
for (auto&& r : DetectNew(image, tryHarder, tryRotate)) {
found = true;
co_yield std::move(r);
}
if (!found && tryHarder) {
if (auto r = DetectOld(image); r.isValid())
co_yield std::move(r);
}
}
#else
auto result = DetectPure(image);
if (!result.isValid() && !isPure)
result = DetectNew(image, tryHarder, tryRotate);
if (!result.isValid() && tryHarder && !isPure)
result = DetectOld(image);
return result;
#endif
}
} // namespace ZXing::DataMatrix
```
|
/content/code_sandbox/core/src/datamatrix/DMDetector.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 9,649
|
```objective-c
/*
*/
#pragma once
#include "ImageView.h"
#include "ZXFilesystem.h"
namespace ZXing::Test::ImageLoader {
void clearCache();
const ImageView& load(const fs::path& imgPath);
} // namespace ZXing::Test::ImageLoader
```
|
/content/code_sandbox/test/blackbox/ImageLoader.h
|
objective-c
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 54
|
```objective-c
/*
*/
#pragma once
#if __has_include(<filesystem>)
# include <filesystem>
# ifdef __cpp_lib_filesystem
namespace fs = std::filesystem;
# endif
#endif
#if !defined(__cpp_lib_filesystem) && __has_include(<experimental/filesystem>)
# include <experimental/filesystem>
# ifdef __cpp_lib_experimental_filesystem
namespace fs = std::experimental::filesystem;
# endif
#endif
#if !defined(__cpp_lib_filesystem) && !defined(__cpp_lib_experimental_filesystem)
# error need standard filesystem library from c++-17 or the Filesystem TR
#endif
// compiling this with clang (e.g. version 6) might require linking against libc++experimental.a or libc++fs.a.
// E.g.: CMAKE_EXE_LINKER_FLAGS = -L/usr/local/Cellar/llvm/6.0.1/lib -lc++experimental
```
|
/content/code_sandbox/test/blackbox/ZXFilesystem.h
|
objective-c
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 195
|
```c++
/*
*/
#include "ImageLoader.h"
#include "BinaryBitmap.h"
#include "ImageView.h"
#include <array>
#include <map>
#include <memory>
#include <stdexcept>
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
namespace ZXing::Test {
class STBImage : public ImageView
{
std::unique_ptr<stbi_uc[], void (*)(void*)> _memory;
public:
STBImage() : ImageView(), _memory(nullptr, stbi_image_free) {}
void load(const fs::path& imgPath)
{
int width, height, channels;
_memory.reset(stbi_load(imgPath.string().c_str(), &width, &height, &channels, 0));
if (_memory == nullptr)
throw std::runtime_error("Failed to read image: " + imgPath.string() + " (" + stbi_failure_reason() + ")");
auto ImageFormatFromChannels = std::array{ImageFormat::None, ImageFormat::Lum, ImageFormat::LumA, ImageFormat::RGB, ImageFormat::RGBA};
ImageView::operator=({_memory.get(), width, height, ImageFormatFromChannels.at(channels)});
// preconvert from RGB -> Lum to do this only once instead of for each rotation
if (_format == ImageFormat::RGB) {
auto* img = _memory.get();
for (int i = 0; i < width * height; ++i)
img[i] = RGBToLum(img[3 * i + 0], img[3 * i + 1], img[3 * i + 2]);
ImageView::operator=({_memory.get(), width, height, ImageFormat::Lum});
}
}
operator bool() const { return _data; }
};
std::map<fs::path, STBImage> cache;
void ImageLoader::clearCache()
{
cache.clear();
}
const ImageView& ImageLoader::load(const fs::path& imgPath)
{
thread_local std::unique_ptr<BinaryBitmap> localAverage, threshold;
auto& binImg = cache[imgPath];
if (!binImg)
binImg.load(imgPath);
return binImg;
}
} // namespace ZXing::Test
```
|
/content/code_sandbox/test/blackbox/ImageLoader.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 469
|
```c++
/*
*/
#include "BarcodeFormat.h"
#include "gtest/gtest.h"
#include <stdexcept>
#include <vector>
using namespace ZXing;
TEST(BarcodeFormatTest, BarcodeFormat)
{
using namespace std::literals;
EXPECT_EQ(ToString(BarcodeFormat::QRCode), "QRCode"s);
EXPECT_EQ(ToString(BarcodeFormat::None), "None"s);
EXPECT_EQ(ToString(BarcodeFormat::DataMatrix | BarcodeFormat::EAN13), "DataMatrix|EAN-13");
EXPECT_EQ(BarcodeFormat::EAN8, BarcodeFormatFromString("EAN_8"));
EXPECT_EQ(BarcodeFormat::EAN8, BarcodeFormatFromString("EAN-8"));
EXPECT_EQ(BarcodeFormat::EAN8, BarcodeFormatFromString("EAN8"));
EXPECT_EQ(BarcodeFormat::EAN8, BarcodeFormatFromString("ean8"));
EXPECT_EQ(BarcodeFormat::None, BarcodeFormatFromString("invalid-string"));
EXPECT_EQ(BarcodeFormat::None, BarcodeFormatsFromString(""));
auto formats = BarcodeFormat::EAN8 | BarcodeFormat::ITF;
EXPECT_EQ(formats, BarcodeFormatsFromString("EAN-8,ITF"));
EXPECT_EQ(formats, BarcodeFormatsFromString("EAN-8, ITF"));
EXPECT_EQ(formats, BarcodeFormatsFromString("EAN-8 ITF"));
EXPECT_EQ(formats, BarcodeFormatsFromString("ean8|itf"));
auto f1 = std::vector<BarcodeFormat>(formats.begin(), formats.end());
auto f2 = std::vector<BarcodeFormat>{BarcodeFormat::EAN8, BarcodeFormat::ITF};
EXPECT_EQ(f1, f2);
EXPECT_THROW(BarcodeFormatsFromString("ITF, invalid-string"), std::invalid_argument);
}
```
|
/content/code_sandbox/test/unit/BarcodeFormatTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 352
|
```c++
/*
*/
#include "Utf.h"
#include "gtest/gtest.h"
using namespace ZXing;
#if __cplusplus > 201703L
std::string EscapeNonGraphical(const char8_t* utf8)
{
return EscapeNonGraphical(reinterpret_cast<const char*>(utf8));
}
#endif
TEST(TextUtfEncodingTest, EscapeNonGraphical)
{
EXPECT_EQ(EscapeNonGraphical(u8"\u00B6\u0416"), "");
EXPECT_EQ(EscapeNonGraphical(u8"\x01\x1F\x7F"), "<SOH><US><DEL>");
EXPECT_EQ(EscapeNonGraphical(u8"\u0080\u009F"), "<U+80><U+9F>");
EXPECT_EQ(EscapeNonGraphical(u8"\u00A0"), "<U+A0>"); // NO-BREAK space (nbsp)
EXPECT_EQ(EscapeNonGraphical(u8"\u2007"), "<U+2007>"); // NO-BREAK space (numsp)
EXPECT_EQ(EscapeNonGraphical(u8"\u2000"), "<U+2000>"); // Space char (nqsp)
EXPECT_EQ(EscapeNonGraphical(u8"\uFFFD"), "<U+FFFD>");
EXPECT_EQ(EscapeNonGraphical(u8"\uFFFF"), "<U+FFFF>");
}
TEST(TextUtfEncodingTest, FromUtf8)
{
EXPECT_EQ(FromUtf8(u8"\U00010000"), L"\U00010000");
EXPECT_EQ(FromUtf8(u8"\U00010FFF"), L"\U00010FFF");
EXPECT_EQ(FromUtf8("A\xE8\x80\xBFG"), L"A\u803FG"); // U+803F
// EXPECT_EQ(FromUtf8("A\xE8\x80\xBF\x80G"), L"A\u803FG"); // Bad UTF-8 (extra continuation byte)
// EXPECT_EQ(FromUtf8("A\xE8\x80\xC0G"), L"AG"); // Bad UTF-8 (non-continuation byte)
// EXPECT_EQ(FromUtf8("A\xE8\x80G"), L"AG"); // Bad UTF-8 (missing continuation byte)
// EXPECT_EQ(FromUtf8("A\xE8G"), L"AG"); // Bad UTF-8 (missing continuation bytes)
// EXPECT_EQ(FromUtf8("A\xED\xA0\x80G"), L"AG"); // Bad UTF-8 (unpaired high surrogate U+D800)
}
```
|
/content/code_sandbox/test/unit/TextUtfEncodingTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 525
|
```c++
/*
*/
#include "gtest/gtest.h"
// see path_to_url#sanitizer-integration
extern "C"
{
void __ubsan_on_report() { FAIL() << "Encountered an undefined behavior sanitizer error"; }
void __asan_on_error() { FAIL() << "Encountered an address sanitizer error"; }
void __tsan_on_report() { FAIL() << "Encountered a thread sanitizer error"; }
} // extern "C"
```
|
/content/code_sandbox/test/unit/SanitizerSupport.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 94
|
```c++
/*
*/
#include "BlackboxTestRunner.h"
#include "ImageLoader.h"
#include "ReadBarcode.h"
#include "Utf.h"
#include "ZXAlgorithms.h"
#include <fmt/core.h>
#include <fmt/ostream.h>
#include <chrono>
#include <exception>
#include <fstream>
#include <map>
#include <optional>
#include <set>
#include <sstream>
#include <string>
#include <string_view>
#include <vector>
namespace ZXing::Test {
namespace {
struct PureTag {} pure;
struct TestCase
{
struct TC
{
std::string name = {};
int minPassCount = 0; // The number of images which must decode for the test to pass.
int maxMisreads = 0; // Maximum number of successfully read images with the wrong contents.
std::set<fs::path> notDetectedFiles = {};
std::map<fs::path, std::string> misReadFiles = {};
};
TC tc[2] = {};
int rotation = 0; // The rotation in degrees clockwise to use for this test.
TestCase(int mntf, int mnts, int mmf, int mms, int r) : tc{{"fast", mntf, mmf}, {"slow", mnts, mms}}, rotation(r) {}
TestCase(int mntf, int mnts, int r) : TestCase(mntf, mnts, 0, 0, r) {}
TestCase(int mntp, int mmp, PureTag) : tc{{"pure", mntp, mmp}} {}
};
struct FalsePositiveTestCase
{
int maxAllowed; // Maximum number of images which can fail due to successfully reading the wrong contents
int rotation; // The rotation in degrees clockwise to use for this test.
};
}
// Helper for `compareResult()` - map `key` to Barcode property, converting value to std::string
static std::string getBarcodeValue(const Barcode& barcode, const std::string& key)
{
if (key == "contentType")
return ToString(barcode.contentType());
if (key == "ecLevel")
return barcode.ecLevel();
if (key == "orientation")
return std::to_string(barcode.orientation());
if (key == "symbologyIdentifier")
return barcode.symbologyIdentifier();
if (key == "sequenceSize")
return std::to_string(barcode.sequenceSize());
if (key == "sequenceIndex")
return std::to_string(barcode.sequenceIndex());
if (key == "sequenceId")
return barcode.sequenceId();
if (key == "isLastInSequence")
return barcode.isLastInSequence() ? "true" : "false";
if (key == "isPartOfSequence")
return barcode.isPartOfSequence() ? "true" : "false";
if (key == "isMirrored")
return barcode.isMirrored() ? "true" : "false";
if (key == "isInverted")
return barcode.isInverted() ? "true" : "false";
if (key == "readerInit")
return barcode.readerInit() ? "true" : "false";
return fmt::format("***Unknown key '{}'***", key);
}
// Read ".result.txt" file contents `expected` with lines "key=value" and compare to `actual`
static bool compareResult(const Barcode& barcode, const std::string& expected, std::string& actual)
{
bool ret = true;
actual.clear();
actual.reserve(expected.size());
std::stringstream expectedLines(expected);
std::string expectedLine;
while (std::getline(expectedLines, expectedLine)) {
if (expectedLine.empty() || expectedLine[0] == '#')
continue;
auto equals = expectedLine.find('=');
if (equals == std::string::npos) {
actual += "***Bad format, missing equals***\n";
return false;
}
std::string key = expectedLine.substr(0, equals);
std::string expectedValue = expectedLine.substr(equals + 1);
std::string actualValue = getBarcodeValue(barcode, key);
if (actualValue != expectedValue) {
ret = false;
actualValue += " ***Mismatch***";
}
actual += key + '=' + actualValue + '\n';
}
return ret;
}
static std::string checkResult(const fs::path& imgPath, std::string_view expectedFormat, const Barcode& barcode)
{
if (auto format = ToString(barcode.format()); expectedFormat != format)
return fmt::format("Format mismatch: expected '{}' but got '{}'", expectedFormat, format);
auto readFile = [imgPath](const char* ending) {
std::ifstream ifs(fs::path(imgPath).replace_extension(ending), std::ios::binary);
return ifs ? std::optional(std::string(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>())) : std::nullopt;
};
if (auto expected = readFile(".result.txt")) {
std::string actual;
if (!compareResult(barcode, *expected, actual))
return fmt::format("Result mismatch: expected\n{} but got\n{}", *expected, actual);
}
if (auto expected = readFile(".txt")) {
expected = EscapeNonGraphical(*expected);
auto utf8Result = barcode.text(TextMode::Escaped);
return utf8Result != *expected ? fmt::format("Content mismatch: expected '{}' but got '{}'", *expected, utf8Result) : "";
}
if (auto expected = readFile(".bin")) {
ByteArray binaryExpected(*expected);
return barcode.bytes() != binaryExpected
? fmt::format("Content mismatch: expected '{}' but got '{}'", ToHex(binaryExpected), ToHex(barcode.bytes()))
: "";
}
return "Error reading file";
}
static int failed = 0;
static int extra = 0;
static int totalImageLoadTime = 0;
int timeSince(std::chrono::steady_clock::time_point startTime)
{
auto duration = std::chrono::steady_clock::now() - startTime;
return narrow_cast<int>(std::chrono::duration_cast<std::chrono::milliseconds>(duration).count());
}
// pre-load images into cache, so the disc io time does not end up in the timing measurement
void preloadImageCache(const std::vector<fs::path>& imgPaths)
{
auto startTime = std::chrono::steady_clock::now();
ImageLoader::clearCache();
for (const auto& imgPath : imgPaths)
ImageLoader::load(imgPath);
totalImageLoadTime += timeSince(startTime);
}
static std::string printPositiveTestStats(int imageCount, const TestCase::TC& tc)
{
int passCount = imageCount - Size(tc.misReadFiles) - Size(tc.notDetectedFiles);
fmt::print(" | {}: {:3} of {:3}, misread {} of {}", tc.name, passCount, tc.minPassCount, Size(tc.misReadFiles), tc.maxMisreads);
std::string failures;
if (passCount < tc.minPassCount && !tc.notDetectedFiles.empty()) {
failures += fmt::format(" Not detected ({}):", tc.name);
for (const auto& f : tc.notDetectedFiles)
failures += fmt::format(" {}", f.filename().string());
failures += "\n";
failed += tc.minPassCount - passCount;
}
extra += std::max(0, passCount - tc.minPassCount);
if (passCount > tc.minPassCount)
failures += fmt::format(" Unexpected detections ({}): {}\n", tc.name, passCount - tc.minPassCount);
if (Size(tc.misReadFiles) > tc.maxMisreads) {
failures += fmt::format(" Read error ({}):", tc.name);
for (const auto& [path, error] : tc.misReadFiles)
failures += fmt::format(" {}: {}\n", path.filename().string(), error);
failed += Size(tc.misReadFiles) - tc.maxMisreads;
}
return failures;
}
static std::vector<fs::path> getImagesInDirectory(const fs::path& directory)
{
std::vector<fs::path> result;
for (const auto& entry : fs::directory_iterator(directory))
if (fs::is_regular_file(entry.status()) &&
Contains({".png", ".jpg", ".pgm", ".gif"}, entry.path().extension()))
result.push_back(entry.path());
preloadImageCache(result);
return result;
}
static void doRunTests(const fs::path& directory, std::string_view format, int totalTests, const std::vector<TestCase>& tests,
ReaderOptions opts)
{
auto imgPaths = getImagesInDirectory(directory);
auto folderName = directory.stem();
if (Size(imgPaths) != totalTests)
fmt::print("TEST {} => Expected number of tests: {}, got: {} => FAILED\n", folderName.string(), totalTests, imgPaths.size());
for (auto& test : tests) {
fmt::print("{:20} @ {:3}, {:3}", folderName.string(), test.rotation, Size(imgPaths));
std::vector<int> times;
std::string failures;
for (auto tc : test.tc) {
if (tc.name.empty())
break;
auto startTime = std::chrono::steady_clock::now();
opts.setTryDownscale(tc.name == "slow_");
opts.setDownscaleFactor(2);
opts.setDownscaleThreshold(180);
opts.setTryHarder(tc.name == "slow");
opts.setTryRotate(tc.name == "slow");
opts.setTryInvert(tc.name == "slow");
opts.setIsPure(tc.name == "pure");
if (opts.isPure())
opts.setBinarizer(Binarizer::FixedThreshold);
for (const auto& imgPath : imgPaths) {
auto barcode = ReadBarcode(ImageLoader::load(imgPath).rotated(test.rotation), opts);
if (barcode.isValid()) {
auto error = checkResult(imgPath, format, barcode);
if (!error.empty())
tc.misReadFiles[imgPath] = error;
} else {
tc.notDetectedFiles.insert(imgPath);
}
}
times.push_back(timeSince(startTime));
failures += printPositiveTestStats(Size(imgPaths), tc);
}
fmt::print(" | time: {:3} vs {:3} ms\n", times.front(), times.back());
if (!failures.empty())
fmt::print("\n{}\n", failures);
}
}
static Barcode readMultiple(const std::vector<fs::path>& imgPaths, std::string_view format)
{
Barcodes allBarcodes;
for (const auto& imgPath : imgPaths) {
auto barcodes = ReadBarcodes(ImageLoader::load(imgPath),
ReaderOptions().setFormats(BarcodeFormatFromString(format)).setTryDownscale(false));
allBarcodes.insert(allBarcodes.end(), barcodes.begin(), barcodes.end());
}
return MergeStructuredAppendSequence(allBarcodes);
}
static void doRunStructuredAppendTest(const fs::path& directory, std::string_view format, int totalTests,
const std::vector<TestCase>& tests)
{
auto imgPaths = getImagesInDirectory(directory);
auto folderName = directory.stem();
std::map<fs::path, std::vector<fs::path>> imageGroups;
for (const auto& imgPath : imgPaths) {
std::string fn = imgPath.filename().string();
auto p = fn.find_last_of('-');
imageGroups[imgPath.parent_path() / fn.substr(0, p)].push_back(imgPath);
}
if (Size(imageGroups) != totalTests)
fmt::print("TEST {} => Expected number of tests: {}, got: {} => FAILED\n", folderName.string(), totalTests,
imageGroups.size());
for (auto& test : tests) {
fmt::print("{:20} @ {:3}, {:3}", folderName.string(), test.rotation, Size(imgPaths));
auto tc = test.tc[0];
auto startTime = std::chrono::steady_clock::now();
for (const auto& [testPath, testImgPaths] : imageGroups) {
auto barcode = readMultiple(testImgPaths, format);
if (barcode.isValid()) {
auto error = checkResult(testPath, format, barcode);
if (!error.empty())
tc.misReadFiles[testPath] = error;
} else {
tc.notDetectedFiles.insert(testPath);
}
}
auto failures = printPositiveTestStats(Size(imageGroups), tc);
fmt::print(" | time: {:3} ms\n", timeSince(startTime));
if (!failures.empty())
fmt::print("\n{}\n", failures);
}
}
int runBlackBoxTests(const fs::path& testPathPrefix, const std::set<std::string>& includedTests)
{
auto hasTest = [&includedTests](const fs::path& dir) {
auto stem = dir.stem().string();
return includedTests.empty() || Contains(includedTests, stem) ||
Contains(includedTests, stem.substr(0, stem.size() - 2));
};
auto runTests = [&](std::string_view directory, std::string_view format, int total,
const std::vector<TestCase>& tests, const ReaderOptions& opts = ReaderOptions()) {
if (hasTest(directory))
doRunTests(testPathPrefix / directory, format, total, tests, opts);
};
auto runStructuredAppendTest = [&](std::string_view directory, std::string_view format, int total,
const std::vector<TestCase>& tests) {
if (hasTest(directory))
doRunStructuredAppendTest(testPathPrefix / directory, format, total, tests);
};
try
{
auto startTime = std::chrono::steady_clock::now();
// clang-format off
// Expected failures:
// abc-inverted.png (fast) - fast does not try inverted
// az-thick.png (pure)
runTests("aztec-1", "Aztec", 31, {
{ 30, 31, 0 },
{ 30, 31, 90 },
{ 30, 31, 180 },
{ 30, 31, 270 },
{ 29, 0, pure },
});
runTests("aztec-2", "Aztec", 22, {
{ 21, 21, 0 },
{ 21, 21, 90 },
{ 21, 21, 180 },
{ 21, 21, 270 },
});
runTests("datamatrix-1", "DataMatrix", 29, {
{ 29, 29, 0 },
{ 0, 27, 90 },
{ 0, 27, 180 },
{ 0, 27, 270 },
{ 28, 0, pure },
});
runTests("datamatrix-2", "DataMatrix", 13, {
{ 13, 13, 0 },
{ 0, 13, 90 },
{ 0, 13, 180 },
{ 0, 13, 270 },
});
runTests("datamatrix-3", "DataMatrix", 21, {
{ 20, 21, 0 },
{ 0, 21, 90 },
{ 0, 21, 180 },
{ 0, 21, 270 },
});
runTests("datamatrix-4", "DataMatrix", 21, {
{ 21, 21, 0 },
{ 0, 21, 90 },
{ 0, 21, 180 },
{ 0, 21, 270 },
{ 19, 0, pure },
});
runTests("dxfilmedge-1", "DXFilmEdge", 3, {
{ 1, 3, 0 },
{ 0, 3, 180 },
});
runTests("codabar-1", "Codabar", 11, {
{ 11, 11, 0 },
{ 11, 11, 180 },
});
runTests("codabar-2", "Codabar", 4, {
{ 2, 3, 0 },
{ 2, 3, 180 },
});
runTests("code39-1", "Code39", 4, {
{ 4, 4, 0 },
{ 4, 4, 180 },
});
runTests("code39-2", "Code39", 2, {
{ 2, 2, 0 },
{ 2, 2, 180 },
});
runTests("code39-3", "Code39", 12, {
{ 12, 12, 0 },
{ 12, 12, 180 },
});
runTests("code93-1", "Code93", 3, {
{ 3, 3, 0 },
{ 3, 3, 180 },
});
runTests("code128-1", "Code128", 6, {
{ 6, 6, 0 },
{ 6, 6, 180 },
});
runTests("code128-2", "Code128", 22, {
{ 19, 22, 0 },
{ 20, 22, 180 },
});
runTests("code128-3", "Code128", 2, {
{ 2, 2, 0 },
{ 2, 2, 180 },
});
runTests("ean8-1", "EAN-8", 9, {
{ 9, 9, 0 },
{ 9, 9, 180 },
{ 8, 0, pure },
});
runTests("ean13-1", "EAN-13", 32, {
{ 26, 30, 0 },
{ 25, 30, 180 },
});
runTests("ean13-2", "EAN-13", 24, {
{ 7, 13, 0 },
{ 7, 13, 180 },
});
runTests("ean13-3", "EAN-13", 21, {
{ 20, 21, 0 },
{ 21, 21, 180 },
});
runTests("ean13-4", "EAN-13", 22, {
{ 6, 13, 0 },
{ 7, 13, 180 },
});
runTests("ean13-extension-1", "EAN-13", 5, {
{ 3, 5, 0 },
{ 3, 5, 180 },
}, ReaderOptions().setEanAddOnSymbol(EanAddOnSymbol::Require));
runTests("itf-1", "ITF", 11, {
{ 10, 11, 0 },
{ 10, 11, 180 },
});
runTests("itf-2", "ITF", 6, {
{ 6, 6, 0 },
{ 6, 6, 180 },
});
runTests("maxicode-1", "MaxiCode", 9, {
{ 9, 9, 0 },
});
runTests("maxicode-2", "MaxiCode", 4, {
{ 0, 0, 0 },
});
runTests("upca-1", "UPC-A", 12, {
{ 10, 12, 0 },
{ 11, 12, 180 },
});
runTests("upca-2", "UPC-A", 36, {
{ 17, 22, 0 },
{ 17, 22, 180 },
});
runTests("upca-3", "UPC-A", 21, {
{ 7, 11, 0 },
{ 8, 11, 180 },
});
runTests("upca-4", "UPC-A", 19, {
{ 8, 12, 0, 1, 0 },
{ 9, 12, 0, 1, 180 },
});
runTests("upca-5", "UPC-A", 32, {
{ 18, 20, 0 },
{ 18, 20, 180 },
});
runTests("upca-extension-1", "UPC-A", 6, {
{ 4, 4, 0 },
{ 3, 4, 180 },
}, ReaderOptions().setEanAddOnSymbol(EanAddOnSymbol::Require));
runTests("upce-1", "UPC-E", 3, {
{ 3, 3, 0 },
{ 3, 3, 180 },
{ 3, 0, pure },
});
runTests("upce-2", "UPC-E", 28, {
{ 18, 22, 0, 1, 0 },
{ 19, 22, 1, 1, 180 },
});
runTests("upce-3", "UPC-E", 11, {
{ 5, 7, 0 },
{ 6, 7, 180 },
});
runTests("rss14-1", "DataBar", 6, {
{ 6, 6, 0 },
{ 6, 6, 180 },
});
runTests("rss14-2", "DataBar", 16, {
{ 8, 10, 0 },
{ 9, 10, 180 },
});
runTests("rssexpanded-1", "DataBarExpanded", 34, {
{ 34, 34, 0 },
{ 34, 34, 180 },
{ 34, 0, pure },
});
runTests("rssexpanded-2", "DataBarExpanded", 15, {
{ 13, 15, 0 },
{ 13, 15, 180 },
});
runTests("rssexpanded-3", "DataBarExpanded", 118, {
{ 118, 118, 0 },
{ 118, 118, 180 },
{ 118, 0, pure },
});
runTests("rssexpandedstacked-1", "DataBarExpanded", 65, {
{ 55, 65, 0 },
{ 55, 65, 180 },
{ 60, 0, pure },
});
runTests("rssexpandedstacked-2", "DataBarExpanded", 2, {
{ 2, 2, 0 },
{ 2, 2, 180 },
});
runTests("qrcode-1", "QRCode", 16, {
{ 16, 16, 0 },
{ 16, 16, 90 },
{ 16, 16, 180 },
{ 16, 16, 270 },
});
runTests("qrcode-2", "QRCode", 51, {
{ 45, 48, 0 },
{ 45, 48, 90 },
{ 45, 48, 180 },
{ 45, 48, 270 },
{ 22, 1, pure }, // the misread is the 'outer' symbol in 16.png
});
runTests("qrcode-3", "QRCode", 28, {
{ 28, 28, 0 },
{ 28, 28, 90 },
{ 28, 28, 180 },
{ 28, 28, 270 },
});
runTests("qrcode-4", "QRCode", 41, {
{ 31, 31, 0 },
{ 31, 31, 90 },
{ 31, 31, 180 },
{ 31, 31, 270 },
});
runTests("qrcode-5", "QRCode", 16, {
{ 16, 16, 0 },
{ 16, 16, 90 },
{ 16, 16, 180 },
{ 16, 16, 270 },
{ 4, 0, pure },
});
runTests("qrcode-6", "QRCode", 15, {
{ 15, 15, 0 },
{ 15, 15, 90 },
{ 15, 15, 180 },
{ 15, 15, 270 },
});
runStructuredAppendTest("qrcode-7", "QRCode", 1, {
{ 1, 1, 0 },
});
runTests("microqrcode-1", "MicroQRCode", 16, {
{ 15, 15, 0 },
{ 14, 14, 90 },
{ 14, 14, 180 }, // ughs: 1 result is platform/compiler dependent (e.g. -march=core2 vs. haswell)
{ 15, 15, 270 },
{ 9, 0, pure },
});
runTests("rmqrcode-1", "rMQRCode", 3, {
{ 2, 3, 0 },
{ 2, 3, 90 },
{ 2, 3, 180 },
{ 2, 3, 270 },
{ 2, 2, pure },
});
runTests("pdf417-1", "PDF417", 17, {
{ 16, 17, 0 },
{ 1, 17, 90 },
{ 16, 17, 180 },
{ 1, 17, 270 },
{ 16, 0, pure },
});
runTests("pdf417-2", "PDF417", 25, {
{ 25, 25, 0 },
{ 0, 25, 90 },
{ 25, 25, 180 },
{ 0, 25, 270 },
});
runTests("pdf417-3", "PDF417", 16, {
{ 16, 16, 0 },
{ 0, 16, 90 },
{ 16, 16, 180 },
{ 0, 16, 270 },
{ 7, 0, pure },
});
runStructuredAppendTest("pdf417-4", "PDF417", 3, {
{ 3, 3, 0 },
});
runTests("falsepositives-1", "None", 27, {
{ 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 90 },
{ 0, 0, 0, 0, 180 },
{ 0, 0, 0, 0, 270 },
{ 0, 0, pure },
});
runTests("falsepositives-2", "None", 25, {
{ 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 90 },
{ 0, 0, 0, 0, 180 },
{ 0, 0, 0, 0, 270 },
{ 0, 0, pure },
});
// clang-format on
int totalTime = timeSince(startTime);
int decodeTime = totalTime - totalImageLoadTime;
fmt::print("load time: {} ms.\n", totalImageLoadTime);
fmt::print("decode time: {} ms.\n", decodeTime);
fmt::print("total time: {} ms.\n", totalTime);
if (failed)
fmt::print("WARNING: {} tests failed.\n", failed);
if (extra)
fmt::print("INFO: {} tests succeeded unexpectedly.\n", extra);
return failed;
}
catch (const std::exception& e) {
fmt::print("{}\n", e.what());
}
catch (...) {
fmt::print("Internal error\n");
}
return -1;
}
} // ZXing::Test
```
|
/content/code_sandbox/test/blackbox/BlackboxTestRunner.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 6,576
|
```c++
/*
*/
#include "GTIN.h"
#include "gtest/gtest.h"
using namespace ZXing;
using namespace ZXing::GTIN;
TEST(GTINTest, CountryIdentifierEAN13)
{
// From test/samples/ean13-*/
EXPECT_EQ(LookupCountryIdentifier("8413000065504"), "ES");
EXPECT_EQ(LookupCountryIdentifier("8413000065504 12"), "ES");
EXPECT_EQ(LookupCountryIdentifier("8413000065504 51299"), "ES");
EXPECT_EQ(LookupCountryIdentifier("5449000039231"), "BE");
EXPECT_TRUE(LookupCountryIdentifier("9788430532674").empty()); // Bookland (ISBN)
EXPECT_EQ(LookupCountryIdentifier("8480017507990"), "ES");
EXPECT_EQ(LookupCountryIdentifier("3166298099809"), "FR");
EXPECT_EQ(LookupCountryIdentifier("5201815331227"), "GR");
EXPECT_EQ(LookupCountryIdentifier("3560070169443"), "FR");
EXPECT_EQ(LookupCountryIdentifier("4045787034318"), "DE");
EXPECT_EQ(LookupCountryIdentifier("3086126100326"), "FR");
EXPECT_EQ(LookupCountryIdentifier("4820024790635"), "UA");
EXPECT_EQ(LookupCountryIdentifier("7622200008018"), "CH");
EXPECT_EQ(LookupCountryIdentifier("5603667020517"), "PT");
EXPECT_EQ(LookupCountryIdentifier("5709262942503"), "DK");
EXPECT_EQ(LookupCountryIdentifier("4901780188352"), "JP");
EXPECT_EQ(LookupCountryIdentifier("4007817327098"), "DE");
EXPECT_EQ(LookupCountryIdentifier("5025121072311"), "GB");
EXPECT_EQ(LookupCountryIdentifier("5025121072311 12"), "GB");
EXPECT_EQ(LookupCountryIdentifier("5025121072311 51299"), "GB");
EXPECT_EQ(LookupCountryIdentifier("5030159003930"), "GB");
EXPECT_EQ(LookupCountryIdentifier("5000213002834"), "GB");
EXPECT_TRUE(LookupCountryIdentifier("1920081045006").empty()); // 140-199 unassigned
EXPECT_TRUE(LookupCountryIdentifier("9780735200449 51299").empty()); // Bookland (ISBN)
// Other
EXPECT_TRUE(LookupCountryIdentifier("0000000001465").empty()); // 0000000 Restricted Circulation Numbers
EXPECT_TRUE(LookupCountryIdentifier("0000000111461 12").empty());
EXPECT_TRUE(LookupCountryIdentifier("0000001991469").empty()); // 0000001-0000099 unused to avoid GTIN-8 collision
EXPECT_TRUE(LookupCountryIdentifier("0000099991463").empty());
EXPECT_EQ(LookupCountryIdentifier("0000102301463"), "US"); // 00001-00009 US
EXPECT_EQ(LookupCountryIdentifier("0000102301463 51299"), "US");
EXPECT_EQ(LookupCountryIdentifier("0000902301465"), "US");
EXPECT_EQ(LookupCountryIdentifier("0001602301465"), "US"); // 0001-0009 US
EXPECT_EQ(LookupCountryIdentifier("0009602301461 12"), "US");
EXPECT_EQ(LookupCountryIdentifier("0016602301469"), "US"); // 001-019 US
EXPECT_EQ(LookupCountryIdentifier("0036602301467"), "US");
EXPECT_EQ(LookupCountryIdentifier("0196602301468 51299"), "US");
EXPECT_TRUE(LookupCountryIdentifier("0206602301464").empty()); // 020-029 Restricted Circulation Numbers
EXPECT_TRUE(LookupCountryIdentifier("0296602301465").empty());
EXPECT_EQ(LookupCountryIdentifier("0306602301461"), "US"); // 030-039 US
EXPECT_EQ(LookupCountryIdentifier("0396602301462"), "US");
EXPECT_TRUE(LookupCountryIdentifier("0406602301468").empty()); // 040-049 Restricted Circulation Numbers
EXPECT_TRUE(LookupCountryIdentifier("0496602301469").empty());
EXPECT_TRUE(LookupCountryIdentifier("0506602301465").empty()); // 050-059 reserved for future use
EXPECT_TRUE(LookupCountryIdentifier("0596602301466").empty());
EXPECT_EQ(LookupCountryIdentifier("0606602301462"), "US"); // 060-099 US
EXPECT_EQ(LookupCountryIdentifier("0996602301464"), "US");
EXPECT_EQ(LookupCountryIdentifier("1006602301469"), "US"); // 100-139 US
EXPECT_EQ(LookupCountryIdentifier("1396602301461"), "US");
EXPECT_TRUE(LookupCountryIdentifier("1406602301467").empty()); // 140-199 unassigned
EXPECT_TRUE(LookupCountryIdentifier("1996602301463").empty());
EXPECT_TRUE(LookupCountryIdentifier("2006602301468").empty()); // 200-299 Restricted Circulation Numbers
EXPECT_TRUE(LookupCountryIdentifier("2996602301462").empty());
EXPECT_EQ(LookupCountryIdentifier("9586602301468"), "MO");
EXPECT_EQ(LookupCountryIdentifier("9586602301468 12"), "MO");
EXPECT_EQ(LookupCountryIdentifier("9586602301468 51299"), "MO");
// Additions/updates
EXPECT_EQ(LookupCountryIdentifier("3890102301467"), "ME");
//EXPECT_EQ(LookupCountryIdentifier("3900102301463"), "XK"); // Kosovo according to Wikipedia - awaiting GS1 confirmation
EXPECT_EQ(LookupCountryIdentifier("4700102301468"), "KG");
EXPECT_EQ(LookupCountryIdentifier("4830102301462"), "TM");
EXPECT_EQ(LookupCountryIdentifier("4880102301467"), "TJ");
EXPECT_EQ(LookupCountryIdentifier("5210102301461"), "GR");
EXPECT_EQ(LookupCountryIdentifier("5300102301469"), "AL");
EXPECT_EQ(LookupCountryIdentifier("6040102301463"), "SN");
EXPECT_EQ(LookupCountryIdentifier("6150102301469"), "NG");
EXPECT_EQ(LookupCountryIdentifier("6170102301467"), "CM");
EXPECT_EQ(LookupCountryIdentifier("6200102301461"), "TZ");
EXPECT_EQ(LookupCountryIdentifier("6230102301468"), "BN");
EXPECT_EQ(LookupCountryIdentifier("6300102301468"), "QA");
EXPECT_EQ(LookupCountryIdentifier("6310102301467"), "NA");
EXPECT_EQ(LookupCountryIdentifier("6990102301461"), "CN");
EXPECT_EQ(LookupCountryIdentifier("7710102301464"), "CO");
EXPECT_EQ(LookupCountryIdentifier("7780102301467"), "AR");
EXPECT_TRUE(LookupCountryIdentifier("7850102301467").empty());
EXPECT_EQ(LookupCountryIdentifier("8600102301467"), "RS");
EXPECT_EQ(LookupCountryIdentifier("8830102301468"), "MM");
EXPECT_EQ(LookupCountryIdentifier("8840102301467"), "KH");
EXPECT_EQ(LookupCountryIdentifier("9400102301462"), "NZ");
}
TEST(GTINTest, CountryIdentifierUPCA)
{
// From test/samples/upca-*/
EXPECT_EQ(LookupCountryIdentifier("036602301467"), "US"); // 001-019 US/CA
EXPECT_EQ(LookupCountryIdentifier("036602301467 12"), "US"); // 001-019 US
EXPECT_EQ(LookupCountryIdentifier("036602301467 51299"), "US"); // 001-019 US
EXPECT_EQ(LookupCountryIdentifier("070097025088"), "US");
EXPECT_EQ(LookupCountryIdentifier("781735802045"), "US"); // 060-099 US
EXPECT_TRUE(LookupCountryIdentifier("456314319671").empty()); // 040-049 Restricted Circulation Numbers
EXPECT_TRUE(LookupCountryIdentifier("434704791429").empty());
EXPECT_EQ(LookupCountryIdentifier("752919460009"), "US"); // 060-099 US
EXPECT_EQ(LookupCountryIdentifier("606949762520"), "US");
EXPECT_EQ(LookupCountryIdentifier("890444000335"), "US");
EXPECT_EQ(LookupCountryIdentifier("181497000879"), "US"); // 001-019 US
EXPECT_EQ(LookupCountryIdentifier("012546619592"), "US");
EXPECT_EQ(LookupCountryIdentifier("854818000116"), "US"); // 060-099 US
EXPECT_EQ(LookupCountryIdentifier("312547701310"), "US"); // 030-039 US
EXPECT_EQ(LookupCountryIdentifier("071831007995 19868"), "US"); // 001-019 US
EXPECT_EQ(LookupCountryIdentifier("027011006951 02601"), "US");
EXPECT_EQ(LookupCountryIdentifier("024543136538 00"), "US");
// Other
EXPECT_TRUE(LookupCountryIdentifier("000000001465").empty()); // 0000000 Restricted Circulation Numbers
EXPECT_TRUE(LookupCountryIdentifier("000000111461 12").empty());
EXPECT_TRUE(LookupCountryIdentifier("000001991468").empty()); // 0000001-0000099 unused to avoid GTIN-8 collision
EXPECT_TRUE(LookupCountryIdentifier("000099991463").empty());
EXPECT_EQ(LookupCountryIdentifier("000102301463"), "US"); // 00001-00009 US
EXPECT_EQ(LookupCountryIdentifier("000102301463 51299"), "US");
EXPECT_EQ(LookupCountryIdentifier("000902301465"), "US");
EXPECT_EQ(LookupCountryIdentifier("001602301465"), "US"); // 0001-0009 US
EXPECT_EQ(LookupCountryIdentifier("009602301461 12"), "US");
EXPECT_EQ(LookupCountryIdentifier("016602301469"), "US"); // 001-019 US
EXPECT_EQ(LookupCountryIdentifier("036602301467"), "US");
EXPECT_EQ(LookupCountryIdentifier("196602301468 51299"), "US");
EXPECT_TRUE(LookupCountryIdentifier("206602301464").empty()); // 020-029 Restricted Circulation Numbers
EXPECT_TRUE(LookupCountryIdentifier("296602301465").empty());
EXPECT_EQ(LookupCountryIdentifier("306602301461"), "US"); // 030-039 US
EXPECT_EQ(LookupCountryIdentifier("396602301462"), "US");
EXPECT_TRUE(LookupCountryIdentifier("406602301468").empty()); // 040-049 Restricted Circulation Numbers
EXPECT_TRUE(LookupCountryIdentifier("496602301469").empty());
EXPECT_TRUE(LookupCountryIdentifier("506602301465").empty()); // 050-059 reserved for future use
EXPECT_TRUE(LookupCountryIdentifier("596602301466").empty());
EXPECT_EQ(LookupCountryIdentifier("606602301462"), "US"); // 060-099 US
EXPECT_EQ(LookupCountryIdentifier("996602301464"), "US");
}
TEST(GTINTest, CountryIdentifierUPCE)
{
// From test/samples/upce-*/
EXPECT_EQ(LookupCountryIdentifier("01234565"), "US"); // 001-019 US
EXPECT_EQ(LookupCountryIdentifier("01234565", BarcodeFormat::UPCE), "US"); // 001-019 US
EXPECT_EQ(LookupCountryIdentifier("00123457"), "US"); // 0001-0009 US
EXPECT_EQ(LookupCountryIdentifier("00123457", BarcodeFormat::UPCE), "US"); // 0001-0009 US
EXPECT_EQ(LookupCountryIdentifier("05096893"), "US"); // 001-019 US
EXPECT_EQ(LookupCountryIdentifier("05096893", BarcodeFormat::UPCE), "US"); // 001-019 US
EXPECT_EQ(LookupCountryIdentifier("04963406 01"), "US"); // 001-019 US
EXPECT_EQ(LookupCountryIdentifier("04963406 01", BarcodeFormat::UPCE), "US"); // 001-019 US
// Other
// 0000000, 0000001-0000099 and 00001-00009 not possible for UPC-E
EXPECT_EQ(LookupCountryIdentifier("00021357"), "US"); // 0001-0009 US
EXPECT_EQ(LookupCountryIdentifier("00021357 01"), "US");
EXPECT_EQ(LookupCountryIdentifier("11621355"), "US"); // 001-019 US
EXPECT_TRUE(LookupCountryIdentifier("22221111").empty()); // 020-029 Restricted Circulation Numbers
EXPECT_EQ(LookupCountryIdentifier("31621358"), "US"); // 030-039 US
EXPECT_TRUE(LookupCountryIdentifier("40621359").empty()); // 040-049 Restricted Circulation Numbers
EXPECT_TRUE(LookupCountryIdentifier("50621359").empty()); // 050-059 reserved for future use
EXPECT_EQ(LookupCountryIdentifier("61621358"), "US"); // 060-099 US
EXPECT_EQ(LookupCountryIdentifier("99621350"), "US");
}
TEST(GTINTest, CountryIdentifierEAN8)
{
auto format = BarcodeFormat::EAN8; // Require BarcodeFormat for EAN-8 to be distinguished from UPC-E
// From test/samples/ean8-*/
EXPECT_EQ(LookupCountryIdentifier("48512343", format), "AM");
EXPECT_EQ(LookupCountryIdentifier("12345670", format), "US");
EXPECT_TRUE(LookupCountryIdentifier("67678983", format).empty()); // 650-689 unassigned
EXPECT_EQ(LookupCountryIdentifier("80674313", format), "IT");
EXPECT_EQ(LookupCountryIdentifier("59001270", format), "PL");
EXPECT_EQ(LookupCountryIdentifier("50487066", format), "GB");
EXPECT_TRUE(LookupCountryIdentifier("55123457", format).empty()); // 550-559 unassigned
EXPECT_TRUE(LookupCountryIdentifier("95012346", format).empty()); // 950 GS1 Global Office
// Other (GS1 General Specifications 1.4.3 Figure 1.4.3-1
EXPECT_TRUE(LookupCountryIdentifier("00045674", format).empty()); // 000-099 EAN-8 Restricted Circulation Numbers
EXPECT_TRUE(LookupCountryIdentifier("09945678", format).empty());
EXPECT_EQ(LookupCountryIdentifier("10045671", format), "US"); // 100-139 US
EXPECT_EQ(LookupCountryIdentifier("13945671", format), "US");
EXPECT_TRUE(LookupCountryIdentifier("14045677", format).empty()); // 140-199 unassigned
EXPECT_TRUE(LookupCountryIdentifier("19945675", format).empty());
EXPECT_TRUE(LookupCountryIdentifier("20045678", format).empty()); // 200-299 Restricted Circulation Numbers
EXPECT_TRUE(LookupCountryIdentifier("29945672", format).empty());
EXPECT_EQ(LookupCountryIdentifier("30045675", format), "FR");
EXPECT_EQ(LookupCountryIdentifier("95845678", format), "MO");
EXPECT_TRUE(LookupCountryIdentifier("97645672", format).empty()); // Unassigned
EXPECT_TRUE(LookupCountryIdentifier("97745679", format).empty()); // 977-999 Reserved for future use
EXPECT_TRUE(LookupCountryIdentifier("99945671", format).empty());
}
TEST(GTINTest, CountryIdentifierGTIN14)
{
// From test/samples/itf-*/
EXPECT_EQ(LookupCountryIdentifier("30712345000010"), "US");
EXPECT_EQ(LookupCountryIdentifier("00012345678905"), "US");
// Other
EXPECT_TRUE(LookupCountryIdentifier("12345678901231").empty()); // 200-299 Restricted Circulation Numbers
EXPECT_EQ(LookupCountryIdentifier("13005678901233"), "FR");
}
```
|
/content/code_sandbox/test/unit/GTINTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 3,433
|
```objective-c
#pragma once
#include <string>
#include <string_view>
namespace ZXing {
class BitArray;
namespace Utility {
std::string ToString(const BitArray& arr, char one, char zero);
std::string ToString(const BitArray& BitArray);
BitArray ParseBitArray(std::string_view str, char one = 'X');
}} // ZXing::Utility
```
|
/content/code_sandbox/test/unit/BitArrayUtility.h
|
objective-c
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 76
|
```c++
/*
*/
#include "Pattern.h"
#include "gtest/gtest.h"
using namespace ZXing;
constexpr int N = 33;
PatternRow pr;
TEST(PatternTest, AllWhite)
{
for (int s = 1; s <= N; ++s) {
std::vector<uint8_t> in(s, 0);
GetPatternRow(Range{in}, pr);
EXPECT_EQ(pr.size(), 1);
EXPECT_EQ(pr[0], s);
}
}
TEST(PatternTest, AllBlack)
{
for (int s = 1; s <= N; ++s) {
std::vector<uint8_t> in(s, 0xff);
GetPatternRow(Range{in}, pr);
EXPECT_EQ(pr.size(), 3);
EXPECT_EQ(pr[0], 0);
EXPECT_EQ(pr[1], s);
EXPECT_EQ(pr[2], 0);
}
}
TEST(PatternTest, BlackWhite)
{
for (int s = 1; s <= N; ++s) {
std::vector<uint8_t> in(N, 0);
std::fill_n(in.data(), s, 0xff);
GetPatternRow(Range{in}, pr);
EXPECT_EQ(pr.size(), 3);
EXPECT_EQ(pr[0], 0);
EXPECT_EQ(pr[1], s);
EXPECT_EQ(pr[2], N - s);
}
}
TEST(PatternTest, WhiteBlack)
{
for (int s = 0; s < N; ++s) {
std::vector<uint8_t> in(N, 0xff);
std::fill_n(in.data(), s, 0);
GetPatternRow(Range{in}, pr);
EXPECT_EQ(pr.size(), 3);
EXPECT_EQ(pr[0], s);
EXPECT_EQ(pr[1], N - s);
EXPECT_EQ(pr[2], 0);
}
}
```
|
/content/code_sandbox/test/unit/PatternTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 405
|
```c++
/*
*/
#include "Error.h"
#include "gtest/gtest.h"
using namespace ZXing;
TEST(ErrorTest, Default)
{
Error e;
EXPECT_FALSE(e);
EXPECT_EQ(e.type(), Error::Type::None);
EXPECT_EQ(e.msg().empty(), true);
EXPECT_EQ(e.location().empty(), true);
}
TEST(ErrorTest, Empty)
{
Error e = ChecksumError();
EXPECT_TRUE(e);
EXPECT_EQ(e.type(), Error::Type::Checksum);
EXPECT_EQ(e.type(), Error::Checksum);
EXPECT_EQ(e, Error::Checksum);
EXPECT_EQ(Error::Checksum, e);
EXPECT_EQ(e.msg().empty(), true);
EXPECT_EQ(e.location().empty(), false);
}
TEST(ErrorTest, WithMsg)
{
Error e = FormatError("something is wrong"); int line = __LINE__;
EXPECT_TRUE(e);
EXPECT_EQ(e, Error::Format);
EXPECT_EQ(e.msg(), "something is wrong");
EXPECT_EQ(e.location(), "ErrorTest.cpp:" + std::to_string(line));
}
```
|
/content/code_sandbox/test/unit/ErrorTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 201
|
```c++
/*
*/
#include "ZXAlgorithms.h"
#include "gtest/gtest.h"
using namespace ZXing;
TEST(ZXAlgorithmsTest, ToDigit)
{
EXPECT_EQ(ToDigit(0), '0');
EXPECT_EQ(ToDigit(9), '9');
EXPECT_THROW(ToDigit(-1), Error);
EXPECT_THROW(ToDigit(11), Error);
}
TEST(ZXAlgorithmsTest, ToString)
{
EXPECT_EQ(ToString(0, 1), "0");
EXPECT_EQ(ToString(0, 2), "00");
EXPECT_EQ(ToString(1, 3), "001");
EXPECT_EQ(ToString(99, 2), "99");
EXPECT_THROW(ToString(-1, 2), Error);
EXPECT_THROW(ToString(111, 2), Error);
}
TEST(ZXAlgorithmsTest, UpdateMinMax)
{
int m = 10, M = 0;
UpdateMinMax(m, M, 5);
EXPECT_EQ(m, 5);
EXPECT_EQ(M, 5);
UpdateMinMax(m, M, 2);
EXPECT_EQ(m, 2);
EXPECT_EQ(M, 5);
m = M = 1;
UpdateMinMax(m, M, 0);
EXPECT_EQ(m, 0);
EXPECT_EQ(M, 1);
UpdateMinMax(m, M, 2);
EXPECT_EQ(m, 0);
EXPECT_EQ(M, 2);
}
```
|
/content/code_sandbox/test/unit/ZXAlgorithmsTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 284
|
```c++
/*
*/
#include "Content.h"
#include "ECI.h"
#include "gtest/gtest.h"
using namespace ZXing;
using namespace testing;
#if __cplusplus > 201703L
namespace std {
bool operator==(const string& lhs, const char8_t* rhs)
{
return lhs == reinterpret_cast<const char*>(rhs);
}
} // namespace std
#endif
TEST(ContentTest, Base)
{
{ // Null
Content c;
EXPECT_EQ(c.guessEncoding(), CharacterSet::Unknown);
EXPECT_EQ(c.symbology.toString(), "");
EXPECT_TRUE(c.empty());
}
{ // set latin1
Content c;
c.switchEncoding(CharacterSet::ISO8859_1);
c.append(ByteArray{'A', 0xE9, 'Z'});
EXPECT_EQ(c.utf8(), u8"A\u00E9Z");
}
{ // set CharacterSet::ISO8859_5
Content c;
c.switchEncoding(CharacterSet::ISO8859_5);
c.append(ByteArray{'A', 0xE9, 'Z'});
EXPECT_EQ(c.utf8(), u8"A\u0449Z");
}
{ // switch to CharacterSet::ISO8859_5
Content c;
c.append(ByteArray{'A', 0xE9, 'Z'});
EXPECT_FALSE(c.hasECI);
c.switchEncoding(CharacterSet::ISO8859_5);
EXPECT_FALSE(c.hasECI);
c.append(ByteArray{'A', 0xE9, 'Z'});
EXPECT_EQ(c.utf8(), u8"A\u00E9ZA\u0449Z");
}
}
TEST(ContentTest, GuessEncoding)
{
{ // guess latin1
Content c;
c.append(ByteArray{'A', 0xE9, 'Z'});
EXPECT_EQ(c.guessEncoding(), CharacterSet::ISO8859_1);
EXPECT_EQ(c.utf8(), u8"A\u00E9Z");
EXPECT_EQ(c.bytesECI(), c.bytes);
}
{ // guess Shift_JIS
Content c;
c.append(ByteArray{'A', 0x83, 0x65, 'Z'});
EXPECT_EQ(c.guessEncoding(), CharacterSet::Shift_JIS);
EXPECT_EQ(c.utf8(), u8"A\u30C6Z");
}
}
TEST(ContentTest, ECI)
{
{ // switch to ECI::ISO8859_5
Content c;
c.append(ByteArray{'A', 0xE9, 'Z'});
c.switchEncoding(ECI::ISO8859_5);
c.append(ByteArray{'A', 0xE9, 'Z'});
EXPECT_TRUE(c.hasECI);
EXPECT_EQ(c.utf8(), u8"A\u00E9ZA\u0449Z");
EXPECT_EQ(c.bytesECI().asString(), std::string_view("\\000003A\xE9Z\\000007A\xE9Z"));
}
{ // switch ECI -> latin1 for unknown (instead of Shift_JIS)
Content c;
c.append(ByteArray{'A', 0x83, 0x65, 'Z'});
c.switchEncoding(ECI::ISO8859_5);
c.append(ByteArray{'A', 0xE9, 'Z'});
EXPECT_EQ(c.utf8(), u8"A\u0083\u0065ZA\u0449Z");
EXPECT_EQ(c.bytesECI().asString(), std::string_view("\\000003A\x83\x65Z\\000007A\xE9Z"));
}
{ // double '\'
Content c;
c.append("C:\\Test");
EXPECT_EQ(c.utf8(), u8"C:\\Test");
EXPECT_EQ(c.bytesECI().asString(), std::string_view("C:\\\\Test"));
}
}
```
|
/content/code_sandbox/test/unit/ContentTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 816
|
```c++
/*
*/
#include "CharacterSet.h"
#include "TextDecoder.h"
#include "Utf.h"
#include "gtest/gtest.h"
#include "gmock/gmock.h"
using namespace ZXing;
using namespace testing;
namespace ZXing {
int Utf32ToUtf8(char32_t utf32, char* out);
}
// Encode Unicode codepoint `utf32` as UTF-8
std::string Utf32ToUtf8(const char32_t utf32)
{
char buf[4];
int len = Utf32ToUtf8(utf32, buf);
return std::string(buf, len);
}
TEST(TextDecoderTest, AppendBINARY_ASCII)
{
uint8_t data[256];
for (int i = 0; i < 256; i++) {
data[i] = (uint8_t)i;
}
{
std::wstring str;
TextDecoder::Append(str, data, sizeof(data), CharacterSet::BINARY);
EXPECT_THAT(str, ElementsAreArray(data, sizeof(data)));
}
{
// Accepts non-ASCII
std::wstring str;
TextDecoder::Append(str, data, sizeof(data), CharacterSet::ASCII);
EXPECT_THAT(str, ElementsAreArray(data, sizeof(data)));
}
}
TEST(TextDecoderTest, AppendAllASCIIRange00_7F)
{
std::string expected;
uint8_t data[0x80];
uint8_t dataUTF16BE[0x80 * 2];
uint8_t dataUTF16LE[0x80 * 2];
uint8_t dataUTF32BE[0x80 * 4];
uint8_t dataUTF32LE[0x80 * 4];
for (int i = 0; i < 0x80; i++) {
uint8_t ch = static_cast<uint8_t>(i);
data[i] = ch;
expected.append(Utf32ToUtf8(i));
int j = i << 1;
int k = j << 1;
dataUTF16BE[j] = 0;
dataUTF16BE[j + 1] = ch;
dataUTF16LE[j] = ch;
dataUTF16LE[j + 1] = 0;
dataUTF32BE[k] = dataUTF32BE[k + 1] = dataUTF32BE[k + 2] = 0;
dataUTF32BE[k + 3] = ch;
dataUTF32LE[k] = ch;
dataUTF32LE[k + 1] = dataUTF32LE[k + 2] = dataUTF32LE[k + 3] = 0;
}
EXPECT_EQ(expected.size(), 128);
for (int i = 0; i < static_cast<int>(CharacterSet::CharsetCount); i++) {
std::string str;
CharacterSet cs = static_cast<CharacterSet>(i);
switch(cs) {
case CharacterSet::UTF16BE: TextDecoder::Append(str, dataUTF16BE, sizeof(dataUTF16BE), cs); break;
case CharacterSet::UTF16LE: TextDecoder::Append(str, dataUTF16LE, sizeof(dataUTF16LE), cs); break;
case CharacterSet::UTF32BE: TextDecoder::Append(str, dataUTF32BE, sizeof(dataUTF32BE), cs); break;
case CharacterSet::UTF32LE: TextDecoder::Append(str, dataUTF32LE, sizeof(dataUTF32LE), cs); break;
default: TextDecoder::Append(str, data, sizeof(data), cs); break;
}
EXPECT_EQ(str, expected) << " charset: " << ToString(cs);
}
}
TEST(TextDecoderTest, AppendISO8859Range80_9F)
{
uint8_t data[0xA0 - 0x80];
for (int i = 0x80; i < 0xA0; i++) {
data[i - 0x80] = (uint8_t)i;
}
static const CharacterSet isos[] = {
CharacterSet::ISO8859_1, CharacterSet::ISO8859_2, CharacterSet::ISO8859_3, CharacterSet::ISO8859_4,
CharacterSet::ISO8859_5, CharacterSet::ISO8859_6, CharacterSet::ISO8859_7, CharacterSet::ISO8859_8,
CharacterSet::ISO8859_7, CharacterSet::ISO8859_8, CharacterSet::ISO8859_9, CharacterSet::ISO8859_10,
CharacterSet::ISO8859_11, // extended with 9 CP874 codepoints in 0x80-9F range
CharacterSet::ISO8859_13, CharacterSet::ISO8859_14, CharacterSet::ISO8859_15, CharacterSet::ISO8859_16
};
for (CharacterSet iso : isos) {
std::wstring str;
TextDecoder::Append(str, data, sizeof(data), iso);
EXPECT_THAT(str, ElementsAreArray(data, sizeof(data))) << "iso: " << static_cast<int>(iso);
}
}
TEST(TextDecoderTest, AppendShift_JIS)
{
{
// Shift JIS 0x5C (backslash in ASCII) normally mapped to U+00A5 (Yen sign), but direct ASCII mapping used
static const uint8_t data[] = { 0x5C };
std::wstring str;
TextDecoder::Append(str, data, sizeof(data), CharacterSet::Shift_JIS);
EXPECT_EQ(str, L"\u005C"); // Would normally be "\u00A5"
EXPECT_EQ(ToUtf8(str), "\\"); // "" ditto
}
// {
// // Shift JIS 0x815F goes to U+FF3C (full width reverse solidus i.e. backslash)
// static const uint8_t data[] = { 0x81, 0x5F };
// std::wstring str;
// TextDecoder::Append(str, data, sizeof(data), CharacterSet::Shift_JIS);
// EXPECT_EQ(str, L"\uFF3C");
// EXPECT_EQ(ToUtf8(str), "");
// }
{
// Shift JIS 0xA5 (Yen sign in ISO/IEC 8859-1) goes to U+FF65 (half-width katakana middle dot)
static const uint8_t data[] = { 0xA5 };
std::wstring str;
TextDecoder::Append(str, data, sizeof(data), CharacterSet::Shift_JIS);
EXPECT_EQ(str, L"\uFF65");
EXPECT_EQ(ToUtf8(str), "");
}
{
// Shift JIS 0x7E (tilde in ASCII) normally mapped to U+203E (overline), but direct ASCII mapping used
static const uint8_t data[] = { 0x7E };
std::wstring str;
TextDecoder::Append(str, data, sizeof(data), CharacterSet::Shift_JIS);
EXPECT_EQ(str, L"~"); // Would normally be "\u203E"
EXPECT_EQ(ToUtf8(str), "~"); // "" ditto
}
{
static const uint8_t data[] = { 'a', 0x83, 0xC0, 'c', 0x84, 0x47, 0xA5, 0xBF, 0x93, 0x5F,
0xE4, 0xAA, 0x83, 0x65 };
std::wstring str;
TextDecoder::Append(str, data, sizeof(data), CharacterSet::Shift_JIS);
EXPECT_EQ(str, L"a\u03B2c\u0416\uFF65\uFF7F\u70B9\u8317\u30C6");
EXPECT_EQ(ToUtf8(str), "ac");
}
}
TEST(TextDecoderTest, AppendBig5)
{
// {
// static const uint8_t data[] = { 0xA1, 0x5A }; // Drawings box light left in Big5-2003; not in original Big5
// std::wstring str;
// TextDecoder::Append(str, data, sizeof(data), CharacterSet::Big5);
// EXPECT_EQ(str, L"\u2574");
// EXPECT_EQ(ToUtf8(str), "");
// }
{
static const uint8_t data[] = { 0xA1, 0x56 }; // En dash U+2013 in Big5, horizontal bar U+2015 in Big5-2003
std::wstring str;
TextDecoder::Append(str, data, sizeof(data), CharacterSet::Big5);
EXPECT_EQ(str, L"\u2013");
EXPECT_EQ(ToUtf8(str), "");
}
{
static const uint8_t data[] = { 0x1, ' ', 0xA1, 0x71, '@', 0xC0, 0x40, 0xF9, 0xD5, 0x7F };
std::wstring str;
TextDecoder::Append(str, data, sizeof(data), CharacterSet::Big5);
EXPECT_EQ(str, L"\u0001 \u3008@\u9310\u9F98\u007F");
EXPECT_EQ(ToUtf8(str), "\x01 @\x7F");
}
}
TEST(TextDecoderTest, AppendGB2312)
{
{
static const uint8_t data[] = { 'a', 0xB0, 0xA1 };
std::wstring str;
TextDecoder::Append(str, data, sizeof(data), CharacterSet::GB2312);
EXPECT_EQ(str, L"a\u554a");
EXPECT_EQ(ToUtf8(str), "a");
}
}
TEST(TextDecoderTest, AppendGB18030)
{
{
static const uint8_t data[] = { 'a', 0xA6, 0xC2, 'c', 0x81, 0x39, 0xA7, 0x39, 0xA1, 0xA4, 0xA1, 0xAA,
0xA8, 0xA6, 'Z' };
std::wstring str;
TextDecoder::Append(str, data, sizeof(data), CharacterSet::GB18030);
EXPECT_EQ(str, L"a\u03B2c\u30FB\u00B7\u2014\u00E9Z");
EXPECT_EQ(ToUtf8(str), "acZ");
}
}
TEST(TextDecoderTest, AppendEUC_KR)
{
{
static const uint8_t data[] = { 0xA2, 0xE6 }; // Euro sign U+20AC added KS X 1001:1998
std::wstring str;
TextDecoder::Append(str, data, sizeof(data), CharacterSet::EUC_KR);
EXPECT_EQ(str, L"\u20AC");
EXPECT_EQ(ToUtf8(str), "");
}
{
static const uint8_t data[] = { 'a', 0xA4, 0xA1, 'Z' };
std::wstring str;
TextDecoder::Append(str, data, sizeof(data), CharacterSet::EUC_KR);
EXPECT_EQ(str, L"a\u3131Z");
EXPECT_EQ(ToUtf8(str), "aZ");
}
}
TEST(TextDecoderTest, AppendUTF16BE)
{
{
std::wstring str;
static const uint8_t data[] = { 0x00, 0x01, 0x00, 0x7F, 0x00, 0x80, 0x00, 0xFF, 0x01, 0xFF, 0x10, 0xFF,
0xFF, 0xFD };
TextDecoder::Append(str, data, sizeof(data), CharacterSet::UTF16BE);
EXPECT_EQ(str, L"\u0001\u007F\u0080\u00FF\u01FF\u10FF\uFFFD");
EXPECT_EQ(ToUtf8(str), "\x01\x7F\xC2\x80\xEF\xBF\xBD");
}
{
std::wstring str;
static const uint8_t data[] = { 0xD8, 0x00, 0xDC, 0x00 }; // Surrogate pair U+10000
TextDecoder::Append(str, data, sizeof(data), CharacterSet::UTF16BE);
EXPECT_EQ(str, L"\U00010000");
EXPECT_EQ(ToUtf8(str), "");
}
}
```
|
/content/code_sandbox/test/unit/TextDecoderTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 2,712
|
```c++
/*
*/
#include "ThresholdBinarizer.h"
#include "oned/ODReader.h"
#include "gtest/gtest.h"
using namespace ZXing;
// Helper to parse a 0/1 string into a BitMatrix
static BitMatrix ParseBitMatrix(const std::string& str, const int width)
{
const int height = narrow_cast<int>(str.length() / width);
BitMatrix mat(width, height);
for (int y = 0; y < height; ++y) {
size_t offset = y * width;
for (int x = 0; x < width; ++x, offset++) {
if (str[offset] == '1') {
mat.set(x, y);
}
}
}
return mat;
}
// Helper to convert a BitMatrix into a black/white ImageView
static ImageView getImageView(std::vector<uint8_t> &buf, const BitMatrix &bits)
{
buf.resize(bits.width() * bits.height());
for (int r = 0; r < bits.height(); r++) {
const int k = r * bits.width();
for (int c = 0; c < bits.width(); c++) {
buf[k + c] = bits.get(c, r) ? 0x00 : 0xFF;
}
}
return ImageView(buf.data(), bits.width(), bits.height(), ImageFormat::Lum);
}
TEST(ThresholdBinarizerTest, PatternRowClear)
{
std::string bitstream;
BitMatrix bits;
ReaderOptions opts;
std::vector<uint8_t> buf;
// Test that ThresholdBinarizer::getPatternRow() clears row first (same as GlobalHistogramBinarizer)
// Following was failing due to OneD::DoDecode() accumulating bars in loop when using ThresholdBinarizer
// DataBarExpanded Stacked with 11 rows (11 + 10 * 3 separators), 1 column (2 data segments) wide
bitstream = "01010101111011111110111111110000101100100000010100010"
"00001010000100000001000000001010010011011111101010000"
"00000101010101010101010101010101010101010101010100000"
"00001000001110100010100001010101001110000101100110000"
"10100111110001011101011110000000010001111010011000101"
"00001000001110100010100001010101001110000101100110000"
"00000101010101010101010101010101010101010101010100000"
"00000001110100100001010000001010010101100111000110000"
"01011110001011011110001111110000101010011000111000010"
"00000001110100100001010000001010010101100111000110000"
"00000101010101010101010101010101010101010101010100000"
"00000110001111101110100001010100001110001110111010000"
"10101001110000010001011110000001110001110001000100101"
"00000110001111101110100001010100001110001110111010000"
"00000101010101010101010101010101010101010101010100000"
"00001000011011000101010000101010010011100010001100000"
"01000111100100111010001111000000101100011101110010010"
"00001000011011000101010000101010010011100010001100000"
"00000101010101010101010101010101010101010101010100000"
"00001000110001110110100000000100001011110100001000000"
"10100111001110001001011111111001110100001011110111101"
"00001000110001110110100000000100001011110100001000000"
"00000101010101010101010101010101010101010101010100000"
"00000010011101111101010010101010010100110000100000000"
"01011101100010000010001100000000101011001111011110010"
"00000010011101111101010010101010010100110000100000000"
"00000101010101010101010101010101010101010101010100000"
"00000100010111101110100000101010001100000110011010000"
"10111011101000010001011111000000110011111001100101101"
"00000100010111101110100000101010001100000110011010000"
"00000101010101010101010101010101010101010101010100000"
"00000011000110001001000000010101010000011110011010000"
"01011100111001110110011111100000101111100001100101010"
"00000011000110001001000000010101010000011110011010000"
"00000101010101010101010101010101010101010101010100000"
"00001011100010001110100000000010001011111010001100000"
"10100100011101110001011111111100110100000101110011101"
"00001011100010001110100000000010001011111010001100000"
"00000101010101010101010101010101010101010101010100000"
"00001000111010000101000101010101010100001011000110000"
"01000111000101111010011000000000101011110100111000010";
bits = ParseBitMatrix(bitstream, 53 /*width*/);
opts.setFormats(BarcodeFormat::DataBarExpanded);
opts.setMinLineCount(1);
OneD::Reader reader(opts);
auto barcode = reader.decode(ThresholdBinarizer(getImageView(buf, bits), 0x7F));
EXPECT_TRUE(barcode.isValid());
EXPECT_EQ(barcode.text(TextMode::HRI), "(91)your_sha256_hash5678");
}
```
|
/content/code_sandbox/test/unit/ThresholdBinarizerTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 1,405
|
```c++
/*
*/
#include "BitHacks.h"
#include "gtest/gtest.h"
#include <vector>
TEST(BitHackTest, BitHacks)
{
using namespace ZXing::BitHacks;
EXPECT_EQ(NumberOfLeadingZeros(0), 32);
EXPECT_EQ(NumberOfLeadingZeros(1), 31);
EXPECT_EQ(NumberOfLeadingZeros(0xffffffff), 0);
// EXPECT_EQ(NumberOfTrailingZeros(0), 32);
EXPECT_EQ(NumberOfTrailingZeros(1), 0);
EXPECT_EQ(NumberOfTrailingZeros(2), 1);
EXPECT_EQ(NumberOfTrailingZeros(0xffffffff), 0);
EXPECT_EQ(Reverse(0), 0);
EXPECT_EQ(Reverse(1), 0x80000000);
EXPECT_EQ(Reverse(0xffffffff), 0xffffffff);
EXPECT_EQ(Reverse(0xff00ff00), 0x00ff00ff);
EXPECT_EQ(CountBitsSet(0), 0);
EXPECT_EQ(CountBitsSet(1), 1);
EXPECT_EQ(CountBitsSet(2), 1);
EXPECT_EQ(CountBitsSet(0xffffffff), 32);
EXPECT_EQ(CountBitsSet(0x11111111), 8);
EXPECT_EQ(HighestBitSet(0x1), 0);
EXPECT_EQ(HighestBitSet(0xffffffff), 31);
EXPECT_EQ(HighestBitSet(0x1F), 4);
using V = std::vector<uint32_t>;
auto checkReverse = [](V&& v1, int p, V&& v2) {
Reverse(v1, p);
EXPECT_EQ(v1, v2);
};
checkReverse(V{1}, 0, V{0x80000000});
checkReverse(V{0, 1}, 0, V{0x80000000, 0});
checkReverse(V{0, 1}, 31, V{1, 0});
checkReverse(V{0xffffffff, 0}, 16, V{0xffff0000, 0xffff});
}
```
|
/content/code_sandbox/test/unit/BitHacksTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 431
|
```c++
/*
*/
#include "CharacterSet.h"
#include "ECI.h"
#include "gtest/gtest.h"
using namespace ZXing;
using namespace testing;
TEST(CharacterSetECITest, Charset2ECI)
{
EXPECT_EQ(ToInt(ToECI(CharacterSet::ISO8859_1)), 3);
EXPECT_EQ(ToInt(ToECI(CharacterSet::ISO8859_2)), 4);
EXPECT_EQ(ToInt(ToECI(CharacterSet::ASCII)), 27);
EXPECT_EQ(ToInt(ToECI(CharacterSet::EUC_KR)), 30);
EXPECT_EQ(ToInt(ToECI(CharacterSet::BINARY)), 899);
EXPECT_EQ(ToInt(ToECI(CharacterSet::Unknown)), -1);
}
TEST(CharacterSetECITest, CharacterSetFromString)
{
EXPECT_EQ(CharacterSet::ISO8859_1, CharacterSetFromString("ISO-8859-1"));
EXPECT_EQ(CharacterSet::ISO8859_1, CharacterSetFromString("ISO8859_1"));
EXPECT_EQ(CharacterSet::ISO8859_1, CharacterSetFromString("ISO 8859-1"));
EXPECT_EQ(CharacterSet::ISO8859_1, CharacterSetFromString("iso88591"));
EXPECT_EQ(CharacterSet::Unknown, CharacterSetFromString("invalid-name"));
}
```
|
/content/code_sandbox/test/unit/CharacterSetECITest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 262
|
```objective-c
#pragma once
#include <random>
namespace ZXing {
class PseudoRandom {
std::minstd_rand _random;
public:
PseudoRandom(size_t seed) : _random(static_cast<std::minstd_rand::result_type>(seed)) {}
template <typename IntType>
IntType next(IntType low, IntType high) {
return std::uniform_int_distribution<IntType>(low, high)(_random);
}
};
}
```
|
/content/code_sandbox/test/unit/PseudoRandom.h
|
objective-c
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 89
|
```c++
/*
*/
#include "CharacterSet.h"
#include "TextDecoder.h"
#include "TextEncoder.h"
#include "gtest/gtest.h"
using namespace ZXing;
using namespace testing;
template <typename CharT>
void EnDeCode(CharacterSet cs, const CharT* in, std::string_view out)
{
std::string bytes = TextEncoder::FromUnicode(reinterpret_cast<const char*>(in), cs);
EXPECT_EQ(bytes, out);
std::string dec;
TextDecoder::Append(dec, reinterpret_cast<const uint8_t*>(bytes.data()), bytes.size(), cs);
EXPECT_EQ(dec, reinterpret_cast<const char*>(in));
}
TEST(TextEncoderTest, FullCycleEncodeDecode)
{
EnDeCode(CharacterSet::Cp437, u8"\u00C7", "\x80"); // LATIN CAPITAL LETTER C WITH CEDILLA
EnDeCode(CharacterSet::ISO8859_1, u8"\u00A0", "\xA0"); // NO-BREAK SPACE
EnDeCode(CharacterSet::ISO8859_2, u8"\u0104", "\xA1"); // LATIN CAPITAL LETTER A WITH OGONEK
EnDeCode(CharacterSet::ISO8859_3, u8"\u0126", "\xA1"); // LATIN CAPITAL LETTER H WITH STROKE
EnDeCode(CharacterSet::ISO8859_4, u8"\u0138", "\xA2"); // LATIN SMALL LETTER KRA
EnDeCode(CharacterSet::ISO8859_5, u8"\u045F", "\xFF"); // CYRILLIC SMALL LETTER DZHE
EnDeCode(CharacterSet::ISO8859_6, u8"\u0652", "\xF2"); // ARABIC SUKUN
EnDeCode(CharacterSet::ISO8859_7, u8"\u03CE", "\xFE"); // GREEK SMALL LETTER OMEGA WITH TONOS
EnDeCode(CharacterSet::ISO8859_8, u8"\u05EA", "\xFA"); // HEBREW LETTER TAV
EnDeCode(CharacterSet::ISO8859_9, u8"\u011E", "\xD0"); // LATIN CAPITAL LETTER G WITH BREVE
EnDeCode(CharacterSet::ISO8859_10, u8"\u0138", "\xFF"); // LATIN SMALL LETTER KRA
EnDeCode(CharacterSet::ISO8859_11, u8"\u0E5B", "\xFB"); // THAI CHARACTER KHOMUT
EnDeCode(CharacterSet::ISO8859_13, u8"\u2019", "\xFF"); // RIGHT SINGLE QUOTATION MARK
EnDeCode(CharacterSet::ISO8859_14, u8"\u1E6B", "\xF7"); // LATIN SMALL LETTER T WITH DOT ABOVE
EnDeCode(CharacterSet::ISO8859_15, u8"\u00BF", "\xBF"); // INVERTED QUESTION MARK
EnDeCode(CharacterSet::ISO8859_16, u8"\u017C", "\xBF"); // LATIN SMALL LETTER Z WITH DOT ABOVE
// EnDeCode(CharacterSet::Shift_JIS, u8"\u00A5", "\x5C"); // YEN SIGN Mapped to backslash
// EnDeCode(CharacterSet::Shift_JIS, u8"\u203E", "\x7E"); // OVERLINE Mapped to tilde
EnDeCode(CharacterSet::Shift_JIS, u8"\u3000", "\x81\x40"); // IDEOGRAPHIC SPACE
EnDeCode(CharacterSet::Cp1250, u8"\u20AC", "\x80"); // EURO SIGN
EnDeCode(CharacterSet::Cp1251, u8"\u045F", "\x9F"); // CYRILLIC SMALL LETTER DZHE
EnDeCode(CharacterSet::Cp1252, u8"\u02DC", "\x98"); // SMALL TILDE
EnDeCode(CharacterSet::Cp1256, u8"\u0686", "\x8D"); // ARABIC LETTER TCHEH
EnDeCode(CharacterSet::UTF16BE, u8"\u20AC", "\x20\xAC"); // EURO SIGN
EnDeCode(CharacterSet::UTF8, u8"\u20AC", "\xE2\x82\xAC"); // EURO SIGN
EnDeCode(CharacterSet::ASCII, u8"#", "#");
EnDeCode(CharacterSet::Big5, u8"\u3000", "\xA1\x40"); // IDEOGRAPHIC SPACE
EnDeCode(CharacterSet::GB2312, u8"\u3000", "\xA1\xA1"); // IDEOGRAPHIC SPACE
EnDeCode(CharacterSet::EUC_KR, u8"\u3000", "\xA1\xA1"); // IDEOGRAPHIC SPACE
// EnDeCode(CharacterSet::GBK, u8"\u3000", "\xA1\xA1"); // IDEOGRAPHIC SPACE
EnDeCode(CharacterSet::GB18030, u8"\u3000", "\xA1\xA1"); // IDEOGRAPHIC SPACE
EnDeCode(CharacterSet::UTF16LE, u8"\u20AC", "\xAC\x20"); // EURO SIGN
EnDeCode(CharacterSet::UTF32BE, u8"\u20AC", std::string("\x00\x00\x20\xAC", 4)); // EURO SIGN
EnDeCode(CharacterSet::UTF32LE, u8"\u20AC", std::string("\xAC\x20\x00\x00", 4)); // EURO SIGN
// EnDeCode(CharacterSet::ISO646_Inv, "%", "%");
EnDeCode(CharacterSet::BINARY, u8"\u0080\u00FF", "\x80\xFF");
EnDeCode(CharacterSet::Unknown, u8"\u0080", "\x80"); // Treated as binary
EnDeCode(CharacterSet::EUC_JP, u8"\u0080", "\x80"); // Not supported, treated as binary
}
```
|
/content/code_sandbox/test/unit/TextEncoderTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 1,300
|
```c++
/*
*/
#include "GenericGF.h"
#include "PseudoRandom.h"
#include "ReedSolomonDecoder.h"
#include "ReedSolomonEncoder.h"
#include <algorithm>
#include <ostream>
static std::ostream& operator<<(std::ostream& out, const ZXing::GenericGF& field) {
out << "GF(" << field.size() << ',' << field.generatorBase() << ')';
return out;
}
#include "gtest/gtest.h"
using namespace ZXing;
namespace {
static const int DECODER_RANDOM_TEST_ITERATIONS = 3;
static const int DECODER_TEST_ITERATIONS = 10;
std::vector<int> operator+(const std::vector<int>& a, const std::vector<int>& b) {
std::vector<int> c;
c.reserve(a.size() + b.size());
c.insert(c.end(), a.begin(), a.end());
c.insert(c.end(), b.begin(), b.end());
return c;
}
void TestEncoder(const GenericGF& field, const std::vector<int>& dataWords, const std::vector<int>& ecWords) {
auto messageExpected = dataWords + ecWords;
auto message = dataWords;
message.resize(message.size() + ecWords.size());
ReedSolomonEncode(field, message, Size(ecWords));
EXPECT_EQ(message, messageExpected) << "Encode in " << field << " (" << dataWords.size() << ',' << ecWords.size() << ") failed";
}
void Corrupt(std::vector<int>& received, size_t howMany, PseudoRandom& random, int max) {
std::vector<bool> corrupted(received.size(), false);
for (size_t j = 0; j < howMany; j++) {
auto location = random.next(size_t(0), received.size() - 1);
int value = random.next(0, max - 1);
if (corrupted[location] || received[location] == value) {
j--;
}
else {
corrupted[location] = true;
received[location] = value;
}
}
}
void TestDecoder(const GenericGF& field, const std::vector<int>& dataWords, const std::vector<int>& ecWords) {
std::vector<int> message(dataWords.size() + ecWords.size());
auto maxErrors = ecWords.size() / 2;
PseudoRandom random(0x12345678);
int iterations = field.size() > 256 ? 1 : DECODER_TEST_ITERATIONS;
for (int j = 0; j < iterations; j++) {
for (size_t i = 0; i < ecWords.size(); i++) {
if (i > 10 && i < ecWords.size() / 2 - 10) {
// performance improvement - skip intermediate cases in long-running tests
i += ecWords.size() / 10;
}
auto message = dataWords + ecWords;
Corrupt(message, i, random, field.size());
bool success = ReedSolomonDecode(field, message, Size(ecWords));
if (!success) {
// fail only if maxErrors exceeded
ASSERT_GT(i, maxErrors) << "Decode in " << field << " (" << dataWords.size() << ',' << ecWords.size() << ") failed at " << i;
// else stop
break;
}
if (i < maxErrors) {
message.resize(dataWords.size());
ASSERT_EQ(message, dataWords) << "Decode in " << field << " (" << dataWords.size() << ',' << ecWords.size() << ") failed at " << i << " errors";
}
}
}
}
void TestEncodeDecode(const GenericGF& field, const std::vector<int>& dataWords, const std::vector<int>& ecWords) {
TestEncoder(field, dataWords, ecWords);
TestDecoder(field, dataWords, ecWords);
}
void TestEncodeDecodeRandom(const GenericGF& field, int dataSize, int ecSize) {
ASSERT_TRUE(dataSize > 0 && dataSize <= field.size() - 3) << "Invalid data size for " << field;
ASSERT_TRUE(ecSize > 0 && ecSize + dataSize <= field.size()) << "Invalid ECC size for " << field;
ReedSolomonEncoder encoder(field);
std::vector<int> message(dataSize + ecSize);
std::vector<int> dataWords(dataSize);
std::vector<int> ecWords(ecSize);
PseudoRandom random(0x12345678);
int iterations = field.size() > 256 ? 1 : DECODER_RANDOM_TEST_ITERATIONS;
for (int i = 0; i < iterations; i++) {
// generate random data
for (auto& val : dataWords) {
val = random.next(0, field.size() - 1);
}
// generate ECC words
std::copy(dataWords.begin(), dataWords.end(), message.begin());
encoder.encode(message, Size(ecWords));
std::copy_n(message.begin() + dataWords.size(), ecSize, ecWords.begin());
// check to see if Decoder can fix up to ecWords/2 random errors
TestDecoder(field, dataWords, ecWords);
}
}
}
TEST(ReedSolomonTest, DataMatrix)
{
// real life test cases
TestEncodeDecode(GenericGF::DataMatrixField256(),
{ 142, 164, 186 }, { 114, 25, 5, 88, 102 });
TestEncodeDecode(GenericGF::DataMatrixField256(), {
0x69, 0x75, 0x75, 0x71, 0x3B, 0x30, 0x30, 0x64,
0x70, 0x65, 0x66, 0x2F, 0x68, 0x70, 0x70, 0x68,
0x6D, 0x66, 0x2F, 0x64, 0x70, 0x6E, 0x30, 0x71,
0x30, 0x7B, 0x79, 0x6A, 0x6F, 0x68, 0x30, 0x81,
0xF0, 0x88, 0x1F, 0xB5 }, {
0x1C, 0x64, 0xEE, 0xEB, 0xD0, 0x1D, 0x00, 0x03,
0xF0, 0x1C, 0xF1, 0xD0, 0x6D, 0x00, 0x98, 0xDA,
0x80, 0x88, 0xBE, 0xFF, 0xB7, 0xFA, 0xA9, 0x95 });
// synthetic test cases
TestEncodeDecodeRandom(GenericGF::DataMatrixField256(), 10, 240);
TestEncodeDecodeRandom(GenericGF::DataMatrixField256(), 128, 127);
TestEncodeDecodeRandom(GenericGF::DataMatrixField256(), 220, 35);
}
TEST(ReedSolomonTest, QRCode)
{
// Test case from example given in ISO 18004, Annex I
TestEncodeDecode(GenericGF::QRCodeField256(), {
0x10, 0x20, 0x0C, 0x56, 0x61, 0x80, 0xEC, 0x11,
0xEC, 0x11, 0xEC, 0x11, 0xEC, 0x11, 0xEC, 0x11 }, {
0xA5, 0x24, 0xD4, 0xC1, 0xED, 0x36, 0xC7, 0x87,
0x2C, 0x55 });
TestEncodeDecode(GenericGF::QRCodeField256(), {
0x72, 0x67, 0x2F, 0x77, 0x69, 0x6B, 0x69, 0x2F,
0x4D, 0x61, 0x69, 0x6E, 0x5F, 0x50, 0x61, 0x67,
0x65, 0x3B, 0x3B, 0x00, 0xEC, 0x11, 0xEC, 0x11,
0xEC, 0x11, 0xEC, 0x11, 0xEC, 0x11, 0xEC, 0x11 }, {
0xD8, 0xB8, 0xEF, 0x14, 0xEC, 0xD0, 0xCC, 0x85,
0x73, 0x40, 0x0B, 0xB5, 0x5A, 0xB8, 0x8B, 0x2E,
0x08, 0x62 });
// real life test cases
// synthetic test cases
TestEncodeDecodeRandom(GenericGF::QRCodeField256(), 10, 240);
TestEncodeDecodeRandom(GenericGF::QRCodeField256(), 128, 127);
TestEncodeDecodeRandom(GenericGF::QRCodeField256(), 220, 35);
}
TEST(ReedSolomonTest, Aztec)
{
// real life test cases
TestEncodeDecode(GenericGF::AztecParam(),
{ 0x5, 0x6 }, { 0x3, 0x2, 0xB, 0xB, 0x7 });
TestEncodeDecode(GenericGF::AztecParam(),
{ 0x0, 0x0, 0x0, 0x9 }, { 0xA, 0xD, 0x8, 0x6, 0x5, 0x6 });
TestEncodeDecode(GenericGF::AztecParam(),
{ 0x2, 0x8, 0x8, 0x7 }, { 0xE, 0xC, 0xA, 0x9, 0x6, 0x8 });
TestEncodeDecode(GenericGF::AztecData6(),
{ 0x9, 0x32, 0x1, 0x29, 0x2F, 0x2, 0x27, 0x25, 0x1, 0x1B },
{ 0x2C, 0x2, 0xD, 0xD, 0xA, 0x16, 0x28, 0x9, 0x22, 0xA, 0x14 });
TestEncodeDecode(GenericGF::AztecData8(), {
0xE0, 0x86, 0x42, 0x98, 0xE8, 0x4A, 0x96, 0xC6,
0xB9, 0xF0, 0x8C, 0xA7, 0x4A, 0xDA, 0xF8, 0xCE,
0xB7, 0xDE, 0x88, 0x64, 0x29, 0x8E, 0x84, 0xA9,
0x6C, 0x6B, 0x9F, 0x08, 0xCA, 0x74, 0xAD, 0xAF,
0x8C, 0xEB, 0x7C, 0x10, 0xC8, 0x53, 0x1D, 0x09,
0x52, 0xD8, 0xD7, 0x3E, 0x11, 0x94, 0xE9, 0x5B,
0x5F, 0x19, 0xD6, 0xFB, 0xD1, 0x0C, 0x85, 0x31,
0xD0, 0x95, 0x2D, 0x8D, 0x73, 0xE1, 0x19, 0x4E,
0x95, 0xB5, 0xF1, 0x9D, 0x6F }, {
0x31, 0xD7, 0x04, 0x46, 0xB2, 0xC1, 0x06, 0x94,
0x17, 0xE5, 0x0C, 0x2B, 0xA3, 0x99, 0x15, 0x7F,
0x16, 0x3C, 0x66, 0xBA, 0x33, 0xD9, 0xE8, 0x87,
0x86, 0xBB, 0x4B, 0x15, 0x4E, 0x4A, 0xDE, 0xD4,
0xED, 0xA1, 0xF8, 0x47, 0x2A, 0x50, 0xA6, 0xBC,
0x53, 0x7D, 0x29, 0xFE, 0x06, 0x49, 0xF3, 0x73,
0x9F, 0xC1, 0x75 });
TestEncodeDecode(GenericGF::AztecData10(), {
0x15C, 0x1E1, 0x2D5, 0x02E, 0x048, 0x1E2, 0x037, 0x0CD,
0x02E, 0x056, 0x26A, 0x281, 0x1C2, 0x1A6, 0x296, 0x045,
0x041, 0x0AA, 0x095, 0x2CE, 0x003, 0x38F, 0x2CD, 0x1A2,
0x036, 0x1AD, 0x04E, 0x090, 0x271, 0x0D3, 0x02E, 0x0D5,
0x2D4, 0x032, 0x2CA, 0x281, 0x0AA, 0x04E, 0x024, 0x2D3,
0x296, 0x281, 0x0E2, 0x08A, 0x1AA, 0x28A, 0x280, 0x07C,
0x286, 0x0A1, 0x1D0, 0x1AD, 0x154, 0x032, 0x2C2, 0x1C1,
0x145, 0x02B, 0x2D4, 0x2B0, 0x033, 0x2D5, 0x276, 0x1C1,
0x282, 0x10A, 0x2B5, 0x154, 0x003, 0x385, 0x20F, 0x0C4,
0x02D, 0x050, 0x266, 0x0D5, 0x033, 0x2D5, 0x276, 0x1C1,
0x0D4, 0x2A0, 0x08F, 0x0C4, 0x024, 0x20F, 0x2E2, 0x1AD,
0x154, 0x02E, 0x056, 0x26A, 0x281, 0x090, 0x1E5, 0x14E,
0x0CF, 0x2B6, 0x1C1, 0x28A, 0x2A1, 0x04E, 0x0D5, 0x003,
0x391, 0x122, 0x286, 0x1AD, 0x2D4, 0x028, 0x262, 0x2EA,
0x0A2, 0x004, 0x176, 0x295, 0x201, 0x0D5, 0x024, 0x20F,
0x116, 0x0C1, 0x056, 0x095, 0x213, 0x004, 0x1EA, 0x28A,
0x02A, 0x234, 0x2CE, 0x037, 0x157, 0x0D3, 0x262, 0x026,
0x262, 0x2A0, 0x086, 0x106, 0x2A1, 0x126, 0x1E5, 0x266,
0x26A, 0x2A1, 0x0E6, 0x1AA, 0x281, 0x2B6, 0x271, 0x154,
0x02F, 0x0C4, 0x02D, 0x213, 0x0CE, 0x003, 0x38F, 0x2CD,
0x1A2, 0x036, 0x1B5, 0x26A, 0x086, 0x280, 0x086, 0x1AA,
0x2A1, 0x226, 0x1AD, 0x0CF, 0x2A6, 0x292, 0x2C6, 0x022,
0x1AA, 0x256, 0x0D5, 0x02D, 0x050, 0x266, 0x0D5, 0x004,
0x176, 0x295, 0x201, 0x0D3, 0x055, 0x031, 0x2CD, 0x2EA,
0x1E2, 0x261, 0x1EA, 0x28A, 0x004, 0x145, 0x026, 0x1A6,
0x1C6, 0x1F5, 0x2CE, 0x034, 0x051, 0x146, 0x1E1, 0x0B0,
0x1B0, 0x261, 0x0D5, 0x025, 0x142, 0x1C0, 0x07C, 0x0B0,
0x1E6, 0x081, 0x044, 0x02F, 0x2CF, 0x081, 0x290, 0x0A2,
0x1A6, 0x281, 0x0CD, 0x155, 0x031, 0x1A2, 0x086, 0x262,
0x2A1, 0x0CD, 0x0CA, 0x0E6, 0x1E5, 0x003, 0x394, 0x0C5,
0x030, 0x26F, 0x053, 0x0C1, 0x1B6, 0x095, 0x2D4, 0x030,
0x26F, 0x053, 0x0C0, 0x07C, 0x2E6, 0x295, 0x143, 0x2CD,
0x2CE, 0x037, 0x0C9, 0x144, 0x2CD, 0x040, 0x08E, 0x054,
0x282, 0x022, 0x2A1, 0x229, 0x053, 0x0D5, 0x262, 0x027,
0x26A, 0x1E8, 0x14D, 0x1A2, 0x004, 0x26A, 0x296, 0x281,
0x176, 0x295, 0x201, 0x0E2, 0x2C4, 0x143, 0x2D4, 0x026,
0x262, 0x2A0, 0x08F, 0x0C4, 0x031, 0x213, 0x2B5, 0x155,
0x213, 0x02F, 0x143, 0x121, 0x2A6, 0x1AD, 0x2D4, 0x034,
0x0C5, 0x026, 0x295, 0x003, 0x396, 0x2A1, 0x176, 0x295,
0x201, 0x0AA, 0x04E, 0x004, 0x1B0, 0x070, 0x275, 0x154,
0x026, 0x2C1, 0x2B3, 0x154, 0x2AA, 0x256, 0x0C1, 0x044,
0x004, 0x23F }, {
0x379, 0x099, 0x348, 0x010, 0x090, 0x196, 0x09C, 0x1FF,
0x1B0, 0x32D, 0x244, 0x0DE, 0x201, 0x386, 0x163, 0x11F,
0x39B, 0x344, 0x3FE, 0x02F, 0x188, 0x113, 0x3D9, 0x102,
0x04A, 0x2E1, 0x1D1, 0x18E, 0x077, 0x262, 0x241, 0x20D,
0x1B8, 0x11D, 0x0D0, 0x0A5, 0x29C, 0x24D, 0x3E7, 0x006,
0x2D0, 0x1B7, 0x337, 0x178, 0x0F1, 0x1E0, 0x00B, 0x01E,
0x0DA, 0x1C6, 0x2D9, 0x00D, 0x28B, 0x34A, 0x252, 0x27A,
0x057, 0x0CA, 0x2C2, 0x2E4, 0x3A6, 0x0E3, 0x22B, 0x307,
0x174, 0x292, 0x10C, 0x1ED, 0x2FD, 0x2D4, 0x0A7, 0x051,
0x34F, 0x07A, 0x1D5, 0x01D, 0x22E, 0x2C2, 0x1DF, 0x08F,
0x105, 0x3FE, 0x286, 0x2A2, 0x3B1, 0x131, 0x285, 0x362,
0x315, 0x13C, 0x0F9, 0x1A2, 0x28D, 0x246, 0x1B3, 0x12C,
0x2AD, 0x0F8, 0x222, 0x0EC, 0x39F, 0x358, 0x014, 0x229,
0x0C8, 0x360, 0x1C2, 0x031, 0x098, 0x041, 0x3E4, 0x046,
0x332, 0x318, 0x2E3, 0x24E, 0x3E2, 0x1E1, 0x0BE, 0x239,
0x306, 0x3A5, 0x352, 0x351, 0x275, 0x0ED, 0x045, 0x229,
0x0BF, 0x05D, 0x253, 0x1BE, 0x02E, 0x35A, 0x0E4, 0x2E9,
0x17A, 0x166, 0x03C, 0x007 });
TestEncodeDecode(GenericGF::AztecData12(), {
0x571, 0xE1B, 0x542, 0xE12, 0x1E2, 0x0DC, 0xCD0, 0xB85,
0x69A, 0xA81, 0x709, 0xA6A, 0x584, 0x510, 0x4AA, 0x256,
0xCE0, 0x0F8, 0xFB3, 0x5A2, 0x0D9, 0xAD1, 0x389, 0x09C,
0x4D3, 0x0B8, 0xD5B, 0x503, 0x2B2, 0xA81, 0x2A8, 0x4E0,
0x92D, 0x3A5, 0xA81, 0x388, 0x8A6, 0xAA8, 0xAA0, 0x07C,
0xA18, 0xA17, 0x41A, 0xD55, 0x032, 0xB09, 0xC15, 0x142,
0xBB5, 0x2B0, 0x0CE, 0xD59, 0xD9C, 0x1A0, 0x90A, 0xAD5,
0x540, 0x0F8, 0x583, 0xCC4, 0x0B4, 0x509, 0x98D, 0x50C,
0xED5, 0x9D9, 0xC13, 0x52A, 0x023, 0xCC4, 0x092, 0x0FB,
0x89A, 0xD55, 0x02E, 0x15A, 0x6AA, 0x049, 0x079, 0x54E,
0x33E, 0xB67, 0x068, 0xAA8, 0x44E, 0x354, 0x03E, 0x452,
0x2A1, 0x9AD, 0xB50, 0x289, 0x8AE, 0xA28, 0x804, 0x5DA,
0x958, 0x04D, 0x509, 0x20F, 0x458, 0xC11, 0x589, 0x584,
0xC04, 0x7AA, 0x8A0, 0xAA3, 0x4B3, 0x837, 0x55C, 0xD39,
0x882, 0x698, 0xAA0, 0x219, 0x06A, 0x852, 0x679, 0x666,
0x9AA, 0xA13, 0x99A, 0xAA0, 0x6B6, 0x9C5, 0x540, 0xBCC,
0x40B, 0x613, 0x338, 0x03E, 0x3EC, 0xD68, 0x836, 0x6D6,
0x6A2, 0x1A8, 0x021, 0x9AA, 0xA86, 0x266, 0xB4C, 0xFA9,
0xA92, 0xB18, 0x226, 0xAA5, 0x635, 0x42D, 0x142, 0x663,
0x540, 0x45D, 0xA95, 0x804, 0xD31, 0x543, 0x1B3, 0x6EA,
0x78A, 0x617, 0xAA8, 0xA01, 0x145, 0x099, 0xA67, 0x19F,
0x5B3, 0x834, 0x145, 0x467, 0x84B, 0x06C, 0x261, 0x354,
0x255, 0x09C, 0x01F, 0x0B0, 0x798, 0x811, 0x102, 0xFB3,
0xC81, 0xA40, 0xA26, 0x9A8, 0x133, 0x555, 0x0C5, 0xA22,
0x1A6, 0x2A8, 0x4CD, 0x328, 0xE67, 0x940, 0x3E5, 0x0C5,
0x0C2, 0x6F1, 0x4CC, 0x16D, 0x895, 0xB50, 0x309, 0xBC5,
0x330, 0x07C, 0xB9A, 0x955, 0x0EC, 0xDB3, 0x837, 0x325,
0x44B, 0x344, 0x023, 0x854, 0xA08, 0x22A, 0x862, 0x914,
0xCD5, 0x988, 0x279, 0xA9E, 0x853, 0x5A2, 0x012, 0x6AA,
0x5A8, 0x15D, 0xA95, 0x804, 0xE2B, 0x114, 0x3B5, 0x026,
0x98A, 0xA02, 0x3CC, 0x40C, 0x613, 0xAD5, 0x558, 0x4C2,
0xF50, 0xD21, 0xA99, 0xADB, 0x503, 0x431, 0x426, 0xA54,
0x03E, 0x5AA, 0x15D, 0xA95, 0x804, 0xAA1, 0x380, 0x46C,
0x070, 0x9D5, 0x540, 0x9AC, 0x1AC, 0xD54, 0xAAA, 0x563,
0x044, 0x401, 0x220, 0x9F1, 0x4F0, 0xDAA, 0x170, 0x90F,
0x106, 0xE66, 0x85C, 0x2B4, 0xD54, 0x0B8, 0x4D3, 0x52C,
0x228, 0x825, 0x512, 0xB67, 0x007, 0xC7D, 0x9AD, 0x106,
0xCD6, 0x89C, 0x484, 0xE26, 0x985, 0xC6A, 0xDA8, 0x195,
0x954, 0x095, 0x427, 0x049, 0x69D, 0x2D4, 0x09C, 0x445,
0x355, 0x455, 0x003, 0xE50, 0xC50, 0xBA0, 0xD6A, 0xA81,
0x958, 0x4E0, 0xA8A, 0x15D, 0xA95, 0x806, 0x76A, 0xCEC,
0xE0D, 0x048, 0x556, 0xAAA, 0x007, 0xC2C, 0x1E6, 0x205,
0xA28, 0x4CC, 0x6A8, 0x676, 0xACE, 0xCE0, 0x9A9, 0x501,
0x1E6, 0x204, 0x907, 0xDC4, 0xD6A, 0xA81, 0x70A, 0xD35,
0x502, 0x483, 0xCAA, 0x719, 0xF5B, 0x383, 0x455, 0x422,
0x71A, 0xA01, 0xF22, 0x915, 0x0CD, 0x6DA, 0x814, 0x4C5,
0x751, 0x440, 0x22E, 0xD4A, 0xC02, 0x6A8, 0x490, 0x7A2,
0xC60, 0x8AC, 0x4AC, 0x260, 0x23D, 0x545, 0x055, 0x1A5,
0x9C1, 0xBAA, 0xE69, 0xCC4, 0x134, 0xC55, 0x010, 0xC83,
0x542, 0x933, 0xCB3, 0x34D, 0x550, 0x9CC, 0xD55, 0x035,
0xB4E, 0x2AA, 0x05E, 0x620, 0x5B0, 0x999, 0xC01, 0xF1F,
0x66B, 0x441, 0xB36, 0xB35, 0x10D, 0x401, 0x0CD, 0x554,
0x313, 0x35A, 0x67D, 0x4D4, 0x958, 0xC11, 0x355, 0x2B1,
0xAA1, 0x68A, 0x133, 0x1AA, 0x022, 0xED4, 0xAC0, 0x269,
0x8AA, 0x18D, 0x9B7, 0x53C, 0x530, 0xBD5, 0x450, 0x08A,
0x284, 0xCD3, 0x38C, 0xFAD, 0x9C1, 0xA0A, 0x2A3, 0x3C2,
0x583, 0x613, 0x09A, 0xA12, 0xA84, 0xE00, 0xF85, 0x83C,
0xC40, 0x888, 0x17D, 0x9E4, 0x0D2, 0x051, 0x34D, 0x409,
0x9AA, 0xA86, 0x2D1, 0x10D, 0x315, 0x426, 0x699, 0x473,
0x3CA, 0x01F, 0x286, 0x286, 0x137, 0x8A6, 0x60B, 0x6C4,
0xADA, 0x818, 0x4DE, 0x299, 0x803, 0xE5C, 0xD4A, 0xA87,
0x66D, 0x9C1, 0xB99, 0x2A2, 0x59A, 0x201, 0x1C2, 0xA50,
0x411, 0x543, 0x148, 0xA66, 0xACC, 0x413, 0xCD4, 0xF42,
0x9AD, 0x100, 0x935, 0x52D, 0x40A, 0xED4, 0xAC0, 0x271,
0x588, 0xA1D, 0xA81, 0x34C, 0x550, 0x11E, 0x620, 0x630,
0x9D6, 0xAAA, 0xC26, 0x17A, 0x869, 0x0D4, 0xCD6, 0xDA8,
0x1A1, 0x8A1, 0x352, 0xA01, 0xF2D, 0x50A, 0xED4, 0xAC0,
0x255, 0x09C, 0x023, 0x603, 0x84E, 0xAAA, 0x04D, 0x60D,
0x66A, 0xA55, 0x52B, 0x182, 0x220, 0x091, 0x00F, 0x8A7,
0x86D, 0x50B, 0x848, 0x788, 0x373, 0x342, 0xE15, 0xA6A,
0xA05, 0xC26, 0x9A9, 0x611, 0x441, 0x2A8, 0x95B, 0x380,
0x3E3, 0xECD, 0x688, 0x366, 0xB44, 0xE24, 0x271, 0x34C,
0x2E3, 0x56D, 0x40C, 0xACA, 0xA04, 0xAA1, 0x382, 0x4B4,
0xE96, 0xA04, 0xE22, 0x29A, 0xAA2, 0xA80, 0x1F2, 0x862,
0x85D, 0x06B, 0x554, 0x0CA, 0xC27, 0x054, 0x50A, 0xED4,
0xAC0, 0x33B, 0x567, 0x670, 0x682, 0x42A, 0xB55, 0x500,
0x3E1, 0x60F, 0x310, 0x2D1, 0x426, 0x635, 0x433, 0xB56,
0x767, 0x04D, 0x4A8, 0x08F, 0x310, 0x248, 0x3EE, 0x26B,
0x554, 0x0B8, 0x569, 0xAA8, 0x124, 0x1E5, 0x538, 0xCFA,
0xD9C, 0x1A2, 0xAA1, 0x138, 0xD50, 0x0F9, 0x148, 0xA86,
0x6B6, 0xD40, 0xA26, 0x2BA, 0x8A2, 0x011, 0x76A, 0x560,
0x135, 0x424, 0x83D, 0x163, 0x045, 0x625, 0x613, 0x011,
0xEAA, 0x282, 0xA8D, 0x2CE, 0x0DD, 0x573, 0x4E6, 0x209,
0xA62, 0xA80, 0x864, 0x1AA, 0x149, 0x9E5, 0x99A, 0x6AA,
0x84E, 0x66A, 0xA81, 0xADA, 0x715, 0x502, 0xF31, 0x02D,
0x84C, 0xCE0, 0x0F8, 0xFB3, 0x5A2, 0x0D9, 0xB59, 0xA88,
0x6A0, 0x086, 0x6AA, 0xA18, 0x99A, 0xD33, 0xEA6, 0xA4A,
0xC60, 0x89A, 0xA95, 0x8D5, 0x0B4, 0x509, 0x98D, 0x501,
0x176, 0xA56, 0x013, 0x4C5, 0x50C, 0x6CD, 0xBA9, 0xE29,
0x85E, 0xAA2, 0x804, 0x514, 0x266, 0x99C, 0x67D, 0x6CE,
0x0D0, 0x515, 0x19E, 0x12C, 0x1B0, 0x984, 0xD50, 0x954,
0x270, 0x07C, 0x2C1, 0xE62, 0x044, 0x40B, 0xECF, 0x206,
0x902, 0x89A, 0x6A0, 0x4CD, 0x554, 0x316, 0x888, 0x698,
0xAA1, 0x334, 0xCA3, 0x99E, 0x500, 0xF94, 0x314, 0x309,
0xBC5, 0x330, 0x5B6, 0x256, 0xD40, 0xC26, 0xF14, 0xCC0,
0x1F2, 0xE6A, 0x554, 0x3B3, 0x6CE, 0x0DC, 0xC95, 0x12C,
0xD10, 0x08E, 0x152, 0x820, 0x8AA, 0x18A, 0x453, 0x356,
0x620, 0x9E6, 0xA7A, 0x14D, 0x688, 0x049, 0xAA9, 0x6A0,
0x576, 0xA56, 0x013, 0x8AC, 0x450, 0xED4, 0x09A, 0x62A,
0x808, 0xF31, 0x031, 0x84E, 0xB55, 0x561, 0x30B, 0xD43,
0x486, 0xA66, 0xB6D, 0x40D, 0x0C5, 0x09A, 0x950, 0x0F9,
0x6A8, 0x576, 0xA56, 0x012, 0xA84, 0xE01, 0x1B0, 0x1C2,
0x755, 0x502, 0x6B0, 0x6B3, 0x552, 0xAA9, 0x58C, 0x111,
0x004, 0x882, 0x7C5, 0x3C3, 0x6A8, 0x5C2, 0x43C, 0x41B,
0x99A, 0x170, 0xAD3, 0x550, 0x2E1, 0x34D, 0x4B0, 0x8A2,
0x095, 0x44A, 0xD9C, 0x01F, 0x1F6, 0x6B4, 0x41B, 0x35A,
0x271, 0x213, 0x89A, 0x617, 0x1AB, 0x6A0, 0x656, 0x550,
0x255, 0x09C, 0x125, 0xA74, 0xB50, 0x271, 0x114, 0xD55,
0x154, 0x00F, 0x943, 0x142, 0xE83, 0x5AA, 0xA06, 0x561,
0x382, 0xA28, 0x576, 0xA56, 0x019, 0xDAB, 0x3B3, 0x834,
0x121, 0x55A, 0xAA8, 0x01F, 0x0B0, 0x798, 0x816, 0x8A1,
0x331, 0xAA1, 0x9DA, 0xB3B, 0x382, 0x6A5, 0x404, 0x798,
0x812, 0x41F, 0x713, 0x5AA, 0xA05, 0xC2B, 0x4D5, 0x409,
0x20F, 0x2A9, 0xC67, 0xD6C, 0xE0D, 0x155, 0x089, 0xC6A,
0x807, 0xC8A, 0x454, 0x335, 0xB6A, 0x051, 0x315, 0xD45,
0x100, 0x8BB, 0x52B, 0x009, 0xAA1, 0x241, 0xE8B, 0x182,
0x2B1, 0x2B0, 0x980, 0x8F5, 0x514, 0x154, 0x696, 0x706,
0xEAB, 0x9A7, 0x310, 0x4D3, 0x154, 0x043, 0x20D, 0x50A,
0x4CF, 0x2CC, 0xD35, 0x542, 0x733, 0x554, 0x0D6, 0xD38,
0xAA8, 0x179, 0x881, 0x6C2, 0x667, 0x007, 0xC7D, 0x9AD,
0x106, 0xCDA, 0xCD4, 0x435, 0x004, 0x335, 0x550, 0xC4C,
0xD69, 0x9F5, 0x352, 0x563, 0x044, 0xD54, 0xAC6, 0xA85,
0xA28, 0x4CC, 0x6A8, 0x08B, 0xB52, 0xB00, 0x9A6, 0x2A8,
0x636, 0x6DD, 0x4F1, 0x4C2, 0xF55, 0x140, 0x228, 0xA13,
0x34C, 0xE33, 0xEB6, 0x706, 0x828, 0xA8C, 0xF09, 0x60D,
0x84C, 0x26A, 0x84A, 0xA13, 0x803, 0xE16, 0x0F3, 0x102,
0x220, 0x5F6, 0x790, 0x348, 0x144, 0xD35, 0x026, 0x6AA,
0xA18, 0xB44, 0x434, 0xC55, 0x099, 0xA65, 0x1CC, 0xF28,
0x07C, 0xA18, 0xA18, 0x4DE, 0x299, 0x82D, 0xB12, 0xB6A,
0x061, 0x378, 0xA66, 0x00F, 0x973, 0x52A, 0xA1D, 0x9B6,
0x706, 0xE64, 0xA89, 0x668, 0x804, 0x70A, 0x941, 0x045,
0x50C, 0x522, 0x99A, 0xB31, 0x04F, 0x353, 0xD0A, 0x6B4,
0x402, 0x4D5, 0x4B5, 0x02B, 0xB52, 0xB00, 0x9C5, 0x622,
0x876, 0xA04, 0xD31, 0x540, 0x479, 0x881, 0x8C2, 0x75A,
0xAAB, 0x098, 0x5EA, 0x1A4, 0x353, 0x35B, 0x6A0, 0x686,
0x284, 0xD4A, 0x807, 0xCB5, 0x42B, 0xB52, 0xB00, 0x954,
0x270, 0x08D, 0x80E, 0x13A, 0xAA8, 0x135, 0x835, 0x9AA,
0x801, 0xF14, 0xF0D, 0xAA1, 0x709, 0x0F1, 0x06E, 0x668,
0x5C2, 0xB4D, 0x540, 0xB84, 0xD35, 0x2C2, 0x288, 0x255,
0x12B, 0x670, 0x07C, 0x7D9, 0xAD1, 0x06C, 0xD68, 0x9C4,
0x84E, 0x269, 0x85C, 0x6AD, 0xA81, 0x959, 0x540, 0x954,
0x270, 0x496, 0x9D2, 0xD40, 0x9C4, 0x453, 0x554, 0x550,
0x03E, 0x50C, 0x50B, 0xA0D, 0x6AA, 0x819, 0x584, 0xE0A,
0x8A1, 0x5DA, 0x958, 0x067, 0x6AC, 0xECE, 0x0D0, 0x485,
0x56A, 0xAA0, 0x07C, 0x2C1, 0xE62, 0x05A, 0x284, 0xCC6,
0xA86, 0x76A, 0xCEC, 0xE09, 0xA95, 0x011, 0xE62, 0x049,
0x07D, 0xC4D, 0x6AA, 0x817, 0x0AD, 0x355, 0x024, 0x83C,
0xAA7, 0x19F, 0x5B3, 0x834, 0x554, 0x227, 0x1AA, 0x01F,
0x229, 0x150, 0xCD6, 0xDA8, 0x144, 0xC57, 0x514, 0x402,
0x2ED, 0x4AC, 0x026, 0xA84, 0x907, 0xA2C, 0x608, 0xAC4,
0xAC2, 0x602, 0x3D5, 0x450, 0x551, 0xA59, 0xC1B, 0xAAE,
0x69C, 0xC41, 0x34C, 0x550, 0x10C, 0x835, 0x429, 0x33C,
0xB33, 0x4D5, 0x509, 0xCCD, 0x550, 0x35B, 0x4E2, 0xAA0,
0x5E6, 0x205, 0xB09, 0x99C, 0x09F }, {
0xD54, 0x221, 0x154, 0x7CD, 0xBF3, 0x112, 0x89B, 0xC5E,
0x9CD, 0x07E, 0xFB6, 0x78F, 0x7FA, 0x16F, 0x377, 0x4B4,
0x62D, 0x475, 0xBC2, 0x861, 0xB72, 0x9D0, 0x76A, 0x5A1,
0x22A, 0xF74, 0xDBA, 0x8B1, 0x139, 0xDCD, 0x012, 0x293,
0x705, 0xA34, 0xDD5, 0x3D2, 0x7F8, 0x0A6, 0x89A, 0x346,
0xCE0, 0x690, 0x40E, 0xFF3, 0xC4D, 0x97F, 0x9C9, 0x016,
0x73A, 0x923, 0xBCE, 0xFA9, 0xE6A, 0xB92, 0x02A, 0x07C,
0x04B, 0x8D5, 0x753, 0x42E, 0x67E, 0x87C, 0xEE6, 0xD7D,
0x2BF, 0xFB2, 0xFF8, 0x42F, 0x4CB, 0x214, 0x779, 0x02D,
0x606, 0xA02, 0x08A, 0xD4F, 0xB87, 0xDDF, 0xC49, 0xB51,
0x0E9, 0xF89, 0xAEF, 0xC92, 0x383, 0x98D, 0x367, 0xBD3,
0xA55, 0x148, 0x9DB, 0x913, 0xC79, 0x6FF, 0x387, 0x6EA,
0x7FA, 0xC1B, 0x12D, 0x303, 0xBCA, 0x503, 0x0FB, 0xB14,
0x0D4, 0xAD1, 0xAFC, 0x9DD, 0x404, 0x145, 0x6E5, 0x8ED,
0xF94, 0xD72, 0x645, 0xA21, 0x1A8, 0xABF, 0xC03, 0x91E,
0xD53, 0x48C, 0x471, 0x4E4, 0x408, 0x33C, 0x5DF, 0x73D,
0xA2A, 0x454, 0xD77, 0xC48, 0x2F5, 0x96A, 0x9CF, 0x047,
0x611, 0xE92, 0xC2F, 0xA98, 0x56D, 0x919, 0x615, 0x535,
0x67A, 0x8C1, 0x2E2, 0xBC4, 0xBE8, 0x328, 0x04F, 0x257,
0x3F9, 0xFA5, 0x477, 0x12E, 0x94B, 0x116, 0xEF7, 0x65F,
0x6B3, 0x915, 0xC64, 0x9AF, 0xB6C, 0x6A2, 0x50D, 0xEA3,
0x26E, 0xC23, 0x817, 0xA42, 0x71A, 0x9DD, 0xDA8, 0x84D,
0x3F3, 0x85B, 0xB00, 0x1FC, 0xB0A, 0xC2F, 0x00C, 0x095,
0xC58, 0x0E3, 0x807, 0x962, 0xC4B, 0x29A, 0x6FC, 0x958,
0xD29, 0x59E, 0xB14, 0x95A, 0xEDE, 0xF3D, 0xFB8, 0x0E5,
0x348, 0x2E7, 0x38E, 0x56A, 0x410, 0x3B1, 0x4B0, 0x793,
0xAB7, 0x0BC, 0x648, 0x719, 0xE3E, 0xFB4, 0x3B4, 0xE5C,
0x950, 0xD2A, 0x50B, 0x76F, 0x8D2, 0x3C7, 0xECC, 0x87C,
0x53A, 0xBA7, 0x4C3, 0x148, 0x437, 0x820, 0xECD, 0x660,
0x095, 0x2F4, 0x661, 0x6A4, 0xB74, 0x5F3, 0x1D2, 0x7EC,
0x8E2, 0xA40, 0xA6F, 0xFC3, 0x3BE, 0x1E9, 0x52C, 0x233,
0x173, 0x4EF, 0xA7C, 0x40B, 0x14C, 0x88D, 0xF30, 0x8D9,
0xBDB, 0x0A6, 0x940, 0xD46, 0xB2B, 0x03E, 0x46A, 0x641,
0xF08, 0xAFF, 0x496, 0x68A, 0x7A4, 0x0BA, 0xD43, 0x515,
0xB26, 0xD8F, 0x05C, 0xD6E, 0xA2C, 0xF25, 0x628, 0x4E5,
0x81D, 0xA2A, 0x1FF, 0x302, 0xFBD, 0x6D9, 0x711, 0xD8B,
0xE5C, 0x5CF, 0x42E, 0x008, 0x863, 0xB6F, 0x1E1, 0x3DA,
0xACE, 0x82B, 0x2DB, 0x7EB, 0xC15, 0x79F, 0xA79, 0xDAF,
0x00D, 0x2F6, 0x0CE, 0x370, 0x7E8, 0x9E6, 0x89F, 0xAE9,
0x175, 0xA95, 0x06B, 0x9DF, 0xAFF, 0x45B, 0x823, 0xAA4,
0xC79, 0x773, 0x886, 0x854, 0x0A5, 0x6D1, 0xE55, 0xEBB,
0x518, 0xE50, 0xF8F, 0x8CC, 0x834, 0x388, 0xCD2, 0xFC1,
0xA55, 0x1F8, 0xD1F, 0xE08, 0xF93, 0x362, 0xA22, 0x9FA,
0xCE5, 0x3C3, 0xDD4, 0xC53, 0xB94, 0xAD0, 0x6EB, 0x68D,
0x660, 0x8FC, 0xBCD, 0x914, 0x16F, 0x4C0, 0x134, 0xE1A,
0x76F, 0x9CB, 0x660, 0xEA0, 0x320, 0x15A, 0xCE3, 0x7E8,
0x03E, 0xB9A, 0xC90, 0xA14, 0x256, 0x1A8, 0x639, 0x7C6,
0xA59, 0xA65, 0x956, 0x9E4, 0x592, 0x6A9, 0xCFF, 0x4DC,
0xAA3, 0xD2A, 0xFDE, 0xA87, 0xBF5, 0x9F0, 0xC32, 0x94F,
0x675, 0x9A6, 0x369, 0x648, 0x289, 0x823, 0x498, 0x574,
0x8D1, 0xA13, 0xD1A, 0xBB5, 0xA19, 0x7F7, 0x775, 0x138,
0x949, 0xA4C, 0xE36, 0x126, 0xC85, 0xE05, 0xFEE, 0x962,
0x36D, 0x08D, 0xC76, 0x1E1, 0x1EC, 0x8D7, 0x231, 0xB68,
0x03C, 0x1DE, 0x7DF, 0x2B1, 0x09D, 0xC81, 0xDA4, 0x8F7,
0x6B9, 0x947, 0x9B0 });
// synthetic test cases
TestEncodeDecodeRandom(GenericGF::AztecParam(), 2, 5); // compact mode message
TestEncodeDecodeRandom(GenericGF::AztecParam(), 4, 6); // full mode message
TestEncodeDecodeRandom(GenericGF::AztecData6(), 10, 7);
TestEncodeDecodeRandom(GenericGF::AztecData6(), 20, 12);
TestEncodeDecodeRandom(GenericGF::AztecData8(), 20, 11);
TestEncodeDecodeRandom(GenericGF::AztecData8(), 128, 127);
TestEncodeDecodeRandom(GenericGF::AztecData10(), 128, 128);
TestEncodeDecodeRandom(GenericGF::AztecData10(), 768, 255);
TestEncodeDecodeRandom(GenericGF::AztecData12(), 3072, 1023);
}
```
|
/content/code_sandbox/test/unit/ReedSolomonTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 15,561
|
```c++
/*
*/
#include "BitArrayUtility.h"
#include "BitArray.h"
namespace ZXing { namespace Utility {
std::string ToString(const BitArray& arr)
{
return ToString(arr, 'X', '.');
}
std::string ToString(const BitArray& arr, char one, char zero)
{
std::string result;
result.reserve(arr.size());
for (bool bit : arr)
result.push_back(bit ? one : zero);
return result;
}
BitArray ParseBitArray(std::string_view str, char one)
{
BitArray result(Size(str));
for (int i = 0; i < Size(str); ++i)
result.set(i, str[i] == one);
return result;
}
}} // ZXing::Utility
```
|
/content/code_sandbox/test/unit/BitArrayUtility.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 152
|
```c++
/*
*/
#include "qrcode/QRDecoder.h"
#include "BitMatrix.h"
#include "BitMatrixIO.h"
#include "DecoderResult.h"
#include "gtest/gtest.h"
using namespace ZXing;
using namespace ZXing::QRCode;
TEST(MQRDecoderTest, MQRCodeM3L)
{
const auto bitMatrix = ParseBitMatrix("XXXXXXX X X X X\n"
"X X X X \n"
"X XXX X XXXXXXX\n"
"X XXX X X X XX\n"
"X XXX X X XX\n"
"X X X X X X\n"
"XXXXXXX X XX \n"
" X X X\n"
"XXXXXX X X X\n"
" X XX XXX\n"
"XXX XX XXXX XXX\n"
" X X XXX X \n"
"X XXXXX XXX X X\n"
" X X X XXX \n"
"XXX XX X X XXXX\n",
88, false);
const auto result = Decode(bitMatrix);
EXPECT_TRUE(result.isValid());
}
TEST(MQRDecoderTest, MQRCodeM3M)
{
const auto bitMatrix = ParseBitMatrix("XXXXXXX X X X X\n"
"X X XX\n"
"X XXX X X XX XX\n"
"X XXX X X X \n"
"X XXX X XX XXXX\n"
"X X XX \n"
"XXXXXXX X XXXX\n"
" X XXX \n"
"X XX XX X X\n"
" X X XX \n"
"XX XX XXXXXXX\n"
" X X X\n"
"XX X X X \n"
" X X X \n"
"X X XXXX XXX\n",
88, false);
const auto result = Decode(bitMatrix);
EXPECT_TRUE(result.isValid());
}
TEST(MQRDecoderTest, MQRCodeM1)
{
const auto bitMatrix = ParseBitMatrix("XXXXXXX X X\n"
"X X \n"
"X XXX X XXX\n"
"X XXX X XX\n"
"X XXX X X\n"
"X X XX \n"
"XXXXXXX X \n"
" X \n"
"XX X \n"
" X XXXXX X\n"
"X XXXXXX X\n",
88, false);
const auto result = Decode(bitMatrix);
EXPECT_TRUE(result.isValid());
EXPECT_EQ(L"123", result.text());
}
TEST(MQRDecoderTest, MQRCodeM1Error4Bits)
{
const auto bitMatrix = ParseBitMatrix("XXXXXXX X X\n"
"X X XX\n"
"X XXX X X \n"
"X XXX X XX\n"
"X XXX X X\n"
"X X XX \n"
"XXXXXXX X \n"
" X \n"
"XX X \n"
" X XXXXXX \n"
"X XXXXXXX \n",
88, false);
const auto result = Decode(bitMatrix);
EXPECT_EQ(Error::Checksum, result.error());
EXPECT_TRUE(result.text().empty());
}
TEST(MQRDecoderTest, MQRCodeM4)
{
const auto bitMatrix = ParseBitMatrix("XXXXXXX X X X X X\n"
"X X XX X XX\n"
"X XXX X X X XX\n"
"X XXX X XX XX XX\n"
"X XXX X X XXXXX\n"
"X X XX X\n"
"XXXXXXX XX X XX\n"
" X XX XX\n"
"X X XXX X XXX\n"
" XX X XX XX X \n"
"XX XXXX X XX XX\n"
" XX XX X XX XX\n"
"XXX XXX XXX XX XX\n"
" X X X XX X\n"
"X X XX XXXXX \n"
" X X X X X \n"
"X XXXXXXX X X X\n",
88, false);
const auto result = Decode(bitMatrix);
EXPECT_TRUE(result.isValid());
}
```
|
/content/code_sandbox/test/unit/qrcode/MQRDecoderTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 966
|
```c++
/*
*/
#include "HRI.h"
#include "gtest/gtest.h"
using namespace ZXing;
TEST(HRIFromGS1, Single)
{
// 2-digit AIs
// Fixed length
EXPECT_EQ(HRIFromGS1("00123456789012345678"), "(00)123456789012345678");
// Incorrect lengths
EXPECT_EQ(HRIFromGS1("0012345678901234567"), "");
EXPECT_EQ(HRIFromGS1("001234567890123456789"), "");
// Fixed length
EXPECT_EQ(HRIFromGS1("16123456"), "(16)123456");
// Incorrect lengths
EXPECT_EQ(HRIFromGS1("1612345"), "");
EXPECT_EQ(HRIFromGS1("161234567"), "");
// Max length
EXPECT_EQ(HRIFromGS1("2212345678901234567890"), "(22)12345678901234567890");
EXPECT_EQ(HRIFromGS1("221234567890123456789"), "(22)1234567890123456789");
// Too long
EXPECT_EQ(HRIFromGS1("22123456789012345678901"), "");
// Max length
EXPECT_EQ(HRIFromGS1(your_sha256_hash3456789012345678901234567890"),
"(91)your_sha256_hash56789012345678901234567890");
EXPECT_EQ(HRIFromGS1(your_sha256_hash345678901234567890123456789"),
"(91)your_sha256_hash5678901234567890123456789");
// Too long
EXPECT_EQ(HRIFromGS1(your_sha256_hash34567890123456789012345678901"), "");
// Max length
EXPECT_EQ(HRIFromGS1(your_sha256_hash3456789012345678901234567890"),
"(99)your_sha256_hash56789012345678901234567890");
EXPECT_EQ(HRIFromGS1(your_sha256_hash345678901234567890123456789"),
"(99)your_sha256_hash5678901234567890123456789");
// Too long
EXPECT_EQ(HRIFromGS1(your_sha256_hash34567890123456789012345678901"), "");
// 3-digit AIs
EXPECT_EQ(HRIFromGS1("310"), ""); // incomplete prefix
// Max length
EXPECT_EQ(HRIFromGS1("2351234567890123456789012345678"), "(235)1234567890123456789012345678");
EXPECT_EQ(HRIFromGS1("235123456789012345678901234567"), "(235)123456789012345678901234567");
// Too long
EXPECT_EQ(HRIFromGS1("23512345678901234567890123456789"), "");
// Max length
EXPECT_EQ(HRIFromGS1("24312345678901234567890"), "(243)12345678901234567890");
EXPECT_EQ(HRIFromGS1("2431234567890123456789"), "(243)1234567890123456789");
// Too long
EXPECT_EQ(HRIFromGS1("243123456789012345678901"), "");
// Max length
EXPECT_EQ(HRIFromGS1("253123456789012345678901234567890"), "(253)123456789012345678901234567890");
EXPECT_EQ(HRIFromGS1("25312345678901234567890123456789"), "(253)12345678901234567890123456789");
// Too long
EXPECT_EQ(HRIFromGS1("2531234567890123456789012345678901"), "");
// Max length
EXPECT_EQ(HRIFromGS1("2551234567890123456789012345"), "(255)1234567890123456789012345");
EXPECT_EQ(HRIFromGS1("255123456789012345678901234"), "(255)123456789012345678901234");
// Too long
EXPECT_EQ(HRIFromGS1("25512345678901234567890123456"), "");
// Fixed length
EXPECT_EQ(HRIFromGS1("4151234567890123"), "(415)1234567890123");
// Incorrect lengths
EXPECT_EQ(HRIFromGS1("415123456789012"), "");
EXPECT_EQ(HRIFromGS1("41512345678901234"), "");
// Fixed length
EXPECT_EQ(HRIFromGS1("4171234567890123"), "(417)1234567890123");
// Incorrect lengths
EXPECT_EQ(HRIFromGS1("417123456789012"), "");
EXPECT_EQ(HRIFromGS1("41712345678901234"), "");
// Max length
EXPECT_EQ(HRIFromGS1("421123456789012"), "(421)123456789012");
EXPECT_EQ(HRIFromGS1("42112345678901"), "(421)12345678901");
// Too long
EXPECT_EQ(HRIFromGS1("4211234567890123"), "");
// Max length
EXPECT_EQ(HRIFromGS1("425123456789012345"), "(425)123456789012345");
EXPECT_EQ(HRIFromGS1("42512345678901234"), "(425)12345678901234");
// Too long
EXPECT_EQ(HRIFromGS1("4251234567890123456"), "");
// Max length
EXPECT_EQ(HRIFromGS1("427123"), "(427)123");
EXPECT_EQ(HRIFromGS1("42712"), "(427)12");
// Too long
EXPECT_EQ(HRIFromGS1("4271234"), "");
// Max length
EXPECT_EQ(HRIFromGS1("71012345678901234567890"), "(710)12345678901234567890");
EXPECT_EQ(HRIFromGS1("7101234567890123456789"), "(710)1234567890123456789");
// Too long
EXPECT_EQ(HRIFromGS1("710123456789012345678901"), "");
// Max length
EXPECT_EQ(HRIFromGS1("71512345678901234567890"), "(715)12345678901234567890");
EXPECT_EQ(HRIFromGS1("7151234567890123456789"), "(715)1234567890123456789");
// Too long
EXPECT_EQ(HRIFromGS1("715123456789012345678901"), "");
// 4-digit variable 4th
// Fixed length
EXPECT_EQ(HRIFromGS1("3370123456"), "(3370)123456");
// Incorrect lengths
EXPECT_EQ(HRIFromGS1("337012345"), "");
EXPECT_EQ(HRIFromGS1("33701234567"), "");
// Fixed length
EXPECT_EQ(HRIFromGS1("3375123456"), "(3375)123456");
// Incorrect lengths
EXPECT_EQ(HRIFromGS1("33751234567"), "");
EXPECT_EQ(HRIFromGS1("337512345"), "");
// EXPECT_EQ(ParseFieldsInGeneralPurpose("3376123456"), // Allow although > max 3375
// Fixed length
EXPECT_EQ(HRIFromGS1("39401234"), "(3940)1234");
// Incorrect lengths
EXPECT_EQ(HRIFromGS1("394012345"), "");
EXPECT_EQ(HRIFromGS1("3940123"), "");
// Fixed length
EXPECT_EQ(HRIFromGS1("39431234"), "(3943)1234");
// Incorrect lengths
EXPECT_EQ(HRIFromGS1("394312345"), "");
EXPECT_EQ(HRIFromGS1("3943123"), "");
// EXPECT_EQ(ParseFieldsInGeneralPurpose("39441234"), // Allow although > max 3943
// Fixed length
EXPECT_EQ(HRIFromGS1("3950123456"), "(3950)123456");
// Incorrect lengths
EXPECT_EQ(HRIFromGS1("39501234567"), "");
EXPECT_EQ(HRIFromGS1("395012345"), "");
// Fixed length
EXPECT_EQ(HRIFromGS1("3955123456"), "(3955)123456");
// Incorrect lengths
EXPECT_EQ(HRIFromGS1("39551234567"), "");
EXPECT_EQ(HRIFromGS1("395512345"), "");
// EXPECT_EQ(ParseFieldsInGeneralPurpose("3956123456"), // Allow although > max 3955
// Max length
EXPECT_EQ(HRIFromGS1("7230123456789012345678901234567890"), "(7230)123456789012345678901234567890");
EXPECT_EQ(HRIFromGS1("723012345678901234567890123456789"), "(7230)12345678901234567890123456789");
// Too long
EXPECT_EQ(HRIFromGS1("72301234567890123456789012345678901"), "");
// Max length
EXPECT_EQ(HRIFromGS1("7239123456789012345678901234567890"), "(7239)123456789012345678901234567890");
EXPECT_EQ(HRIFromGS1("723912345678901234567890123456789"), "(7239)12345678901234567890123456789");
// Too long
EXPECT_EQ(HRIFromGS1("72391234567890123456789012345678901"), "");
// 4-digit AIs
// Max length
EXPECT_EQ(HRIFromGS1("430012345678901234567890123456789012345"), "(4300)12345678901234567890123456789012345");
EXPECT_EQ(HRIFromGS1("43001234567890123456789012345678901234"), "(4300)1234567890123456789012345678901234");
// Too long
EXPECT_EQ(HRIFromGS1("4300123456789012345678901234567890123456"), "");
// Fixed length
EXPECT_EQ(HRIFromGS1("430712"), "(4307)12");
// Incorrect lengths
EXPECT_EQ(HRIFromGS1("4307123"), "");
EXPECT_EQ(HRIFromGS1("43071"), "");
// Max length
EXPECT_EQ(HRIFromGS1("4308123456789012345678901234567890"), "(4308)123456789012345678901234567890");
EXPECT_EQ(HRIFromGS1("430812345678901234567890123456789"), "(4308)12345678901234567890123456789");
// Too long
EXPECT_EQ(HRIFromGS1("43081234567890123456789012345678901"), "");
// Fixed length
EXPECT_EQ(HRIFromGS1("431712"), "(4317)12");
// Incorrect lengths
EXPECT_EQ(HRIFromGS1("4317123"), "");
EXPECT_EQ(HRIFromGS1("43171"), "");
// Max length
EXPECT_EQ(HRIFromGS1("431812345678901234567890"), "(4318)12345678901234567890");
EXPECT_EQ(HRIFromGS1("43181234567890123456789"), "(4318)1234567890123456789");
// Too long
EXPECT_EQ(HRIFromGS1("4318123456789012345678901"), "");
// Fixed length
EXPECT_EQ(HRIFromGS1("43211"), "(4321)1");
// Incorrect lengths
EXPECT_EQ(HRIFromGS1("432112"), "");
EXPECT_EQ(HRIFromGS1("4321"), "");
// Fixed length
EXPECT_EQ(HRIFromGS1("4326123456"), "(4326)123456");
// Incorrect lengths
EXPECT_EQ(HRIFromGS1("43261234567"), "");
EXPECT_EQ(HRIFromGS1("432612345"), "");
// Max length
EXPECT_EQ(HRIFromGS1("70041234"), "(7004)1234");
EXPECT_EQ(HRIFromGS1("7004123"), "(7004)123");
// Too long
EXPECT_EQ(HRIFromGS1("700412345"), "");
// Fixed length
EXPECT_EQ(HRIFromGS1("7006123456"), "(7006)123456");
// Incorrect lengths
EXPECT_EQ(HRIFromGS1("70061234567"), "");
EXPECT_EQ(HRIFromGS1("700612345"), "");
// Max length
EXPECT_EQ(HRIFromGS1("701012"), "(7010)12");
EXPECT_EQ(HRIFromGS1("70101"), "(7010)1");
// Too long
EXPECT_EQ(HRIFromGS1("7010123"), "");
// Max length
EXPECT_EQ(HRIFromGS1("702012345678901234567890"), "(7020)12345678901234567890");
EXPECT_EQ(HRIFromGS1("70201234567890123456789"), "(7020)1234567890123456789");
// Too long
EXPECT_EQ(HRIFromGS1("7020123456789012345678901"), "");
// Max length
EXPECT_EQ(HRIFromGS1("7023123456789012345678901234567890"), "(7023)123456789012345678901234567890");
EXPECT_EQ(HRIFromGS1("702312345678901234567890123456789"), "(7023)12345678901234567890123456789");
// Too long
EXPECT_EQ(HRIFromGS1("70231234567890123456789012345678901"), "");
// Max length
EXPECT_EQ(HRIFromGS1("70401234"), "(7040)1234");
EXPECT_EQ(HRIFromGS1("704012345"), "");
// Too long
EXPECT_EQ(HRIFromGS1("7040123"), "");
// Max length
EXPECT_EQ(HRIFromGS1("724012345678901234567890"), "(7240)12345678901234567890");
EXPECT_EQ(HRIFromGS1("72401234567890123456789"), "(7240)1234567890123456789");
// Too long
EXPECT_EQ(HRIFromGS1("7240123456789012345678901"), "");
// Max length
EXPECT_EQ(HRIFromGS1("80071234567890123456789012345678901234"), "(8007)1234567890123456789012345678901234");
EXPECT_EQ(HRIFromGS1("8007123456789012345678901234567890123"), "(8007)123456789012345678901234567890123");
// Too long
EXPECT_EQ(HRIFromGS1("800712345678901234567890123456789012345"), "");
// Max length
EXPECT_EQ(HRIFromGS1("800912345678901234567890123456789012345678901234567890"),
"(8009)12345678901234567890123456789012345678901234567890");
EXPECT_EQ(HRIFromGS1("80091234567890123456789012345678901234567890123456789"),
"(8009)1234567890123456789012345678901234567890123456789");
// Too long
EXPECT_EQ(HRIFromGS1("8009123456789012345678901234567890123456789012345678901"), "");
// Max length
EXPECT_EQ(HRIFromGS1("80131234567890123456789012345"), "(8013)1234567890123456789012345");
EXPECT_EQ(HRIFromGS1("8013123456789012345678901234"), "(8013)123456789012345678901234");
// Too long
EXPECT_EQ(HRIFromGS1("801312345678901234567890123456"), "");
// Fixed length
EXPECT_EQ(HRIFromGS1("8017123456789012345678"), "(8017)123456789012345678");
// Incorrect lengths
EXPECT_EQ(HRIFromGS1("80171234567890123456789"), "");
EXPECT_EQ(HRIFromGS1("801712345678901234567"), "");
// Max length
EXPECT_EQ(HRIFromGS1("80191234567890"), "(8019)1234567890");
EXPECT_EQ(HRIFromGS1("8019123456789"), "(8019)123456789");
// Too long
EXPECT_EQ(HRIFromGS1("801912345678901"), "");
// Fixed length
EXPECT_EQ(HRIFromGS1("8026123456789012345678"), "(8026)123456789012345678");
// Incorrect lengths
EXPECT_EQ(HRIFromGS1("80261234567890123456789"), "");
EXPECT_EQ(HRIFromGS1("802612345678901234567"), "");
// Non-existing
EXPECT_EQ(HRIFromGS1("8100123456"), "");
EXPECT_EQ(HRIFromGS1("81011234567890"), "");
EXPECT_EQ(HRIFromGS1("810212"), "");
// Max length
EXPECT_EQ(HRIFromGS1(your_sha256_hash1234567890"),
"(8110)your_sha256_hash567890");
EXPECT_EQ(HRIFromGS1(your_sha256_hash123456789"),
"(8110)your_sha256_hash56789");
// Too long
EXPECT_EQ(HRIFromGS1(your_sha256_hash12345678901"), "");
// Fixed length
EXPECT_EQ(HRIFromGS1("81111234"), "(8111)1234");
// Incorrect lengths
EXPECT_EQ(HRIFromGS1("811112345"), "");
EXPECT_EQ(HRIFromGS1("8111123"), "");
// Max length
EXPECT_EQ(HRIFromGS1(your_sha256_hash1234567890"),
"(8112)your_sha256_hash567890");
EXPECT_EQ(HRIFromGS1(your_sha256_hash123456789"),
"(8112)your_sha256_hash56789");
// Too long
EXPECT_EQ(HRIFromGS1(your_sha256_hash12345678901"), "");
// Max length
EXPECT_EQ(HRIFromGS1(your_sha256_hash1234567890"),
"(8200)your_sha256_hash567890");
EXPECT_EQ(HRIFromGS1(your_sha256_hash123456789"),
"(8200)your_sha256_hash56789");
// Too long
EXPECT_EQ(HRIFromGS1(your_sha256_hash12345678901"), "");
}
TEST(HRIFromGS1, MultiFixed)
{
EXPECT_EQ(HRIFromGS1("81111234430712"), "(8111)1234(4307)12");
}
TEST(HRIFromGS1, MultiVariable)
{
EXPECT_EQ(HRIFromGS1("70041234\x1d""81111234"), "(7004)1234(8111)1234");
}
```
|
/content/code_sandbox/test/unit/GS1Test.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 4,176
|
```c++
/*
*/
#include "qrcode/QRFormatInformation.h"
#include "gtest/gtest.h"
using namespace ZXing;
using namespace ZXing::QRCode;
static const int MASKED_TEST_FORMAT_INFO = 0x2BED;
static const int MASKED_TEST_FORMAT_INFO2 = ((0x2BED << 1) & 0b1111111000000000) | 0b100000000 | (0x2BED & 0b11111111); // insert the 'Dark Module'
static const int UNMASKED_TEST_FORMAT_INFO = MASKED_TEST_FORMAT_INFO ^ 0x5412;
static const int MICRO_MASKED_TEST_FORMAT_INFO = 0x3BBA;
static const int RMQR_MASKED_TEST_FORMAT_INFO = 0x20137;
static const int RMQR_MASKED_TEST_FORMAT_INFO_SUB = 0x1F1FE;
static void DoFormatInformationTest(const int formatInfo, const uint8_t expectedMask, const ErrorCorrectionLevel& expectedECL)
{
FormatInformation parsedFormat = FormatInformation::DecodeMQR(formatInfo);
EXPECT_TRUE(parsedFormat.isValid());
EXPECT_EQ(expectedMask, parsedFormat.dataMask);
EXPECT_EQ(expectedECL, parsedFormat.ecLevel);
}
// Helper for rMQR to unset `numBits` number of bits
static uint32_t RMQRUnsetBits(uint32_t formatInfoBits, int numBits)
{
for (int i = 0; i < 18 && numBits; i++) {
if (formatInfoBits & (1 << i)) {
formatInfoBits ^= 1 << i;
numBits--;
}
}
return formatInfoBits;
}
TEST(QRFormatInformationTest, Decode)
{
// Normal case
FormatInformation expected = FormatInformation::DecodeQR(MASKED_TEST_FORMAT_INFO, MASKED_TEST_FORMAT_INFO2);
EXPECT_TRUE(expected.isValid());
EXPECT_EQ(0x07, expected.dataMask);
EXPECT_EQ(ErrorCorrectionLevel::Quality, expected.ecLevel);
// where the code forgot the mask!
EXPECT_EQ(expected, FormatInformation::DecodeQR(UNMASKED_TEST_FORMAT_INFO, MASKED_TEST_FORMAT_INFO2));
}
TEST(QRFormatInformationTest, DecodeWithBitDifference)
{
FormatInformation expected = FormatInformation::DecodeQR(MASKED_TEST_FORMAT_INFO, MASKED_TEST_FORMAT_INFO2);
// 1,2,3,4 bits difference
EXPECT_EQ(expected, FormatInformation::DecodeQR(MASKED_TEST_FORMAT_INFO ^ 0x01, MASKED_TEST_FORMAT_INFO2 ^ 0x01));
EXPECT_EQ(expected, FormatInformation::DecodeQR(MASKED_TEST_FORMAT_INFO ^ 0x03, MASKED_TEST_FORMAT_INFO2 ^ 0x03));
EXPECT_EQ(expected, FormatInformation::DecodeQR(MASKED_TEST_FORMAT_INFO ^ 0x07, MASKED_TEST_FORMAT_INFO2 ^ 0x07));
auto unexpected = FormatInformation::DecodeQR(MASKED_TEST_FORMAT_INFO ^ 0x0F, MASKED_TEST_FORMAT_INFO2 ^ 0x0F);
EXPECT_FALSE(expected == unexpected);
EXPECT_FALSE(unexpected.isValid() && unexpected.type() == Type::Model2);
}
TEST(QRFormatInformationTest, DecodeWithMisread)
{
FormatInformation expected = FormatInformation::DecodeQR(MASKED_TEST_FORMAT_INFO, MASKED_TEST_FORMAT_INFO2);
EXPECT_EQ(expected, FormatInformation::DecodeQR(MASKED_TEST_FORMAT_INFO ^ 0x03, MASKED_TEST_FORMAT_INFO2 ^ 0x0F));
}
TEST(QRFormatInformationTest, DecodeMicro)
{
// Normal cases.
DoFormatInformationTest(0x4445, 0x0, ErrorCorrectionLevel::Low);
DoFormatInformationTest(0x4172, 0x1, ErrorCorrectionLevel::Low);
DoFormatInformationTest(0x5fc0, 0x2, ErrorCorrectionLevel::Low);
DoFormatInformationTest(0x5af7, 0x3, ErrorCorrectionLevel::Low);
DoFormatInformationTest(0x6793, 0x0, ErrorCorrectionLevel::Medium);
DoFormatInformationTest(0x62a4, 0x1, ErrorCorrectionLevel::Medium);
DoFormatInformationTest(0x3e8d, 0x2, ErrorCorrectionLevel::Quality);
DoFormatInformationTest(MICRO_MASKED_TEST_FORMAT_INFO, 0x3, ErrorCorrectionLevel::Quality);
// where the code forgot the mask!
// static const int MICRO_UNMASKED_TEST_FORMAT_INFO = MICRO_MASKED_TEST_FORMAT_INFO ^ 0x4445;
// DoFormatInformationTest(MICRO_UNMASKED_TEST_FORMAT_INFO, 0x3, ErrorCorrectionLevel::Quality);
}
// This doesn't work as expected because the implementation of the decode tries with
// and without the mask (0x4445). This effectively adds a tolerance of 5 bits to the Hamming
// distance calculation.
TEST(QRFormatInformationTest, DecodeMicroWithBitDifference)
{
FormatInformation expected = FormatInformation::DecodeMQR(MICRO_MASKED_TEST_FORMAT_INFO);
// 1,2,3 bits difference
EXPECT_EQ(expected, FormatInformation::DecodeMQR(MICRO_MASKED_TEST_FORMAT_INFO ^ 0x01));
EXPECT_EQ(expected, FormatInformation::DecodeMQR(MICRO_MASKED_TEST_FORMAT_INFO ^ 0x03));
EXPECT_EQ(expected, FormatInformation::DecodeMQR(MICRO_MASKED_TEST_FORMAT_INFO ^ 0x07));
// Bigger bit differences can return valid FormatInformation objects but the data mask and error
// correction levels do not match.
// EXPECT_TRUE(FormatInformation::DecodeFormatInformation(MICRO_MASKED_TEST_FORMAT_INFO ^ 0x3f).isValid());
// EXPECT_NE(expected.dataMask(), FormatInformation::DecodeFormatInformation(MICRO_MASKED_TEST_FORMAT_INFO ^ 0x3f).dataMask());
// EXPECT_NE(expected.errorCorrectionLevel(),
// FormatInformation::DecodeFormatInformation(MICRO_MASKED_TEST_FORMAT_INFO ^ 0x3f).errorCorrectionLevel());
}
TEST(QRFormatInformationTest, DecodeRMQR)
{
// Normal case
FormatInformation expected = FormatInformation::DecodeRMQR(RMQR_MASKED_TEST_FORMAT_INFO, RMQR_MASKED_TEST_FORMAT_INFO_SUB);
EXPECT_TRUE(expected.isValid());
EXPECT_EQ(4, expected.dataMask);
EXPECT_EQ(ErrorCorrectionLevel::High, expected.ecLevel);
EXPECT_EQ(FORMAT_INFO_MASK_RMQR, expected.mask);
// Not catered for: where the code forgot the mask!
}
TEST(QRFormatInformationTest, DecodeRMQRWithBitDifference)
{
FormatInformation expected = FormatInformation::DecodeRMQR(RMQR_MASKED_TEST_FORMAT_INFO, RMQR_MASKED_TEST_FORMAT_INFO_SUB);
EXPECT_EQ(expected.ecLevel, ErrorCorrectionLevel::High);
// 1,2,3,4,5 bits difference
EXPECT_EQ(expected, FormatInformation::DecodeRMQR(RMQRUnsetBits(RMQR_MASKED_TEST_FORMAT_INFO, 1), RMQRUnsetBits(RMQR_MASKED_TEST_FORMAT_INFO_SUB, 1)));
EXPECT_EQ(expected, FormatInformation::DecodeRMQR(RMQRUnsetBits(RMQR_MASKED_TEST_FORMAT_INFO, 2), RMQRUnsetBits(RMQR_MASKED_TEST_FORMAT_INFO_SUB, 2)));
EXPECT_EQ(expected, FormatInformation::DecodeRMQR(RMQRUnsetBits(RMQR_MASKED_TEST_FORMAT_INFO, 3), RMQRUnsetBits(RMQR_MASKED_TEST_FORMAT_INFO_SUB, 3)));
EXPECT_EQ(expected, FormatInformation::DecodeRMQR(RMQRUnsetBits(RMQR_MASKED_TEST_FORMAT_INFO, 4), RMQRUnsetBits(RMQR_MASKED_TEST_FORMAT_INFO_SUB, 4)));
auto unexpected = FormatInformation::DecodeRMQR(RMQRUnsetBits(RMQR_MASKED_TEST_FORMAT_INFO, 5), RMQRUnsetBits(RMQR_MASKED_TEST_FORMAT_INFO_SUB, 5));
EXPECT_FALSE(expected == unexpected);
EXPECT_FALSE(unexpected.isValid());
EXPECT_TRUE(unexpected.type() == Type::rMQR); // Note `mask` (used to determine type) set regardless
}
TEST(QRFormatInformationTest, DecodeRMQRWithMisread)
{
FormatInformation expected = FormatInformation::DecodeRMQR(RMQR_MASKED_TEST_FORMAT_INFO, RMQR_MASKED_TEST_FORMAT_INFO_SUB);
{
auto actual = FormatInformation::DecodeRMQR(RMQRUnsetBits(RMQR_MASKED_TEST_FORMAT_INFO, 2), RMQRUnsetBits(RMQR_MASKED_TEST_FORMAT_INFO_SUB, 4));
EXPECT_EQ(expected, actual);
EXPECT_EQ(actual.mask, FORMAT_INFO_MASK_RMQR);
}
{
auto actual = FormatInformation::DecodeRMQR(RMQRUnsetBits(RMQR_MASKED_TEST_FORMAT_INFO, 5), RMQRUnsetBits(RMQR_MASKED_TEST_FORMAT_INFO_SUB, 4));
EXPECT_EQ(expected, actual);
EXPECT_EQ(actual.mask, FORMAT_INFO_MASK_RMQR_SUB);
}
}
```
|
/content/code_sandbox/test/unit/qrcode/QRFormatInformationTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 1,894
|
```c++
/*
*/
#include "BitMatrixIO.h"
#include "qrcode/QRWriter.h"
#include "qrcode/QRErrorCorrectionLevel.h"
#include "gtest/gtest.h"
#include <stdexcept>
using namespace ZXing;
using namespace ZXing::QRCode;
namespace {
void DoTest(const std::wstring& contents, ErrorCorrectionLevel ecLevel, int resolution, const char* expected) {
Writer writer;
writer.setErrorCorrectionLevel(ecLevel);
auto matrix = writer.encode(contents, resolution, resolution);
auto actual = ToString(matrix, 'X', ' ', true);
EXPECT_EQ(matrix.width(), resolution);
EXPECT_EQ(matrix.height(), resolution);
EXPECT_EQ(actual, expected);
}
}
TEST(QRWriterTest, OverSize)
{
// The QR should be multiplied up to fit, with extra padding if necessary
int bigEnough = 256;
Writer writer;
BitMatrix matrix = writer.encode(L"path_to_url", bigEnough, bigEnough);
EXPECT_EQ(matrix.width(), bigEnough);
EXPECT_EQ(matrix.height(), bigEnough);
// The QR will not fit in this size, so the matrix should come back bigger
int tooSmall = 20;
matrix = writer.encode(L"path_to_url", tooSmall, tooSmall);
EXPECT_GT(matrix.width(), tooSmall);
EXPECT_GT(matrix.height(), tooSmall);
// We should also be able to handle non-square requests by padding them
int strangeWidth = 500;
int strangeHeight = 100;
matrix = writer.encode(L"path_to_url", strangeWidth, strangeHeight);
EXPECT_EQ(matrix.width(), strangeWidth);
EXPECT_EQ(matrix.height(), strangeHeight);
int overflowSize = 0x1000000;
EXPECT_THROW(writer.encode(L"path_to_url", overflowSize, overflowSize), std::invalid_argument);
}
TEST(QRWriterTest, RegressionTest)
{
DoTest(L"path_to_url", ErrorCorrectionLevel::Medium, 99,
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X \n"
" X X X X X X X X X X X X \n"
" X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
" \n"
);
}
```
|
/content/code_sandbox/test/unit/qrcode/QRWriterTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 4,537
|
```c++
/*
*/
#include "qrcode/QRErrorCorrectionLevel.h"
#include "gtest/gtest.h"
using namespace ZXing;
using namespace ZXing::QRCode;
TEST(QRErrorCorrectionLevelTest, ForBits)
{
EXPECT_EQ(ErrorCorrectionLevel::Medium, ECLevelFromBits(0));
EXPECT_EQ(ErrorCorrectionLevel::Low, ECLevelFromBits(1));
EXPECT_EQ(ErrorCorrectionLevel::High, ECLevelFromBits(2));
EXPECT_EQ(ErrorCorrectionLevel::Quality, ECLevelFromBits(3));
}
TEST(QRErrorCorrectionLevelTest, ForMicroBits)
{
EXPECT_EQ(ErrorCorrectionLevel::Low, ECLevelFromBits(0, true));
EXPECT_EQ(ErrorCorrectionLevel::Low, ECLevelFromBits(1, true));
EXPECT_EQ(ErrorCorrectionLevel::Medium, ECLevelFromBits(2, true));
EXPECT_EQ(ErrorCorrectionLevel::Low, ECLevelFromBits(3, true));
EXPECT_EQ(ErrorCorrectionLevel::Medium, ECLevelFromBits(4, true));
EXPECT_EQ(ErrorCorrectionLevel::Low, ECLevelFromBits(5, true));
EXPECT_EQ(ErrorCorrectionLevel::Medium, ECLevelFromBits(6, true));
EXPECT_EQ(ErrorCorrectionLevel::Quality, ECLevelFromBits(7, true));
EXPECT_EQ(ErrorCorrectionLevel::Quality, ECLevelFromBits(-1, true));
EXPECT_EQ(ErrorCorrectionLevel::Low, ECLevelFromBits(8, true));
}
TEST(QRErrorCorrectionLevelTest, ToString)
{
using namespace std::literals;
EXPECT_EQ("L"s, ToString(ErrorCorrectionLevel::Low));
EXPECT_EQ("M"s, ToString(ErrorCorrectionLevel::Medium));
EXPECT_EQ("Q"s, ToString(ErrorCorrectionLevel::Quality));
EXPECT_EQ("H"s, ToString(ErrorCorrectionLevel::High));
}
```
|
/content/code_sandbox/test/unit/qrcode/QRErrorCorrectionLevelTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 361
|
```c++
/*
*/
#include "BitMatrix.h"
#include "BitMatrixIO.h"
#include "ByteArray.h"
#include "qrcode/QRBitMatrixParser.h"
#include "qrcode/QRFormatInformation.h"
#include "qrcode/QRVersion.h"
#include "gtest/gtest.h"
using namespace ZXing;
using namespace ZXing::QRCode;
TEST(QRBitMatrixParserTest, MQRCodeM3L)
{
const auto bitMatrix = ParseBitMatrix("XXXXXXX X X X X\n"
"X X X X \n"
"X XXX X XXXXXXX\n"
"X XXX X X X XX\n"
"X XXX X X XX\n"
"X X X X X X\n"
"XXXXXXX X XX \n"
" X X X\n"
"XXXXXX X X X\n"
" X XX XXX\n"
"XXX XX XXXX XXX\n"
" X X XXX X \n"
"X XXXXX XXX X X\n"
" X X X XXX \n"
"XXX XX X X XXXX\n",
88, false);
const auto format = ReadFormatInformation(bitMatrix);
const auto version = ReadVersion(bitMatrix, format.type());
EXPECT_EQ(3, version->versionNumber());
const auto codewords = ReadCodewords(bitMatrix, *version, format);
EXPECT_EQ(17, codewords.size());
EXPECT_EQ(0x0, codewords[10]);
EXPECT_EQ(0xd1, codewords[11]);
}
TEST(QRBitMatrixParserTest, MQRCodeM3M)
{
const auto bitMatrix = ParseBitMatrix("XXXXXXX X X X X\n"
"X X XX\n"
"X XXX X X XX XX\n"
"X XXX X X X \n"
"X XXX X XX XXXX\n"
"X X XX \n"
"XXXXXXX X XXXX\n"
" X XXX \n"
"X XX XX X X\n"
" X X XX \n"
"XX XX XXXXXXX\n"
" X X X\n"
"XX X X X \n"
" X X X \n"
"X X XXXX XXX\n",
88, false);
const auto format = ReadFormatInformation(bitMatrix);
const auto version = ReadVersion(bitMatrix, format.type());
EXPECT_EQ(3, version->versionNumber());
const auto codewords = ReadCodewords(bitMatrix, *version, format);
EXPECT_EQ(17, codewords.size());
EXPECT_EQ(0x0, codewords[8]);
EXPECT_EQ(0x89, codewords[9]);
}
```
|
/content/code_sandbox/test/unit/qrcode/QRBitMatrixParserTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 607
|
```c++
/*
*/
#include "qrcode/QRDataMask.h"
#include "BitMatrix.h"
#include "gtest/gtest.h"
#include <functional>
using namespace ZXing;
using namespace ZXing::QRCode;
namespace {
void TestMaskAcrossDimensionsImpl(int maskIndex, bool isMicro, const int versionMax, const int dimensionStart, const int dimensionStep, std::function<bool(int, int)> condition)
{
for (int version = 1; version <= versionMax; version++) {
int dimension = dimensionStart + dimensionStep * version;
BitMatrix bits(dimension);
for (int i = 0; i < dimension; i++)
for (int j = 0; j < dimension; j++)
EXPECT_EQ(GetMaskedBit(bits, j, i, maskIndex, isMicro), condition(i, j)) << "(" << i << ',' << j << ')';
}
}
void TestMaskAcrossDimensions(int maskIndex, std::function<bool(int, int)> condition)
{
TestMaskAcrossDimensionsImpl(maskIndex, false, 40, 17, 4, condition);
}
void TestMicroMaskAcrossDimensions(int maskIndex, std::function<bool(int, int)> condition)
{
TestMaskAcrossDimensionsImpl(maskIndex, true, 4, 9, 2, condition);
}
}
TEST(QRDataMaskTest, Mask0)
{
TestMaskAcrossDimensions(0, [](int i, int j) { return (i + j) % 2 == 0; });
}
TEST(QRDataMaskTest, Mask1)
{
TestMaskAcrossDimensions(1, [](int i, int) { return i % 2 == 0; });
}
TEST(QRDataMaskTest, Mask2)
{
TestMaskAcrossDimensions(2, [](int, int j) { return j % 3 == 0; });
}
TEST(QRDataMaskTest, Mask3)
{
TestMaskAcrossDimensions(3, [](int i, int j) { return (i + j) % 3 == 0; });
}
TEST(QRDataMaskTest, Mask4)
{
TestMaskAcrossDimensions(4, [](int i, int j) { return (i / 2 + j / 3) % 2 == 0; });
}
TEST(QRDataMaskTest, Mask5)
{
TestMaskAcrossDimensions(5, [](int i, int j) { return (i * j) % 2 + (i * j) % 3 == 0; });
}
TEST(QRDataMaskTest, Mask6)
{
TestMaskAcrossDimensions(6, [](int i, int j) { return ((i * j) % 2 + (i * j) % 3) % 2 == 0; });
}
TEST(QRDataMaskTest, Mask7)
{
TestMaskAcrossDimensions(7, [](int i, int j) { return ((i + j) % 2 + (i * j) % 3) % 2 == 0; });
}
TEST(QRDataMaskTest, MicroMask0)
{
TestMicroMaskAcrossDimensions(0, [](int i, int) { return i % 2 == 0; });
}
TEST(QRDataMaskTest, MicroMask1)
{
TestMicroMaskAcrossDimensions(1, [](int i, int j) { return (i / 2 + j / 3) % 2 == 0; });
}
TEST(QRDataMaskTest, MicroMask2)
{
TestMicroMaskAcrossDimensions(2, [](int i, int j) { return ((i * j) % 2 + (i * j) % 3) % 2 == 0; });
}
TEST(QRDataMaskTest, MicroMask3)
{
TestMicroMaskAcrossDimensions(3, [](int i, int j) { return ((i + j) % 2 + (i * j) % 3) % 2 == 0; });
}
```
|
/content/code_sandbox/test/unit/qrcode/QRDataMaskTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 841
|
```c++
/*
*/
#include "BitArray.h"
#include "ByteArray.h"
#include "DecoderResult.h"
#include "qrcode/QRErrorCorrectionLevel.h"
#include "qrcode/QRVersion.h"
#include "gtest/gtest.h"
namespace ZXing {
namespace QRCode {
DecoderResult DecodeBitStream(ByteArray&& bytes, const Version& version, ErrorCorrectionLevel ecLevel);
}
}
using namespace ZXing;
using namespace ZXing::QRCode;
TEST(QRDecodedBitStreamParserTest, SimpleByteMode)
{
BitArray ba;
ba.appendBits(0x04, 4); // Byte mode
ba.appendBits(0x03, 8); // 3 bytes
ba.appendBits(0xF1, 8);
ba.appendBits(0xF2, 8);
ba.appendBits(0xF3, 8);
auto result = DecodeBitStream(ba.toBytes(), *Version::Model2(1), ErrorCorrectionLevel::Medium).text();
EXPECT_EQ(L"\xF1\xF2\xF3", result);
}
TEST(QRDecodedBitStreamParserTest, SimpleSJIS)
{
BitArray ba;
ba.appendBits(0x04, 4); // Byte mode
ba.appendBits(0x04, 8); // 4 bytes
ba.appendBits(0xA1, 8);
ba.appendBits(0xA2, 8);
ba.appendBits(0xA3, 8);
ba.appendBits(0xD0, 8);
auto result = DecodeBitStream(ba.toBytes(), *Version::Model2(1), ErrorCorrectionLevel::Medium).text();
EXPECT_EQ(L"\uff61\uff62\uff63\uff90", result);
}
TEST(QRDecodedBitStreamParserTest, ECI)
{
BitArray ba;
ba.appendBits(0x07, 4); // ECI mode
ba.appendBits(0x02, 8); // ECI 2 = CP437 encoding
ba.appendBits(0x04, 4); // Byte mode
ba.appendBits(0x03, 8); // 3 bytes
ba.appendBits(0xA1, 8);
ba.appendBits(0xA2, 8);
ba.appendBits(0xA3, 8);
auto result = DecodeBitStream(ba.toBytes(), *Version::Model2(1), ErrorCorrectionLevel::Medium).text();
EXPECT_EQ(L"\xED\xF3\xFA", result);
}
TEST(QRDecodedBitStreamParserTest, Hanzi)
{
BitArray ba;
ba.appendBits(0x0D, 4); // Hanzi mode
ba.appendBits(0x01, 4); // Subset 1 = GB2312 encoding
ba.appendBits(0x01, 8); // 1 characters
ba.appendBits(0x03C1, 13);
auto result = DecodeBitStream(ba.toBytes(), *Version::Model2(1), ErrorCorrectionLevel::Medium).text();
EXPECT_EQ(L"\u963f", result);
}
TEST(QRDecodedBitStreamParserTest, HanziLevel1)
{
BitArray ba;
ba.appendBits(0x0D, 4); // Hanzi mode
ba.appendBits(0x01, 4); // Subset 1 = GB2312 encoding
ba.appendBits(0x01, 8); // 1 characters
// A5A2 (U+30A2) => A5A2 - A1A1 = 401, 4*60 + 01 = 0181
ba.appendBits(0x0181, 13);
auto result = DecodeBitStream(ba.toBytes(), *Version::Model2(1), ErrorCorrectionLevel::Medium).text();
EXPECT_EQ(L"\u30a2", result);
}
TEST(QRDecodedBitStreamParserTest, SymbologyIdentifier)
{
const Version& version = *Version::Model2(1);
const ErrorCorrectionLevel ecLevel = ErrorCorrectionLevel::Medium;
DecoderResult result;
// Plain "ANUM(1) A"
result = DecodeBitStream({0x20, 0x09, 0x40}, version, ecLevel);
EXPECT_EQ(result.symbologyIdentifier(), "]Q1");
EXPECT_EQ(result.text(), L"A");
// GS1 "FNC1(1st) NUM(4) 2001"
result = DecodeBitStream({0x51, 0x01, 0x0C, 0x81, 0x00}, version, ecLevel);
EXPECT_EQ(result.symbologyIdentifier(), "]Q3");
EXPECT_EQ(result.text(), L"2001"); // "(20)01"
// GS1 "NUM(4) 2001 FNC1(1st) 301" - FNC1(1st) can occur anywhere (this actually violates the specification)
result = DecodeBitStream({0x10, 0x10, 0xC8, 0x15, 0x10, 0x0D, 0x2D, 0x00}, version, ecLevel);
EXPECT_EQ(result.symbologyIdentifier(), "]Q3");
EXPECT_EQ(result.text(), L"2001301"); // "(20)01(30)1"
// AIM "FNC1(2nd) 99 (0x63) ANUM(1) A"
result = DecodeBitStream({0x96, 0x32, 0x00, 0x94, 0x00}, version, ecLevel);
EXPECT_EQ(result.symbologyIdentifier(), "]Q5");
EXPECT_EQ(result.text(), L"99A");
// AIM "BYTE(1) A FNC1(2nd) 99 (0x63) BYTE(1) B" - FNC1(2nd) can occur anywhere
// Disabled this test, since this violates the specification and the code does support it anymore
// result = DecodeBitStream({0x40, 0x14, 0x19, 0x63, 0x40, 0x14, 0x20, 0x00}, version, ecLevel, "");
// EXPECT_EQ(result.symbologyIdentifier(), "]Q5");
// EXPECT_EQ(result.text(), L"99AB"); // Application Indicator prefixed to data
// AIM "FNC1(2nd) A (100 + 61 = 0xA5) ANUM(1) B"
result = DecodeBitStream({0x9A, 0x52, 0x00, 0x96, 0x00}, version, ecLevel);
EXPECT_EQ(result.symbologyIdentifier(), "]Q5");
EXPECT_EQ(result.text(), L"AB");
// AIM "FNC1(2nd) a (100 + 97 = 0xC5) ANUM(1) B"
result = DecodeBitStream({0x9C, 0x52, 0x00, 0x96, 0x00}, version, ecLevel);
EXPECT_EQ(result.symbologyIdentifier(), "]Q5");
EXPECT_EQ(result.text(), L"aB");
// Bad AIM Application Indicator "FNC1(2nd) @ (0xA4) ANUM(1) B"
result = DecodeBitStream({0x9A, 0x42, 0x00, 0x96, 0x00}, version, ecLevel);
EXPECT_FALSE(result.isValid());
}
TEST(QRDecodedBitStreamParserTest, GS1PercentGS)
{
const Version& version = *Version::Model2(1);
const ErrorCorrectionLevel ecLevel = ErrorCorrectionLevel::Quality;
DecoderResult result;
// GS1 "FNC1(1st) A(11) 9112%%%2012 (9112%<FNC1>2012)"
result = DecodeBitStream({0x52, 0x05, 0x99, 0x60, 0x5F, 0xB5, 0x35, 0x80, 0x01, 0x08, 0x00, 0xEC, 0x11}, version, ecLevel);
EXPECT_EQ(result.content().text(TextMode::Plain), "9112%\x1D" "2012");
EXPECT_EQ(result.content().text(TextMode::HRI), "(91)12%(20)12");
}
```
|
/content/code_sandbox/test/unit/qrcode/QRDecodedBitStreamParserTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 1,815
|
```c++
/*
*/
#include "qrcode/QRCodecMode.h"
#include "qrcode/QRVersion.h"
#include "Error.h"
#include "gtest/gtest.h"
using namespace ZXing;
using namespace ZXing::QRCode;
TEST(QRModeTest, ForBits)
{
ASSERT_EQ(CodecMode::TERMINATOR, CodecModeForBits(0x00, Type::Model2));
ASSERT_EQ(CodecMode::NUMERIC, CodecModeForBits(0x01, Type::Model2));
ASSERT_EQ(CodecMode::ALPHANUMERIC, CodecModeForBits(0x02, Type::Model2));
ASSERT_EQ(CodecMode::BYTE, CodecModeForBits(0x04, Type::Model2));
ASSERT_EQ(CodecMode::KANJI, CodecModeForBits(0x08, Type::Model2));
ASSERT_THROW(CodecModeForBits(0x10, Type::Model2), Error);
}
TEST(QRModeTest, CharacterCount)
{
// Spot check a few values
ASSERT_EQ(10, CharacterCountBits(CodecMode::NUMERIC, *Version::Model2(5)));
ASSERT_EQ(12, CharacterCountBits(CodecMode::NUMERIC, *Version::Model2(26)));
ASSERT_EQ(14, CharacterCountBits(CodecMode::NUMERIC, *Version::Model2(40)));
ASSERT_EQ(9, CharacterCountBits(CodecMode::ALPHANUMERIC, *Version::Model2(6)));
ASSERT_EQ(8, CharacterCountBits(CodecMode::BYTE, *Version::Model2(7)));
ASSERT_EQ(8, CharacterCountBits(CodecMode::KANJI, *Version::Model2(8)));
}
TEST(QRModeTest, MicroForBits)
{
// M1
ASSERT_EQ(CodecMode::NUMERIC, CodecModeForBits(0x00, Type::Micro));
// M2
ASSERT_EQ(CodecMode::NUMERIC, CodecModeForBits(0x00, Type::Micro));
ASSERT_EQ(CodecMode::ALPHANUMERIC, CodecModeForBits(0x01, Type::Micro));
// M3
ASSERT_EQ(CodecMode::NUMERIC, CodecModeForBits(0x00, Type::Micro));
ASSERT_EQ(CodecMode::ALPHANUMERIC, CodecModeForBits(0x01, Type::Micro));
ASSERT_EQ(CodecMode::BYTE, CodecModeForBits(0x02, Type::Micro));
ASSERT_EQ(CodecMode::KANJI, CodecModeForBits(0x03, Type::Micro));
// M4
ASSERT_EQ(CodecMode::NUMERIC, CodecModeForBits(0x00, Type::Micro));
ASSERT_EQ(CodecMode::ALPHANUMERIC, CodecModeForBits(0x01, Type::Micro));
ASSERT_EQ(CodecMode::BYTE, CodecModeForBits(0x02, Type::Micro));
ASSERT_EQ(CodecMode::KANJI, CodecModeForBits(0x03, Type::Micro));
ASSERT_THROW(CodecModeForBits(0x04, Type::Micro), Error);
}
TEST(QRModeTest, MicroCharacterCount)
{
// Spot check a few values
ASSERT_EQ(3, CharacterCountBits(CodecMode::NUMERIC, *Version::Micro(1)));
ASSERT_EQ(4, CharacterCountBits(CodecMode::NUMERIC, *Version::Micro(2)));
ASSERT_EQ(6, CharacterCountBits(CodecMode::NUMERIC, *Version::Micro(4)));
ASSERT_EQ(3, CharacterCountBits(CodecMode::ALPHANUMERIC, *Version::Micro(2)));
ASSERT_EQ(4, CharacterCountBits(CodecMode::BYTE, *Version::Micro(3)));
ASSERT_EQ(4, CharacterCountBits(CodecMode::KANJI, *Version::Micro(4)));
}
TEST(QRModeTest, RMQRForBits)
{
ASSERT_EQ(CodecMode::TERMINATOR, CodecModeForBits(0x00, Type::rMQR));
ASSERT_EQ(CodecMode::NUMERIC, CodecModeForBits(0x01, Type::rMQR));
ASSERT_EQ(CodecMode::ALPHANUMERIC, CodecModeForBits(0x02, Type::rMQR));
ASSERT_EQ(CodecMode::BYTE, CodecModeForBits(0x03, Type::rMQR));
ASSERT_EQ(CodecMode::KANJI, CodecModeForBits(0x04, Type::rMQR));
ASSERT_EQ(CodecMode::FNC1_FIRST_POSITION, CodecModeForBits(0x05, Type::rMQR));
ASSERT_EQ(CodecMode::FNC1_SECOND_POSITION, CodecModeForBits(0x06, Type::rMQR));
ASSERT_EQ(CodecMode::ECI, CodecModeForBits(0x07, Type::rMQR));
ASSERT_THROW(CodecModeForBits(0x08, Type::rMQR), Error);
}
TEST(QRModeTest, RMQRCharacterCount)
{
// Spot check a few values
ASSERT_EQ(7, CharacterCountBits(CodecMode::NUMERIC, *Version::rMQR(5)));
ASSERT_EQ(8, CharacterCountBits(CodecMode::NUMERIC, *Version::rMQR(26)));
ASSERT_EQ(9, CharacterCountBits(CodecMode::NUMERIC, *Version::rMQR(32)));
ASSERT_EQ(5, CharacterCountBits(CodecMode::ALPHANUMERIC, *Version::rMQR(6)));
ASSERT_EQ(5, CharacterCountBits(CodecMode::BYTE, *Version::rMQR(7)));
ASSERT_EQ(5, CharacterCountBits(CodecMode::KANJI, *Version::rMQR(8)));
}
```
|
/content/code_sandbox/test/unit/qrcode/QRModeTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 1,200
|
```c++
/*
*/
#include "BitArray.h"
#include "BitArrayUtility.h"
#include "BitMatrixIO.h"
#include "CharacterSet.h"
#include "TextDecoder.h"
#include "Utf.h"
#include "qrcode/QREncoder.h"
#include "qrcode/QRCodecMode.h"
#include "qrcode/QREncodeResult.h"
#include "qrcode/QRErrorCorrectionLevel.h"
#include "gtest/gtest.h"
namespace ZXing {
namespace QRCode {
int GetAlphanumericCode(int code);
CodecMode ChooseMode(const std::wstring& content, CharacterSet encoding);
void AppendModeInfo(CodecMode mode, BitArray& bits);
void AppendLengthInfo(int numLetters, const Version& version, CodecMode mode, BitArray& bits);
void AppendNumericBytes(const std::wstring& content, BitArray& bits);
void AppendAlphanumericBytes(const std::wstring& content, BitArray& bits);
void Append8BitBytes(const std::wstring& content, CharacterSet encoding, BitArray& bits);
void AppendKanjiBytes(const std::wstring& content, BitArray& bits);
void AppendBytes(const std::wstring& content, CodecMode mode, CharacterSet encoding, BitArray& bits);
void TerminateBits(int numDataBytes, BitArray& bits);
void GetNumDataBytesAndNumECBytesForBlockID(int numTotalBytes, int numDataBytes, int numRSBlocks, int blockID, int& numDataBytesInBlock, int& numECBytesInBlock);
void GenerateECBytes(const ByteArray& dataBytes, int numEcBytesInBlock, ByteArray& ecBytes);
BitArray InterleaveWithECBytes(const BitArray& bits, int numTotalBytes, int numDataBytes, int numRSBlocks);
}
}
using namespace ZXing;
using namespace ZXing::QRCode;
using namespace ZXing::Utility;
namespace {
std::wstring ShiftJISString(const std::vector<uint8_t>& bytes)
{
std::string str;
TextDecoder::Append(str, bytes.data(), bytes.size(), CharacterSet::Shift_JIS);
return FromUtf8(str);
}
std::string RemoveSpace(std::string s)
{
s.erase(std::remove(s.begin(), s.end(), ' '), s.end());
return s;
}
}
TEST(QREncoderTest, GetAlphanumericCode)
{
// The first ten code points are numbers.
for (int i = 0; i < 10; ++i) {
EXPECT_EQ(i, GetAlphanumericCode('0' + i));
}
// The next 26 code points are capital alphabet letters.
for (int i = 10; i < 36; ++i) {
EXPECT_EQ(i, GetAlphanumericCode('A' + i - 10));
}
// Others are symbol letters
EXPECT_EQ(36, GetAlphanumericCode(' '));
EXPECT_EQ(37, GetAlphanumericCode('$'));
EXPECT_EQ(38, GetAlphanumericCode('%'));
EXPECT_EQ(39, GetAlphanumericCode('*'));
EXPECT_EQ(40, GetAlphanumericCode('+'));
EXPECT_EQ(41, GetAlphanumericCode('-'));
EXPECT_EQ(42, GetAlphanumericCode('.'));
EXPECT_EQ(43, GetAlphanumericCode('/'));
EXPECT_EQ(44, GetAlphanumericCode(':'));
// Should return -1 for other letters;
EXPECT_EQ(-1, GetAlphanumericCode('a'));
EXPECT_EQ(-1, GetAlphanumericCode('#'));
EXPECT_EQ(-1, GetAlphanumericCode('\0'));
}
TEST(QREncoderTest, ChooseMode)
{
// Numeric mode.
EXPECT_EQ(CodecMode::NUMERIC, ChooseMode(L"0", CharacterSet::Unknown));
EXPECT_EQ(CodecMode::NUMERIC, ChooseMode(L"0123456789", CharacterSet::Unknown));
// Alphanumeric mode.
EXPECT_EQ(CodecMode::ALPHANUMERIC, ChooseMode(L"A", CharacterSet::Unknown));
EXPECT_EQ(CodecMode::ALPHANUMERIC,
ChooseMode(L"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:", CharacterSet::Unknown));
// 8-bit byte mode.
EXPECT_EQ(CodecMode::BYTE, ChooseMode(L"a", CharacterSet::Unknown));
EXPECT_EQ(CodecMode::BYTE, ChooseMode(L"#", CharacterSet::Unknown));
EXPECT_EQ(CodecMode::BYTE, ChooseMode(L"", CharacterSet::Unknown));
// Kanji mode. We used to use MODE_KANJI for these, but we stopped
// doing that as we cannot distinguish Shift_JIS from other encodings
// from data bytes alone. See also comments in qrcode_encoder.h.
// AIUE in Hiragana in Shift_JIS
EXPECT_EQ(CodecMode::BYTE,
ChooseMode(ShiftJISString({0x8, 0xa, 0x8, 0xa, 0x8, 0xa, 0x8, 0xa6}), CharacterSet::Unknown));
// Nihon in Kanji in Shift_JIS.
EXPECT_EQ(CodecMode::BYTE, ChooseMode(ShiftJISString({0x9, 0xf, 0x9, 0x7b}), CharacterSet::Unknown));
// Sou-Utsu-Byou in Kanji in Shift_JIS.
EXPECT_EQ(CodecMode::BYTE, ChooseMode(ShiftJISString({0xe, 0x4, 0x9, 0x5, 0x9, 0x61}), CharacterSet::Unknown));
}
TEST(QREncoderTest, Encode)
{
auto qrCode = Encode(L"ABCDEF", ErrorCorrectionLevel::High, CharacterSet::Unknown, 0, false, -1);
EXPECT_EQ(qrCode.mode, CodecMode::ALPHANUMERIC);
EXPECT_EQ(qrCode.ecLevel, ErrorCorrectionLevel::High);
ASSERT_NE(qrCode.version, nullptr);
EXPECT_EQ(qrCode.version->versionNumber(), 1);
EXPECT_EQ(qrCode.maskPattern, 4);
EXPECT_EQ(ToString(qrCode.matrix, 'X', ' ', true),
"X X X X X X X X X X X X X X X X \n"
"X X X X X X X \n"
"X X X X X X X X X X \n"
"X X X X X X X X X X X X \n"
"X X X X X X X X X X X X \n"
"X X X X X X X \n"
"X X X X X X X X X X X X X X X X X \n"
" X X \n"
" X X X X X X X X X X \n"
" X X X X X X X X X X X X \n"
"X X X X X X X X X X \n"
"X X X X X X X X X \n"
" X X X X X X X X X X X X X \n"
" X X X X X X \n"
"X X X X X X X X X X X X X \n"
"X X X X X X X X X X \n"
"X X X X X X X X X X X \n"
"X X X X X X X X X X X \n"
"X X X X X X X X X \n"
"X X X X X X X \n"
"X X X X X X X X X X X X \n");
}
TEST(QREncoderTest, EncodeWithVersion)
{
auto qrCode = Encode(L"ABCDEF", ErrorCorrectionLevel::High, CharacterSet::Unknown, 7, false, -1);
ASSERT_NE(qrCode.version, nullptr);
EXPECT_EQ(qrCode.version->versionNumber(), 7);
}
TEST(QREncoderTest, EncodeWithVersionTooSmall)
{
EXPECT_THROW(
Encode(L"THISMESSAGEISTOOLONGFORAQRCODEVERSION3", ErrorCorrectionLevel::High, CharacterSet::Unknown, 3, false, -1)
, std::invalid_argument);
}
TEST(QREncoderTest, SimpleUTF8ECI)
{
auto qrCode = Encode(L"hello", ErrorCorrectionLevel::High, CharacterSet::UTF8, 0, false, -1);
EXPECT_EQ(qrCode.mode, CodecMode::BYTE);
EXPECT_EQ(qrCode.ecLevel, ErrorCorrectionLevel::High);
ASSERT_NE(qrCode.version, nullptr);
EXPECT_EQ(qrCode.version->versionNumber(), 1);
EXPECT_EQ(qrCode.maskPattern, 6);
EXPECT_EQ(ToString(qrCode.matrix, 'X', ' ', true),
"X X X X X X X X X X X X X X X X \n"
"X X X X X X \n"
"X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X \n"
"X X X X X X X X X X X X \n"
"X X X X X \n"
"X X X X X X X X X X X X X X X X X \n"
" X X X X \n"
" X X X X X X X \n"
" X X X X X X X X X \n"
"X X X X X X X X X X X \n"
" X X X X X X \n"
" X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X \n"
"X X X X X X X X X X \n"
"X X X X X X \n"
"X X X X X X X X X \n"
"X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X \n"
"X X X X X X \n"
"X X X X X X X X X X X \n");
}
TEST(QREncoderTest, SimpleBINARYECI)
{
auto qrCode = Encode(L"\u00E9", ErrorCorrectionLevel::High, CharacterSet::BINARY, 0, false, -1);
EXPECT_EQ(qrCode.mode, CodecMode::BYTE);
EXPECT_EQ(qrCode.ecLevel, ErrorCorrectionLevel::High);
ASSERT_NE(qrCode.version, nullptr);
EXPECT_EQ(qrCode.version->versionNumber(), 1);
EXPECT_EQ(qrCode.maskPattern, 6);
EXPECT_EQ(ToString(qrCode.matrix, 'X', ' ', true),
"X X X X X X X X X X X X X X X X X X \n"
"X X X X X \n"
"X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X \n"
"X X X X X X \n"
"X X X X X X X X X X X X X X X X X \n"
" X X X \n"
" X X X X X X X \n"
"X X X X X X X X \n"
"X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X \n"
" X X X X X X X X X X \n"
" X X X X X X X X \n"
"X X X X X X X X X X X X X X X \n"
"X X X X X X X \n"
"X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X \n"
"X X X X X X X X X X \n"
"X X X X X X X \n"
"X X X X X X X X X X X X X \n");
}
TEST(QREncoderTest, EncodeKanjiMode)
{
auto qrCode = Encode(L"\u65e5\u672c", ErrorCorrectionLevel::Medium, CharacterSet::Shift_JIS, 0, false, -1);
EXPECT_EQ(qrCode.mode, CodecMode::KANJI);
EXPECT_EQ(qrCode.ecLevel, ErrorCorrectionLevel::Medium);
ASSERT_NE(qrCode.version, nullptr);
EXPECT_EQ(qrCode.version->versionNumber(), 1);
EXPECT_EQ(qrCode.maskPattern, 0);
EXPECT_EQ(ToString(qrCode.matrix, 'X', ' ', true),
"X X X X X X X X X X X X X X X X \n"
"X X X X X X \n"
"X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X \n"
"X X X X X X X \n"
"X X X X X X X X X X X X X X X X X \n"
" X \n"
"X X X X X X X X \n"
"X X X X X X X X X X \n"
" X X X X X X X X X X X X \n"
"X X X X X X X X X X X \n"
" X X X X X X X X X X X X \n"
" X X X X X \n"
"X X X X X X X X X X X \n"
"X X X X X X X \n"
"X X X X X X X X X X X \n"
"X X X X X X X X X X \n"
"X X X X X X X X X X X X X \n"
"X X X X X X X X X \n"
"X X X X X X X X X X X X X X \n");
}
TEST(QREncoderTest, EncodeShiftjisNumeric)
{
auto qrCode = Encode(L"0123", ErrorCorrectionLevel::Medium, CharacterSet::Shift_JIS, 0, false, -1);
EXPECT_EQ(qrCode.mode, CodecMode::NUMERIC);
EXPECT_EQ(qrCode.ecLevel, ErrorCorrectionLevel::Medium);
ASSERT_NE(qrCode.version, nullptr);
EXPECT_EQ(qrCode.version->versionNumber(), 1);
EXPECT_EQ(qrCode.maskPattern, 2);
EXPECT_EQ(ToString(qrCode.matrix, 'X', ' ', true),
"X X X X X X X X X X X X X X X X X \n"
"X X X X X X \n"
"X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X \n"
"X X X X X X X \n"
"X X X X X X X X X X X X X X X X X \n"
" X X X X X \n"
"X X X X X X X X X X X X X X \n"
"X X X X X X X X \n"
" X X X X X X X X X X X X X X \n"
"X X X X X X X X X \n"
" X X X X X X X X \n"
" X X X X X X X \n"
"X X X X X X X X X X X \n"
"X X X X X X X X X X \n"
"X X X X X X X X X X \n"
"X X X X X X X X X X X \n"
"X X X X X X X X X X X X \n"
"X X X X X X X \n"
"X X X X X X X X X X X X X X \n");
}
TEST(QREncoderTest, EncodeGS1)
{
auto qrCode = Encode(L"100001%11171218", ErrorCorrectionLevel::High, CharacterSet::Unknown, 0, true, -1);
EXPECT_EQ(qrCode.mode, CodecMode::ALPHANUMERIC);
EXPECT_EQ(qrCode.ecLevel, ErrorCorrectionLevel::High);
ASSERT_NE(qrCode.version, nullptr);
EXPECT_EQ(qrCode.version->versionNumber(), 2);
EXPECT_EQ(qrCode.maskPattern, 4);
EXPECT_EQ(ToString(qrCode.matrix, 'X', ' ', true),
"X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X \n"
"X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X \n"
"X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X \n"
" X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X \n"
"X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X \n"
"X X X X X X X X X X X X X X \n"
" X X X X X X X X \n"
"X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X \n");
}
TEST(QREncoderTest, EncodeGS1ModeHeaderWithECI)
{
auto qrCode = Encode(L"hello", ErrorCorrectionLevel::High, CharacterSet::UTF8, 0, true, -1);
EXPECT_EQ(qrCode.mode, CodecMode::BYTE);
EXPECT_EQ(qrCode.ecLevel, ErrorCorrectionLevel::High);
ASSERT_NE(qrCode.version, nullptr);
EXPECT_EQ(qrCode.version->versionNumber(), 1);
EXPECT_EQ(qrCode.maskPattern, 5);
EXPECT_EQ(ToString(qrCode.matrix, 'X', ' ', true),
"X X X X X X X X X X X X X X X X X \n"
"X X X X X X \n"
"X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X \n"
"X X X X X X X X X X X X \n"
"X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X \n"
" X X X X \n"
" X X X X X X X X \n"
" X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X \n"
"X X X X X X X X X X X X \n"
"X X X X X X X X X X \n"
" X X X X X X X X \n"
"X X X X X X X X X X X X \n"
"X X X X X X X X \n"
"X X X X X X X X X X \n"
"X X X X X X X X X X X X \n"
"X X X X X X X X X X X \n"
"X X X X X X X X X \n"
"X X X X X X X X X X X X X X \n");
}
TEST(QREncoderTest, AppendModeInfo)
{
BitArray bits;
AppendModeInfo(CodecMode::NUMERIC, bits);
EXPECT_EQ(ToString(bits), "...X");
}
TEST(QREncoderTest, AppendLengthInfo)
{
BitArray bits;
AppendLengthInfo(1, // 1 letter (1/1).
*Version::Model2(1), CodecMode::NUMERIC, bits);
EXPECT_EQ(ToString(bits), RemoveSpace("........ .X")); // 10 bits.
bits = BitArray();
AppendLengthInfo(2, // 2 letters (2/1).
*Version::Model2(10), CodecMode::ALPHANUMERIC, bits);
EXPECT_EQ(ToString(bits), RemoveSpace("........ .X.")); // 11 bits.
bits = BitArray();
AppendLengthInfo(255, // 255 letter (255/1).
*Version::Model2(27), CodecMode::BYTE, bits);
EXPECT_EQ(ToString(bits), RemoveSpace("........ XXXXXXXX")); // 16 bits.
bits = BitArray();
AppendLengthInfo(512, // 512 letters (1024/2).
*Version::Model2(40), CodecMode::KANJI, bits);
EXPECT_EQ(ToString(bits), RemoveSpace("..X..... ....")); // 12 bits.
}
TEST(QREncoderTest, AppendNumericBytes)
{
// 1 = 01 = 0001 in 4 bits.
BitArray bits;
AppendNumericBytes(L"1", bits);
EXPECT_EQ(ToString(bits), RemoveSpace("...X"));
// 12 = 0xc = 0001100 in 7 bits.
bits = BitArray();
AppendNumericBytes(L"12", bits);
EXPECT_EQ(ToString(bits), RemoveSpace("...XX.."));
// 123 = 0x7b = 0001111011 in 10 bits.
bits = BitArray();
AppendNumericBytes(L"123", bits);
EXPECT_EQ(ToString(bits), RemoveSpace("...XXXX. XX"));
// 1234 = "123" + "4" = 0001111011 + 0100
bits = BitArray();
AppendNumericBytes(L"1234", bits);
EXPECT_EQ(ToString(bits), RemoveSpace("...XXXX. XX.X.."));
// Empty.
bits = BitArray();
AppendNumericBytes(L"", bits);
EXPECT_EQ(ToString(bits), RemoveSpace(""));
}
TEST(QREncoderTest, AppendAlphanumericBytes)
{
// A = 10 = 0xa = 001010 in 6 bits
BitArray bits;
AppendAlphanumericBytes(L"A", bits);
EXPECT_EQ(ToString(bits), RemoveSpace("..X.X."));
// AB = 10 * 45 + 11 = 461 = 0x1cd = 00111001101 in 11 bits
bits = BitArray();
AppendAlphanumericBytes(L"AB", bits);
EXPECT_EQ(ToString(bits), RemoveSpace("..XXX..X X.X"));
// ABC = "AB" + "C" = 00111001101 + 001100
bits = BitArray();
AppendAlphanumericBytes(L"ABC", bits);
EXPECT_EQ(ToString(bits), RemoveSpace("..XXX..X X.X..XX. ."));
// Empty.
bits = BitArray();
AppendAlphanumericBytes(L"", bits);
EXPECT_EQ(ToString(bits), RemoveSpace(""));
// Invalid data.
EXPECT_THROW(AppendAlphanumericBytes(L"abc", bits), std::invalid_argument);
}
TEST(QREncoderTest, Append8BitBytes)
{
// 0x61, 0x62, 0x63
BitArray bits;
Append8BitBytes(L"abc", CharacterSet::Unknown, bits);
EXPECT_EQ(ToString(bits), RemoveSpace(".XX....X .XX...X. .XX...XX"));
// Empty.
bits = BitArray();
Append8BitBytes(L"", CharacterSet::Unknown, bits);
EXPECT_EQ(ToString(bits), RemoveSpace(""));
}
// Numbers are from page 21 of JISX0510:2004
TEST(QREncoderTest, AppendKanjiBytes)
{
BitArray bits;
AppendKanjiBytes(ShiftJISString({ 0x93, 0x5f }), bits);
EXPECT_EQ(ToString(bits), RemoveSpace(".XX.XX.. XXXXX"));
AppendKanjiBytes(ShiftJISString({ 0xe4, 0xaa }), bits);
EXPECT_EQ(ToString(bits), RemoveSpace(".XX.XX.. XXXXXXX. X.X.X.X. X."));
}
TEST(QREncoderTest, AppendBytes)
{
// Should use appendNumericBytes.
// 1 = 01 = 0001 in 4 bits.
BitArray bits;
AppendBytes(L"1", CodecMode::NUMERIC, CharacterSet::Unknown, bits);
EXPECT_EQ(ToString(bits), RemoveSpace("...X"));
// Should use appendAlphanumericBytes.
// A = 10 = 0xa = 001010 in 6 bits
bits = BitArray();
AppendBytes(L"A", CodecMode::ALPHANUMERIC, CharacterSet::Unknown, bits);
EXPECT_EQ(ToString(bits), RemoveSpace("..X.X."));
// Lower letters such as 'a' cannot be encoded in MODE_ALPHANUMERIC.
bits = BitArray();
EXPECT_THROW(AppendBytes(L"a", CodecMode::ALPHANUMERIC, CharacterSet::Unknown, bits), std::invalid_argument);
// Should use append8BitBytes.
// 0x61, 0x62, 0x63
bits = BitArray();
AppendBytes(L"abc", CodecMode::BYTE, CharacterSet::Unknown, bits);
EXPECT_EQ(ToString(bits), RemoveSpace(".XX....X .XX...X. .XX...XX"));
// Anything can be encoded in QRCode.MODE_8BIT_BYTE.
AppendBytes(L"\0", CodecMode::BYTE, CharacterSet::Unknown, bits);
// Should use appendKanjiBytes.
// 0x93, 0x5f
bits = BitArray();
AppendBytes(ShiftJISString({0x93, 0x5f}), CodecMode::KANJI, CharacterSet::Unknown, bits);
EXPECT_EQ(ToString(bits), RemoveSpace(".XX.XX.. XXXXX"));
}
TEST(QREncoderTest, TerminateBits)
{
BitArray v;
TerminateBits(0, v);
EXPECT_EQ(ToString(v), RemoveSpace(""));
v = BitArray();
TerminateBits(1, v);
EXPECT_EQ(ToString(v), RemoveSpace("........"));
v = BitArray();
v.appendBits(0, 3);
TerminateBits(1, v);
EXPECT_EQ(ToString(v), RemoveSpace("........"));
v = BitArray();
v.appendBits(0, 5);
TerminateBits(1, v);
EXPECT_EQ(ToString(v), RemoveSpace("........"));
v = BitArray();
v.appendBits(0, 8);
TerminateBits(1, v);
EXPECT_EQ(ToString(v), RemoveSpace("........"));
v = BitArray();
TerminateBits(2, v);
EXPECT_EQ(ToString(v), RemoveSpace("........ XXX.XX.."));
v = BitArray();
v.appendBits(0, 1);
TerminateBits(3, v);
EXPECT_EQ(ToString(v), RemoveSpace("........ XXX.XX.. ...X...X"));
}
TEST(QREncoderTest, GetNumDataBytesAndNumECBytesForBlockID)
{
int numDataBytes;
int numEcBytes;
// Version 1-H.
GetNumDataBytesAndNumECBytesForBlockID(26, 9, 1, 0, numDataBytes, numEcBytes);
EXPECT_EQ(9, numDataBytes);
EXPECT_EQ(17, numEcBytes);
// Version 3-H. 2 blocks.
GetNumDataBytesAndNumECBytesForBlockID(70, 26, 2, 0, numDataBytes, numEcBytes);
EXPECT_EQ(13, numDataBytes);
EXPECT_EQ(22, numEcBytes);
GetNumDataBytesAndNumECBytesForBlockID(70, 26, 2, 1, numDataBytes, numEcBytes);
EXPECT_EQ(13, numDataBytes);
EXPECT_EQ(22, numEcBytes);
// Version 7-H. (4 + 1) blocks.
GetNumDataBytesAndNumECBytesForBlockID(196, 66, 5, 0, numDataBytes, numEcBytes);
EXPECT_EQ(13, numDataBytes);
EXPECT_EQ(26, numEcBytes);
GetNumDataBytesAndNumECBytesForBlockID(196, 66, 5, 4, numDataBytes, numEcBytes);
EXPECT_EQ(14, numDataBytes);
EXPECT_EQ(26, numEcBytes);
// Version 40-H. (20 + 61) blocks.
GetNumDataBytesAndNumECBytesForBlockID(3706, 1276, 81, 0, numDataBytes, numEcBytes);
EXPECT_EQ(15, numDataBytes);
EXPECT_EQ(30, numEcBytes);
GetNumDataBytesAndNumECBytesForBlockID(3706, 1276, 81, 20, numDataBytes, numEcBytes);
EXPECT_EQ(16, numDataBytes);
EXPECT_EQ(30, numEcBytes);
GetNumDataBytesAndNumECBytesForBlockID(3706, 1276, 81, 80, numDataBytes, numEcBytes);
EXPECT_EQ(16, numDataBytes);
EXPECT_EQ(30, numEcBytes);
}
// Numbers are from path_to_url and
// path_to_url
TEST(QREncoderTest, GenerateECBytes)
{
ByteArray ecBytes;
GenerateECBytes({ 32, 65, 205, 69, 41, 220, 46, 128, 236 }, 17, ecBytes);
ByteArray expected = { 42, 159, 74, 221, 244, 169, 239, 150, 138, 70, 237, 85, 224, 96, 74, 219, 61 };
EXPECT_EQ(ecBytes, expected);
GenerateECBytes({ 67, 70, 22, 38, 54, 70, 86, 102, 118, 134, 150, 166, 182, 198, 214 }, 18, ecBytes);
expected = { 175, 80, 155, 64, 178, 45, 214, 233, 65, 209, 12, 155, 117, 31, 140, 214, 27, 187 };
EXPECT_EQ(ecBytes, expected);
// High-order zero coefficient case.
GenerateECBytes({ 32, 49, 205, 69, 42, 20, 0, 236, 17 }, 17, ecBytes);
expected = { 0, 3, 130, 179, 194, 0, 55, 211, 110, 79, 98, 72, 170, 96, 211, 137, 213 };
EXPECT_EQ(ecBytes, expected);
}
TEST(QREncoderTest, InterleaveWithECBytes)
{
BitArray in;
for (int dataByte : {32, 65, 205, 69, 41, 220, 46, 128, 236})
in.appendBits(dataByte, 8);
BitArray out = InterleaveWithECBytes(in, 26, 9, 1);
std::vector<uint8_t> expected = {
32, 65, 205, 69, 41, 220, 46, 128, 236,
42, 159, 74, 221, 244, 169, 239, 150, 138, 70, 237, 85, 224, 96, 74, 219, 61,
}; // Error correction bytes in second block
ASSERT_EQ(Size(expected), out.sizeInBytes());
EXPECT_EQ(expected, out.toBytes());
// Numbers are from path_to_url
in = BitArray();
for (int dataByte :
{67, 70, 22, 38, 54, 70, 86, 102, 118, 134, 150, 166, 182, 198, 214, 230, 247, 7, 23, 39, 55,
71, 87, 103, 119, 135, 151, 166, 22, 38, 54, 70, 86, 102, 118, 134, 150, 166, 182, 198, 214, 230,
247, 7, 23, 39, 55, 71, 87, 103, 119, 135, 151, 160, 236, 17, 236, 17, 236, 17, 236, 17})
in.appendBits(dataByte, 8);
out = InterleaveWithECBytes(in, 134, 62, 4);
expected = {
67, 230, 54, 55, 70, 247, 70, 71, 22, 7, 86, 87, 38, 23, 102, 103, 54, 39, 118, 119, 70,
55, 134, 135, 86, 71, 150, 151, 102, 87, 166, 160, 118, 103, 182, 236, 134, 119, 198, 17, 150, 135,
214, 236, 166, 151, 230, 17, 182, 166, 247, 236, 198, 22, 7, 17, 214, 38, 23, 236, 39, 17,
175, 155, 245, 236, 80, 146, 56, 74, 155, 165, 133, 142, 64, 183, 132, 13, 178, 54, 132, 108, 45,
113, 53, 50, 214, 98, 193, 152, 233, 147, 50, 71, 65, 190, 82, 51, 209, 199, 171, 54, 12, 112,
57, 113, 155, 117, 211, 164, 117, 30, 158, 225, 31, 190, 242, 38, 140, 61, 179, 154, 214, 138, 147,
87, 27, 96, 77, 47, 187, 49, 156, 214,
}; // Error correction bytes in second block
EXPECT_EQ(Size(expected), out.sizeInBytes());
EXPECT_EQ(expected, out.toBytes());
}
TEST(QREncoderTest, BugInBitVectorNumBytes)
{
// There was a bug in BitVector.sizeInBytes() that caused it to return a
// smaller-by-one value (ex. 1465 instead of 1466) if the number of bits
// in the vector is not 8-bit aligned. In QRCodeEncoder::InitQRCode(),
// BitVector::sizeInBytes() is used for finding the smallest QR Code
// version that can fit the given data. Hence there were corner cases
// where we chose a wrong QR Code version that cannot fit the given
// data. Note that the issue did not occur with MODE_8BIT_BYTE, as the
// bits in the bit vector are always 8-bit aligned.
//
// Before the bug was fixed, the following test didn't pass, because:
//
// - MODE_NUMERIC is chosen as all bytes in the data are '0'
// - The 3518-byte numeric data needs 1466 bytes
// - 3518 / 3 * 10 + 7 = 11727 bits = 1465.875 bytes
// - 3 numeric bytes are encoded in 10 bits, hence the first
// 3516 bytes are encoded in 3516 / 3 * 10 = 11720 bits.
// - 2 numeric bytes can be encoded in 7 bits, hence the last
// 2 bytes are encoded in 7 bits.
// - The version 27 QR Code with the EC level L has 1468 bytes for data.
// - 1828 - 360 = 1468
// - In InitQRCode(), 3 bytes are reserved for a header. Hence 1465 bytes
// (1468 -3) are left for data.
// - Because of the bug in BitVector::sizeInBytes(), InitQRCode() determines
// the given data can fit in 1465 bytes, despite it needs 1466 bytes.
// - Hence QRCodeEncoder.encode() failed and returned false.
// - To be precise, it needs 11727 + 4 (getMode info) + 14 (length info) =
// 11745 bits = 1468.125 bytes are needed (i.e. cannot fit in 1468
// bytes).
Encode(std::wstring(3518, L'0'), ErrorCorrectionLevel::Low, CharacterSet::Unknown, 0, false, -1);
}
```
|
/content/code_sandbox/test/unit/qrcode/QREncoderTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 9,449
|
```c++
/*
*/
#include "qrcode/QRDecoder.h"
#include "BitMatrix.h"
#include "BitMatrixIO.h"
#include "DecoderResult.h"
#include "ECI.h"
#include "gtest/gtest.h"
using namespace ZXing;
using namespace ZXing::QRCode;
TEST(RMQRDecoderTest, RMQRCodeR7x43M)
{
const auto bitMatrix = ParseBitMatrix(
"XXXXXXX X X X X X X XXX X X X X X X X X XXX\n"
"X X X XXX XXXXX XXX X X XX X X\n"
"X XXX X X XXX X X X XXXX XXXX X X XXXXXXXX\n"
"X XXX X XX XXXXX XXXXXX X X X X\n"
"X XXX X XX XXX XXXXXXX X X XX X X X\n"
"X X XXXXX XXX XXX XXXXX XXXXXX X X\n"
"XXXXXXX X X X X X X XXX X X X X X X X XXXXX\n",
'X', false);
const auto result = Decode(bitMatrix);
EXPECT_TRUE(result.isValid());
EXPECT_EQ(result.content().text(TextMode::Plain), "ABCDEFG");
}
TEST(RMQRDecoderTest, RMQRCodeR7x43MError6Bits)
{
const auto bitMatrix = ParseBitMatrix(
"XXXXXXX X X X X X X XXX X X X X X X X X XXX\n"
"X X X XXX XXXXX XXX X X XX X X\n"
"X XXX X X XXX X X XXXX XXXX XX X XXXXXXXX\n" // 2
"X XXX X XX XXXXX X XXXXXX X X X X\n" // 3
"X XXX X XX XXX XXXXXXX X X XXX X X X\n" // 5
"X X XXXXX XXX XXX XXXX X XXXXXX X X\n" // 6
"XXXXXXX X X X X X X XXX X X X X X X X XXXXX\n",
'X', false);
const auto result = Decode(bitMatrix);
EXPECT_EQ(Error::Checksum, result.error());
EXPECT_TRUE(result.text().empty());
EXPECT_TRUE(result.content().text(TextMode::Plain).empty());
}
TEST(RMQRDecoderTest, RMQRCodeR7x139H)
{
const auto bitMatrix = ParseBitMatrix(
"XXXXXXX X X X X X X X X X XXX X X X X X X X X X X X X XXX X X X X X X X X X X X X XXX X X X X X X X X X X X X XXX X X X X X X X X X X X XXX\n"
"X X XX XXX X X X X X XX XX X X X XXX XX XXXX XXX XX XX XX X XX X X X XXX X XX XX XX X X XX X XX XXXX X X X\n"
"X XXX X X XXXXX X XXXXX X X XXX XX X XXX X XX XXX XX X XXX X X XXXX X XXXXXXX X XX XXX X X X XXX X XXXXX\n"
"X XXX X XXXX X XX X X XX XX X XX XX X XXX XX X XX X XX X X XX X X XXX X X X X X X X XX X XX XX X X X\n"
"X XXX X XXXX XXXXX X X XXXXXX XX X XXXX X XXXX X XXX XXXX X XXXXXXX XXX XXXXXX X X XX X XXX X XXXXXXXXX X XXXX X X X X X\n"
"X X X XX XX X X XX X X X XXXX X X X XX X XXX X X X X X XXX XX XXX X X XX XXXX XX X X X X XXXXX XXX XX X XX X\n"
"XXXXXXX X X X X X X X X X XXX X X X X X X X X X X X X XXX X X X X X X X X X X X X XXX X X X X X X X X X X X X XXX X X X X X X X X X X XXXXX\n",
'X', false);
const auto result = Decode(bitMatrix);
EXPECT_TRUE(result.isValid());
EXPECT_EQ(result.content().text(TextMode::Plain), "1234567890,ABCDEFGHIJKLMOPQRSTUVW");
}
TEST(RMQRDecoderTest, RMQRCodeR9x59H)
{
const auto bitMatrix = ParseBitMatrix(
"XXXXXXX X X X X X XXX X X X X X X X X XXX X X X X X X X XXX\n"
"X X X XXXXX XXX X X XXXXXXXX X X X X XXXX X X\n"
"X XXX X XX XXX X XXX XXXX X XXXXXXX X XXXXX X X\n"
"X XXX X XXXX X XX X XX XXXX XX XX X X X XXX X \n"
"X XXX X X X XX XXXXXX X X XX X XX X X XXXX XXXXX\n"
"X X X X X X XXX X X X XX X XXXX XX X X X X\n"
"XXXXXXX XXXXX XXXXXX X XX XXX X XXXX X X X XX X X\n"
" XXX XXXX XX XXX X XXXXXXX X XX XXX XX XX X\n"
"XXX X X X X X X X XXX X X X X X X X X XXX X X X X X X XXXXX\n",
'X', false);
const auto result = Decode(bitMatrix);
EXPECT_TRUE(result.isValid());
EXPECT_EQ(result.content().text(TextMode::Plain), "ABCDEFGHIJKLMN");
}
TEST(RMQRDecoderTest, RMQRCodeR9x77M)
{
const auto bitMatrix = ParseBitMatrix(
"XXXXXXX X X X X X X X X XXX X X X X X X X X X X X XXX X X X X X X X X X X XXX\n"
"X X XXX XX XXX XXX XXXX XXX XX X XXXXXXXXX X XXX XXXX X XXXX XX XXX X\n"
"X XXX X X X X XXX X XXXX XX XX X XX XX XXX XXXX X X XX X X XX X\n"
"X XXX X X X XXXXXX X XX XXXX X XXX X XX X XX XX XX X XXX X X XXX XX \n"
"X XXX X XXXX X X XXXX XXXX XX XXX X XX XXXXXX X X XXX XX XXXXX\n"
"X X X X XX XXX X X XX X X XX XXX X X X X X XX XXXXX X\n"
"XXXXXXX X XX XX X XXXX X X X X X XX XXX X XX X XXX XX X X\n"
" X XXXXX XX X XXXXXX XX XXXXX X XX XX XXXXX XXX X\n"
"XXX X X X X X X X X X X XXX X X X X X X X X X X X XXX X X X X X X X X X XXXXX\n",
'X', false);
const auto result = Decode(bitMatrix);
EXPECT_TRUE(result.isValid());
EXPECT_EQ(result.content().text(TextMode::Plain), "__ABCDEFGH__1234567890___ABCDEFGHIJK");
}
TEST(RMQRDecoderTest, RMQRCodeR11x27H)
{
const auto bitMatrix = ParseBitMatrix(
"XXXXXXX X X X X X X X X XXX\n"
"X X XX X X X X\n"
"X XXX X X XX X X XX\n"
"X XXX X XXXX XX X XXXXXX \n"
"X XXX X X X XX XX XXX X\n"
"X X XXX X XX XXXX X \n"
"XXXXXXX X XX X XXXXX\n"
" X X X X X\n"
"XXXX X X X XX XXXXXX X X\n"
"X XX XXXXXX XXX XXXX X X\n"
"XXX X X X X X X X X X XXXXX\n",
'X', false);
const auto result = Decode(bitMatrix);
EXPECT_TRUE(result.isValid());
EXPECT_EQ(result.content().text(TextMode::Plain), "ABCDEF");
}
TEST(RMQRDecoderTest, RMQRCodeR13x27M_ECI)
{
const auto bitMatrix = ParseBitMatrix(
"XXXXXXX X X X X X X X X XXX\n"
"X X XX XX XXX XX X\n"
"X XXX X XX X XX XX XXX X\n"
"X XXX X XX X XX X X XX \n"
"X XXX X XXXXXXX X X XX\n"
"X X XX X XXX XX XX \n"
"XXXXXXX X X X X XXX\n"
" XXX XX X XX XXX \n"
"XXX XX XX X X XX XX XXXXX\n"
" XXX X X X X X X\n"
"X XX X X XX X XX X X X X\n"
"X X X X X X X X X\n"
"XXX X X X X X X X X X XXXXX\n",
'X', false);
const auto result = Decode(bitMatrix);
EXPECT_TRUE(result.isValid());
EXPECT_EQ(result.content().text(TextMode::Plain), "AB12345AB");
EXPECT_TRUE(result.content().hasECI);
EXPECT_EQ(result.content().encodings[0].eci, ECI::Shift_JIS);
EXPECT_EQ(result.content().symbology.toString(), "]Q1");
}
TEST(RMQRDecoderTest, RMQRCodeR15x59H_GS1)
{
const auto bitMatrix = ParseBitMatrix(
"XXXXXXX X X X X X XXX X X X X X X X X XXX X X X X X X X XXX\n"
"X X XXX XXX X XXXXX XX XXX X X X X X X XXX X\n"
"X XXX X XXX XX X XXX XXX X X XXX XXXXX XX XXX XX\n"
"X XXX X X X XX X X XXX X X X XXXXX XX XXX \n"
"X XXX X XX XXX XX X X X XX XX XX XXX XXXX X XXXX\n"
"X X X X X X X XXX XXX XXXX X XXX XX X X \n"
"XXXXXXX X XXX XXXX X XX XXXX X X XX XXX XXXXX X\n"
" X XXX X XXXXX X XX XXXX XX X \n"
"XX XX X X X XXXXX XX X X XX XX X XX X X XX X\n"
" XX XX X XXXXXX XXX XX X X XX XXX X X XXX \n"
"X X XX XXXXXXXXXX XX X X XX XX XX X XXXX XX XXXXXX\n"
" XX X XX X XXX X X X XXX X XXX X X XXX XXXX X\n"
"XXXX X X XX XXX X X X XX XXXXX XX X XX XXX X X\n"
"X X X XX XXX XXXXXXX XXX X XXX XX X X X XX X\n"
"XXX X X X X X X X XXX X X X X X X X X XXX X X X X X X XXXXX\n",
'X', false);
const auto result = Decode(bitMatrix);
EXPECT_TRUE(result.isValid());
EXPECT_TRUE(result.content().type() == ContentType::GS1);
EXPECT_EQ(result.content().text(TextMode::HRI), "(01)09524000059109(21)12345678p901(10)1234567p(17)231120");
}
TEST(RMQRDecoderTest, RMQRCodeR17x99H)
{
const auto bitMatrix = ParseBitMatrix(
"XXXXXXX X X X X X X X XXX X X X X X X X X X X X XXX X X X X X X X X X X X XXX X X X X X X X X X XXX\n"
"X X X XXXXX XXX X X X XX X X XX XXXXX X XX X XX XXX X X XX X X XXX X X XX X X X\n"
"X XXX X X X XXX XXX X XXX XXX X X XX XXXX X X X X XXX XXXXX X X XX X XX X X\n"
"X XXX X XX X XX X X XX X XXXX X XXXXX X X XX X XXX XX X X X X XXXXXX X \n"
"X XXX X X XX X X X X X X X X XXX XX XXXXXX X X XXX X XXXXXX X X X X X X X XX X\n"
"X X XX X X XXXXX XX X XXX X XX X X XXX X XXX XXX X XXXX XX X X X XX XXXX \n"
"XXXXXXX X XX X XX X X XXX XX X XXXX X X XXX X X XX X XXXX XX X X X XX X XXXX\n"
" XX XX XX XX X XX X X X XXX XX X X XXX XXXX XX X X X X XX XX XXX \n"
"XX X XXX X X XXXX XXX XXXXX XXX XXX X X X X X XXX X XX XX X X X X XX X XXX\n"
" X XXXXX X X XXXXX X XX X XX XXXX X X XXXXX X XX X XX X XX X XX XX \n"
"X XX XX X XX XXX XX XXXXXX X XXXXX XX XXXX X X X X XXXX XX X X XXXXXX XX X X\n"
" XXX XX XXX XX XX X X X XX X X X X XX XXX XXXX X XX XXX X X X XXXX XXXXX X XXX \n"
"X X XX X XX XX XX X X XX X X X XX XXXXXXXX X XX XX X X X X X XX X X XXXXXXXXXXX\n"
" X X X XX X X X XX XXXX X XXX X XX X X X X X XXX XXXXX XX X X X XXXXX X X X\n"
"XXXX XX XX X XXXX XXXX X XX X XX XX XX XXXX XXX X X XX XX X XXXX X XXX XX X XX X X\n"
"X XXX XX XXX X X X XXX X XXX X XXXX XX X X XXXXX X XX X X X X X X X X XXXX XXXX X\n"
"XXX X X X X X X X X X XXX X X X X X X X X X X X XXX X X X X X X X X X X X XXX X X X X X X X X XXXXX\n",
'X', false);
const auto result = Decode(bitMatrix);
EXPECT_TRUE(result.isValid());
EXPECT_EQ(result.content().text(TextMode::Plain), your_sha256_hash______");
}
```
|
/content/code_sandbox/test/unit/qrcode/RMQRDecoderTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 3,736
|
```c++
/*
*/
#include "qrcode/QRVersion.h"
#include "BitMatrix.h"
#include "BitMatrixIO.h"
#include "gtest/gtest.h"
using namespace ZXing;
using namespace ZXing::QRCode;
namespace {
void CheckVersion(const Version* version, int number, int dimension) {
ASSERT_NE(version, nullptr);
EXPECT_EQ(number, version->versionNumber());
if (number > 1 && version->isModel2()) {
EXPECT_FALSE(version->alignmentPatternCenters().empty());
}
EXPECT_EQ(dimension, version->dimension());
}
void DoTestVersion(int expectedVersion, int mask) {
auto version = Version::DecodeVersionInformation(mask);
ASSERT_NE(version, nullptr);
EXPECT_EQ(expectedVersion, version->versionNumber());
}
}
TEST(QRVersionTest, VersionForNumber)
{
auto version = Version::Model2(0);
EXPECT_EQ(version, nullptr) << "There is version with number 0";
for (int i = 1; i <= 40; i++) {
CheckVersion(Version::Model2(i), i, 4*i + 17);
}
}
TEST(QRVersionTest, GetProvisionalVersionForDimension)
{
for (int i = 1; i <= 40; i++) {
EXPECT_EQ(i, Version::Number(BitMatrix(4 * i + 17)));
}
}
TEST(QRVersionTest, DecodeVersionInformation)
{
// Spot check
DoTestVersion(7, 0x07C94);
DoTestVersion(12, 0x0C762);
DoTestVersion(17, 0x1145D);
DoTestVersion(22, 0x168C9);
DoTestVersion(27, 0x1B08E);
DoTestVersion(32, 0x209D5);
}
TEST(QRVersionTest, MicroVersionForNumber)
{
auto version = Version::Micro(0);
EXPECT_EQ(version, nullptr) << "There is version with number 0";
for (int i = 1; i <= 4; i++) {
CheckVersion(Version::Micro(i), i, 2 * i + 9);
}
}
TEST(QRVersionTest, GetProvisionalMicroVersionForDimension)
{
for (int i = 1; i <= 4; i++) {
EXPECT_EQ(i, Version::Number(BitMatrix(2 * i + 9)));
}
}
TEST(QRVersionTest, FunctionPattern)
{
auto testFinderPatternRegion = [](const BitMatrix& bitMatrix) {
for (int row = 0; row < 9; row++)
for (int col = 0; col < 9; col++)
EXPECT_TRUE(bitMatrix.get(col, row));
};
for (int i = 1; i <= 4; i++) {
const auto version = Version::Micro(i);
const auto functionPattern = version->buildFunctionPattern();
testFinderPatternRegion(functionPattern);
// Check timing pattern areas.
const auto dimension = version->dimension();
for (int row = dimension; row < functionPattern.height(); row++)
EXPECT_TRUE(functionPattern.get(0, row));
for (int col = dimension; col < functionPattern.width(); col++)
EXPECT_TRUE(functionPattern.get(col, 0));
}
}
namespace {
void CheckRMQRVersion(const Version* version, int number) {
ASSERT_NE(version, nullptr);
EXPECT_EQ(number, version->versionNumber());
EXPECT_EQ(Version::SymbolSize(number, Type::rMQR).x == 27, version->alignmentPatternCenters().empty());
}
}
TEST(QRVersionTest, RMQRVersionForNumber)
{
auto version = Version::rMQR(0);
EXPECT_EQ(version, nullptr) << "There is version with number 0";
for (int i = 1; i <= 32; i++) {
CheckRMQRVersion(Version::rMQR(i), i);
}
}
TEST(QRVersionTest, RMQRFunctionPattern)
{
{
const auto expected = ParseBitMatrix(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"
"XXXXXXXXXXXX XXX XXXXXXXX\n"
"XXXXXXXXXXXX XXX XXXXXXXX\n"
"XXXXXXXXXXXX X XXXXXXXX\n"
"XXXXXXXXXXX XXX XXXXXXXX\n"
"XXXXXXXXXXX XXX XXXXXXXX\n"
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n",
'X', false);
const auto version = Version::rMQR(1); // R7x43
const auto functionPattern = version->buildFunctionPattern();
EXPECT_EQ(expected, functionPattern);
}
{
const auto expected = ParseBitMatrix(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"
"XXXXXXXXXXXX XXX XX\n"
"XXXXXXXXXXXX XXX X\n"
"XXXXXXXXXXXX X XXXXXX X\n"
"XXXXXXXXXXX X XXXXXXXX\n"
"XXXXXXXXXXX X XXXXXXXX\n"
"XXXXXXXX XXX XXXXXXXX\n"
"XXXXXXXX XXX XXXXXXXX\n"
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n",
'X', false);
const auto version = Version::rMQR(6); // R9x43
const auto functionPattern = version->buildFunctionPattern();
EXPECT_EQ(expected, functionPattern);
}
{
const auto expected = ParseBitMatrix(
"XXXXXXXXXXXXXXXXXXXXXXXXXXX\n"
"XXXXXXXXXXXX XX\n"
"XXXXXXXXXXXX X\n"
"XXXXXXXXXXXX X\n"
"XXXXXXXXXXX X\n"
"XXXXXXXXXXX XXXXXX X\n"
"XXXXXXXX XXXXXXXX\n"
"XXXXXXXX XXXXXXXX\n"
"X XXXXXXXX\n"
"XX XXXXXXXX\n"
"XXXXXXXXXXXXXXXXXXXXXXXXXXX\n",
'X', false);
const auto version = Version::rMQR(11); // R11x27
const auto functionPattern = version->buildFunctionPattern();
EXPECT_EQ(expected, functionPattern);
}
{
const auto expected = ParseBitMatrix(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"
"XXXXXXXXXXXX XXX XX\n"
"XXXXXXXXXXXX XXX X\n"
"XXXXXXXXXXXX X X\n"
"XXXXXXXXXXX X X\n"
"XXXXXXXXXXX X XXXXXX X\n"
"XXXXXXXX X XXXXXXXX\n"
"XXXXXXXX X XXXXXXXX\n"
"X XXX XXXXXXXX\n"
"XX XXX XXXXXXXX\n"
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n",
'X', false);
const auto version = Version::rMQR(12); // R11x43
const auto functionPattern = version->buildFunctionPattern();
EXPECT_EQ(expected, functionPattern);
}
{
const auto expected = ParseBitMatrix(
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"
"XXXXXXXXXXXX XXX XXX XX\n"
"XXXXXXXXXXXX XXX XXX X\n"
"XXXXXXXXXXXX X X X\n"
"XXXXXXXXXXX X X X\n"
"XXXXXXXXXXX X X XXXXXX X\n"
"XXXXXXXX X X XXXXXXXX\n"
"XXXXXXXX X X XXXXXXXX\n"
"X XXX XXX XXXXXXXX\n"
"XX XXX XXX XXXXXXXX\n"
"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n",
'X', false);
const auto version = Version::rMQR(13); // R11x59
const auto functionPattern = version->buildFunctionPattern();
EXPECT_EQ(expected, functionPattern);
}
}
```
|
/content/code_sandbox/test/unit/qrcode/QRVersionTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 1,733
|
```c++
/*
*/
#include "oned/ODUPCEWriter.h"
#include "BitMatrixIO.h"
#include "gtest/gtest.h"
#include <stdexcept>
using namespace ZXing;
using namespace ZXing::OneD;
namespace {
std::string Encode(const std::string& input)
{
auto result = ToString(UPCEWriter().encode(input, 0, 0), '1', '0', false);
return result.substr(0, result.size() - 1); // remove the \n at the end
}
}
TEST(ODUPCEWriterTest, Encode1)
{
std::string toEncode = "05096893";
std::string expected = "000010101110010100111000101101011110110111001011101010100000";
EXPECT_EQ(Encode(toEncode), expected);
}
TEST(ODUPCEWriterTest, EncodeSystem1)
{
std::string toEncode = "12345670";
std::string expected = "000010100100110111101010001101110010000101001000101010100000";
EXPECT_EQ(Encode(toEncode), expected);
}
TEST(ODUPCEWriterTest, AddChecksumAndEncode)
{
std::string toEncode = "0509689";
std::string expected = "000010101110010100111000101101011110110111001011101010100000";
EXPECT_EQ(Encode(toEncode), expected);
}
TEST(ODUPCEWriterTest, EncodeIllegalCharacters)
{
EXPECT_THROW(Encode("05096abc"), std::invalid_argument);
}
```
|
/content/code_sandbox/test/unit/oned/ODUPCEWriterTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 323
|
```c++
/*
*/
#include "BitArray.h"
#include "BitArrayUtility.h"
#include "HRI.h"
#include "oned/ODDataBarExpandedBitDecoder.h"
#include "gtest/gtest.h"
using namespace ZXing;
static std::string parse(std::string bitStr)
{
return HRIFromGS1(OneD::DataBar::DecodeExpandedBits(Utility::ParseBitArray(bitStr, '1')));
}
TEST(ODDataBarExpandedBitDecoderTest, FNC1NumericLatch)
{
std::string result;
// Correctly encoded (Alphanumeric FNC1 "01111" implying numeric latch)
result = parse(your_sha256_hash);
EXPECT_EQ(result, "(10)12A(422)123");
// Incorrectly encoded (Alphanumeric FNC1 "01111" followed by numeric latch "000")
result = parse(your_sha256_hash100");
EXPECT_EQ(result, "(10)12A(422)123");
// Correctly encoded (ISO646 FNC1 "01111" implying numeric latch)
result = parse(your_sha256_hash000010000100");
EXPECT_EQ(result, "(10)12((422)123");
// Incorrectly encoded (ISO646 FNC1 "01111" followed by numeric latch "000")
result = parse(your_sha256_hash100000010000100");
EXPECT_EQ(result, "(10)12((422)123");
}
TEST(ODDataBarExpandedBitDecoderTest, DecodeAI01392x)
{
std::string result;
// Parse AIs following AI01392x
result = parse(your_sha256_hash0001001");
EXPECT_EQ(result, "(01)90012345678908(3920)1(20)01");
result = parse(your_sha256_hash111100000010000010");
EXPECT_EQ(result, "(01)90012345678908(3922)7955(20)01");
result = parse(your_sha256_hash101010101101100010110111011101011001"
"01010101101111100000010000011101");
EXPECT_EQ(result, "(01)90012345678908(3929)12345678901234(20)01");
}
TEST(ODDataBarExpandedBitDecoderTest, DecodeAI01393x)
{
std::string result;
// Parse AIs following AI01393x
result = parse(your_sha256_hash101001111000010010010011000010000010"
"000100110");
EXPECT_EQ(result, "(01)90012345678908(3930)0121(20)01(10)AB1");
result = parse(your_sha256_hash101010110111110000001000001010000000"
"010110000010000100110");
EXPECT_EQ(result, "(01)90012345678908(3932)0081234(20)01(10)AB1");
result = parse(your_sha256_hash101010110110001011011101110101100101"
"0101011011001001001111000010010010011000010000010000100110");
EXPECT_EQ(result, "(01)90012345678908(3933)997123456789012345(20)01(10)AB1");
}
```
|
/content/code_sandbox/test/unit/oned/ODDataBarExpandedBitDecoderTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 687
|
```c++
/*
*/
#include "oned/ODCode128Reader.h"
#include "ReaderOptions.h"
#include "Barcode.h"
#include "gtest/gtest.h"
using namespace ZXing;
using namespace ZXing::OneD;
// Helper to call decodePattern()
static Barcode parse(const int startPattern, PatternRow row)
{
if (startPattern == 'A') {
row.insert(row.begin(), { 0, 2, 1, 1, 4, 1, 2 });
} else if (startPattern == 'B') {
row.insert(row.begin(), { 0, 2, 1, 1, 2, 1, 4 });
} else if (startPattern == 'C') {
row.insert(row.begin(), { 0, 2, 1, 1, 2, 3, 2 });
}
row.insert(row.end(), { 2, 3, 3, 1, 1, 1, 2, 0 }); // Stop pattern
std::unique_ptr<Code128Reader::DecodingState> state;
ReaderOptions opts;
Code128Reader reader(opts);
PatternView next(row);
return reader.decodePattern(0, next, state);
}
TEST(ODCode128ReaderTest, SymbologyIdentifier)
{
{
// Plain "2001"
PatternRow row({ 2, 2, 1, 2, 3, 1, 2, 2, 2, 1, 2, 2, 3, 1, 1, 2, 2, 2 });
auto result = parse('C', row);
EXPECT_EQ(result.symbologyIdentifier(), "]C0");
EXPECT_EQ(result.text(), "2001");
}
{
// GS1 "(20)01"
PatternRow row({ 4, 1, 1, 1, 3, 1, 2, 2, 1, 2, 3, 1, 2, 2, 2, 1, 2, 2, 1, 3, 2, 1, 3, 1 });
auto result = parse('C', row);
EXPECT_EQ(result.symbologyIdentifier(), "]C1");
EXPECT_EQ(result.text(TextMode::HRI), "(20)01");
}
{
// AIM "A FNC1 B"
PatternRow row({ 1, 1, 1, 3, 2, 3, 4, 1, 1, 1, 3, 1, 1, 3, 1, 1, 2, 3, 2, 1, 2, 3, 2, 1 });
auto result = parse('B', row);
EXPECT_EQ(result.symbologyIdentifier(), "]C2");
EXPECT_EQ(result.text(), "AB");
}
{
// AIM "z FNC1 B"
PatternRow row({ 2, 1, 4, 1, 2, 1, 4, 1, 1, 1, 3, 1, 1, 3, 1, 1, 2, 3, 4, 2, 1, 2, 1, 1 });
auto result = parse('B', row);
EXPECT_EQ(result.symbologyIdentifier(), "]C2");
EXPECT_EQ(result.text(), "zB");
}
{
// AIM "99 FNC1 A"
PatternRow row({ 1, 1, 3, 1, 4, 1, 4, 1, 1, 1, 3, 1, 1, 1, 4, 1, 3, 1, 1, 1, 1, 3, 2, 3, 1, 2, 3, 1, 2, 2 });
auto result = parse('C', row);
EXPECT_EQ(result.symbologyIdentifier(), "]C2");
EXPECT_EQ(result.text(), "99A");
}
{
// Bad AIM Application Indicator "? FNC1 B"
PatternRow row({ 2, 1, 2, 3, 2, 1, 4, 1, 1, 1, 3, 1, 1, 3, 1, 1, 2, 3, 3, 2, 2, 2, 1, 1 });
auto result = parse('B', row);
EXPECT_EQ(result.symbologyIdentifier(), "]C0"); // Just ignoring, not giving FormatError
EXPECT_EQ(result.text(), "?<GS>B");
}
}
TEST(ODCode128ReaderTest, ReaderInit)
{
{
// Null
PatternRow row({ 1, 1, 1, 1, 4, 3, 1, 3, 1, 1, 4, 1 });
auto result = parse('C', row);
EXPECT_FALSE(result.readerInit());
EXPECT_EQ(result.text(), "92");
}
{
// Set (FNC3 first)
PatternRow row({ 1, 1, 4, 3, 1, 1, 1, 1, 3, 1, 4, 1, 1, 1, 1, 1, 4, 3, 3, 3, 1, 1, 2, 1 });
auto result = parse('B', row);
EXPECT_TRUE(result.readerInit());
EXPECT_EQ(result.text(), "92");
}
{
// Set (FNC3 between "9" and "2" )
PatternRow row({ 3, 2, 1, 1, 2, 2, 1, 1, 4, 3, 1, 1, 2, 2, 3, 2, 1, 1, 1, 2, 1, 4, 2, 1 });
auto result = parse('B', row);
EXPECT_TRUE(result.readerInit());
EXPECT_EQ(result.text(), "92");
}
}
```
|
/content/code_sandbox/test/unit/oned/ODCode128ReaderTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 1,377
|
```c++
/*
*/
#include "ByteArray.h"
#include "DecoderResult.h"
#include "gtest/gtest.h"
#include <utility>
namespace ZXing::MaxiCode::DecodedBitStreamParser {
DecoderResult Decode(ByteArray&& bytes, const int mode);
}
using namespace ZXing;
// Pad out to max data length 93 (mode 4)
static void pad(ByteArray& padded)
{
while (padded.size() < 93 + 1) { // 93 + mode
padded.push_back(33);
}
}
// Helper to call Decode()
static DecoderResult parse(ByteArray bytes, const int mode, ByteArray *mode2or3 = nullptr)
{
ByteArray padded;
padded.reserve(93 + 1); // 93 + mode
if (mode == 2) {
if (mode2or3) {
padded = *mode2or3;
} else {
// Mode 2, Postcode 152382802, Country 840, Class 001 example from ISO/IEC 16023:2000 Annex B.2
padded = {34, 20, 45, 20, 17, 18, 2, 18, 7, 0};
}
} else if (mode == 3) {
if (mode2or3) {
padded = *mode2or3;
} else {
// Mode 3, Postcode B1050, Country 056, Class 999 example from ISO/IEC 16023:2000 Annex B.1
padded = {3, 8, 28, 13, 28, 44, 0, 14, 28, 62};
}
} else {
padded.push_back(mode);
}
padded.insert(padded.end(), bytes.begin(), bytes.end());
pad(padded);
return MaxiCode::DecodedBitStreamParser::Decode(std::move(padded), mode);
}
// Helper to return Structured Append
static StructuredAppendInfo info(ByteArray bytes, const int mode)
{
return parse(bytes, mode).structuredAppend();
}
TEST(MCDecoderTest, StructuredAppendSymbologyIdentifier)
{
// Null
EXPECT_EQ(info({49}, 2).index, -1); // Mode 2
EXPECT_EQ(info({49}, 2).count, -1);
EXPECT_TRUE(info({49}, 2).id.empty());
EXPECT_EQ(parse({49}, 2).symbologyIdentifier(), "]U1");
EXPECT_EQ(info({49}, 3).index, -1); // Mode 3
EXPECT_EQ(info({49}, 3).count, -1);
EXPECT_TRUE(info({49}, 3).id.empty());
EXPECT_EQ(parse({49}, 3).symbologyIdentifier(), "]U1");
EXPECT_EQ(info({49}, 4).index, -1); // Mode 4
EXPECT_EQ(info({49}, 4).count, -1);
EXPECT_TRUE(info({49}, 4).id.empty());
EXPECT_EQ(parse({49}, 4).symbologyIdentifier(), "]U0");
EXPECT_EQ(info({49}, 5).index, -1); // Mode 5
EXPECT_EQ(info({49}, 5).count, -1);
EXPECT_TRUE(info({49}, 5).id.empty());
EXPECT_EQ(parse({49}, 5).symbologyIdentifier(), "]U0");
EXPECT_EQ(info({49}, 6).index, -1); // Mode 6
EXPECT_EQ(info({49}, 6).count, -1);
EXPECT_TRUE(info({49}, 6).id.empty());
// EXPECT_TRUE(parse({49}, 6).symbologyIdentifier().empty()); // Not defined for reader initialisation/programming
// ISO/IEC 16023:2000 4.9.1 example
EXPECT_EQ(info({33, 22, 49}, 2).index, 2); // Mode 2 - 3rd position 1-based == index 2
EXPECT_EQ(info({33, 22, 49}, 2).count, 7);
EXPECT_TRUE(info({33, 22, 49}, 2).id.empty());
EXPECT_EQ(info({33, 22, 49}, 3).index, 2); // Mode 3
EXPECT_EQ(info({33, 22, 49}, 3).count, 7);
EXPECT_TRUE(info({33, 22, 49}, 3).id.empty());
EXPECT_EQ(info({33, 22, 49}, 4).index, 2); // Mode 4
EXPECT_EQ(info({33, 22, 49}, 4).count, 7);
EXPECT_TRUE(info({33, 22, 49}, 4).id.empty());
EXPECT_EQ(info({33, 22, 49}, 5).index, 2); // Mode 5
EXPECT_EQ(info({33, 22, 49}, 5).count, 7);
EXPECT_TRUE(info({33, 22, 49}, 5).id.empty());
EXPECT_EQ(info({33, 22, 49}, 6).index, 2); // Mode 6
EXPECT_EQ(info({33, 22, 49}, 6).count, 7);
EXPECT_TRUE(info({33, 22, 49}, 6).id.empty());
// Various
EXPECT_EQ(info({33, 007, 49}, 2).index, 0); // Mode 2
EXPECT_EQ(info({33, 007, 49}, 2).count, 8);
EXPECT_EQ(info({33, 007, 49}, 4).index, 0); // Mode 4
EXPECT_EQ(info({33, 007, 49}, 4).count, 8);
EXPECT_EQ(info({33, 067, 49}, 2).index, 6); // Mode 2
EXPECT_EQ(info({33, 067, 49}, 2).count, 8);
EXPECT_EQ(info({33, 067, 49}, 4).index, 6); // Mode 4
EXPECT_EQ(info({33, 067, 49}, 4).count, 8);
EXPECT_EQ(info({33, 077, 49}, 2).index, 7); // Mode 2
EXPECT_EQ(info({33, 077, 49}, 2).count, 8);
EXPECT_EQ(info({33, 077, 49}, 4).index, 7); // Mode 4
EXPECT_EQ(info({33, 077, 49}, 4).count, 8);
EXPECT_EQ(info({33, 001, 49}, 2).index, 0); // Mode 2
EXPECT_EQ(info({33, 001, 49}, 2).count, 2);
EXPECT_EQ(info({33, 001, 49}, 4).index, 0); // Mode 4
EXPECT_EQ(info({33, 001, 49}, 4).count, 2);
EXPECT_EQ(info({33, 011, 49}, 2).index, 1); // Mode 2
EXPECT_EQ(info({33, 011, 49}, 2).count, 2);
EXPECT_EQ(info({33, 011, 49}, 4).index, 1); // Mode 4
EXPECT_EQ(info({33, 011, 49}, 4).count, 2);
// Invalid
EXPECT_EQ(info({33, 000, 49}, 2).index, 0); // Mode 2
EXPECT_EQ(info({33, 000, 49}, 2).count, 0); // Count 1 set to 0
EXPECT_EQ(info({33, 000, 49}, 4).index, 0); // Mode 4
EXPECT_EQ(info({33, 000, 49}, 4).count, 0);
EXPECT_EQ(info({33, 032, 49}, 2).index, 3); // Mode 2
EXPECT_EQ(info({33, 032, 49}, 2).count, 0); // Count 3 <= index 3 so set to 0
EXPECT_EQ(info({33, 032, 49}, 4).index, 3); // Mode 4
EXPECT_EQ(info({33, 032, 49}, 4).count, 0);
}
TEST(MCDecoderTest, ReaderInit)
{
// Null
EXPECT_FALSE(parse({49}, 2).readerInit()); // Mode 2
EXPECT_TRUE(parse({49}, 2).isValid());
// Set
EXPECT_TRUE(parse({49}, 6).readerInit()); // Mode 6
EXPECT_TRUE(parse({49}, 6).isValid());
}
TEST(MCDecoderTest, Mode2)
{
// Good data
{
// Postcode 1234, Postcode Length 4, Country 999, Class 999
ByteArray mode2 = { 34, 52, 4, 0, 0, 0, 49, 57, 31, 62 };
EXPECT_EQ(parse({49}, 2, &mode2).content().utf8(), "1234\035999\035999\0351");
}
{
// Postcode 0123, Postcode Length 4, Country 999, Class 999
ByteArray mode2 = { 50, 30, 0, 0, 0, 0, 49, 57, 31, 62 };
EXPECT_EQ(parse({49}, 2, &mode2).content().utf8(), "0123\035999\035999\0351");
}
// Dodgy data (postcode length mismatch)
{
// Postcode 123456789, Postcode Length 4, Country 999, Class 999
ByteArray mode2 = { 18, 5, 13, 47, 53, 1, 49, 57, 31, 62 };
EXPECT_EQ(parse({49}, 2, &mode2).content().utf8(), "1234\035999\035999\0351"); // Postcode truncated
}
{
// Postcode 123, Postcode Length 4, Country 999, Class 999
ByteArray mode2 = { 50, 30, 0, 0, 0, 0, 49, 57, 31, 62 };
EXPECT_EQ(parse({49}, 2, &mode2).content().utf8(), "0123\035999\035999\0351"); // Postcode zero-filled to len 4
}
// Out-of-range data
{
// Postcode 1, Postcode Length 10, Country 999, Class 999
ByteArray mode2 = { 18, 0, 0, 0, 0, 32, 50, 57, 31, 62 };
EXPECT_EQ(parse({49}, 2, &mode2).content().utf8(), "000000001\035999\035999\0351"); // Postcode capped to len 9 & zero-filled
}
{
// Postcode 1073741823 (0x3FFFFFFF, 30-bit max), Postcode Length 10, Country 999, Class 999
ByteArray mode2 = { 50, 63, 63, 63, 63, 47, 50, 57, 31, 62 };
EXPECT_EQ(parse({49}, 2, &mode2).content().utf8(), "107374182\035999\035999\0351"); // Postcode truncated
}
{
// Postcode 12345, Postcode Length 5, Country 1023 (0x3FF, 10-bit max), Class 999
ByteArray mode2 = { 18, 14, 48, 0, 0, 16, 49, 63, 31, 62 };
EXPECT_EQ(parse({49}, 2, &mode2).content().utf8(), "12345\035999\035999\0351"); // Country capped to 999
}
{
// Postcode 123456, Postcode Length 8, Country 999, Class 1000 (0x3E8)
ByteArray mode2 = { 2, 16, 34, 7, 0, 0, 50, 57, 35, 62 };
EXPECT_EQ(parse({49}, 2, &mode2).content().utf8(), "00123456\035999\035999\0351"); // Class capped to 999
}
}
```
|
/content/code_sandbox/test/unit/maxicode/MCDecoderTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 2,765
|
```c++
/*
*/
#include "oned/ODCode39Writer.h"
#include "BitMatrixIO.h"
#include "gtest/gtest.h"
using namespace ZXing;
using namespace ZXing::OneD;
namespace {
std::string Encode(const std::wstring& input)
{
auto result = ToString(Code39Writer().encode(input, 0, 0), '1', '0', false);
return result.substr(0, result.size() - 1); // remove the \n at the end
}
}
TEST(ODCode39WriterTest, Encode)
{
EXPECT_EQ(Encode(L"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"),
your_sha256_hash01011011010110010101"
your_sha256_hash11010101001101011010"
your_sha256_hash11001101101010110010"
your_sha256_hash01001011010110110010"
your_sha256_hash00101010101001101011"
your_sha256_hash1010010110110100000");
}
TEST(ODCode39WriterTest, EncodeExtended)
{
EXPECT_EQ(Encode(std::wstring(L"\x0\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f", 0x20)),
your_sha256_hash01011010010010010101"
your_sha256_hash10010010010101101011"
your_sha256_hash10010101101010011010"
your_sha256_hash01101010100110100100"
your_sha256_hash10100110100100100101"
your_sha256_hash10100100100101011010"
your_sha256_hash00100101011001010101"
your_sha256_hash01010010110101101001"
your_sha256_hash10100101101010010010"
your_sha256_hash01101010010010010110"
"101100101010010110110100000");
EXPECT_EQ(Encode(L" !\"#$%&'()*+,-./0123456789:;<=>?"),
your_sha256_hash01001010110100101101"
your_sha256_hash11010110010101001001"
your_sha256_hash00110101001001010010"
your_sha256_hash01001001010010101101"
your_sha256_hash11011010110100101011"
your_sha256_hash10101001011011011010"
your_sha256_hash01100101010100100100"
your_sha256_hash01010100100100101010"
"11001101010010110110100000");
EXPECT_EQ(Encode(L"@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_"),
your_sha256_hash010110110110100101010"
your_sha256_hash01101001101010101100"
your_sha256_hash01001010110110100101"
your_sha256_hash10011010101101100110"
your_sha256_hash01001101010010010010"
your_sha256_hash01010010010010110101"
"101001010010110110100000");
EXPECT_EQ(Encode(L"`abcdefghijklmnopqrstuvwxyz{|}~"),
your_sha256_hash01011010010100100101"
your_sha256_hash10010100100101101011"
your_sha256_hash00100101101010011010"
your_sha256_hash01101010100110100101"
your_sha256_hash10100110100101001001"
your_sha256_hash10100101001001011010"
your_sha256_hash01001001011001010101"
your_sha256_hash01010010110101101001"
your_sha256_hash10110100101010010010"
your_sha256_hash00101010010010010101"
"011011001010010110110100000");
}
```
|
/content/code_sandbox/test/unit/oned/ODCode39WriterTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 883
|
```c++
/*
*/
#include "oned/ODUPCAWriter.h"
#include "BitMatrixIO.h"
#include "gtest/gtest.h"
using namespace ZXing;
using namespace ZXing::OneD;
namespace {
std::string Encode(const std::string& input)
{
auto result = ToString(UPCAWriter().encode(input, 0, 0), '1', '0', false);
return result.substr(0, result.size() - 1); // remove the \n at the end
}
}
TEST(ODUPCAWriterTest, Encode1)
{
std::string toEncode = "485963095124";
std::string expected = your_sha256_hash0100100111011001101101100101110010100000";
EXPECT_EQ(Encode(toEncode), expected);
}
TEST(ODUPCAWriterTest, AddChecksumAndEncode)
{
std::string toEncode = "12345678901";
std::string expected = your_sha256_hash1000111010011100101100110110110010100000";
EXPECT_EQ(Encode(toEncode), expected);
}
```
|
/content/code_sandbox/test/unit/oned/ODUPCAWriterTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 226
|
```c++
/*
*/
#include "oned/ODEAN13Writer.h"
#include "BitMatrixIO.h"
#include "gtest/gtest.h"
#include <stdexcept>
using namespace ZXing;
using namespace ZXing::OneD;
namespace {
std::string Encode(const std::string& input)
{
auto result = ToString(EAN13Writer().encode(input, 0, 0), '1', '0', false);
return result.substr(0, result.size() - 1); // remove the \n at the end
}
}
TEST(ODEAN13WriterTest, Encode1)
{
std::string toEncode = "5901234123457";
std::string expected = your_sha256_hash1100100001010111001001110100010010100000";
EXPECT_EQ(Encode(toEncode), expected);
}
TEST(ODEAN13WriterTest, AddChecksumAndEncode)
{
std::string toEncode = "590123412345";
std::string expected = your_sha256_hash1100100001010111001001110100010010100000";
EXPECT_EQ(Encode(toEncode), expected);
}
TEST(ODEAN13WriterTest, EncodeIllegalCharacters)
{
EXPECT_THROW({ Encode("5901234123abc"); }, std::invalid_argument);
}
```
|
/content/code_sandbox/test/unit/oned/ODEAN13WriterTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 262
|
```c++
/*
*/
#include "oned/ODCode128Writer.h"
#include "BitMatrixIO.h"
#include "ReaderOptions.h"
#include "Barcode.h"
#include "oned/ODCode128Reader.h"
#include "gtest/gtest.h"
using namespace ZXing;
using namespace ZXing::OneD;
static const std::string FNC1 = "11110101110";
static const std::string FNC2 = "11110101000";
static const std::string FNC3 = "10111100010";
static const std::string FNC4A = "11101011110";
static const std::string FNC4B = "10111101110";
static const std::string START_CODE_A = "11010000100";
static const std::string START_CODE_B = "11010010000";
static const std::string START_CODE_C = "11010011100";
static const std::string SWITCH_CODE_A = "11101011110";
static const std::string SWITCH_CODE_B = "10111101110";
static const std::string QUIET_SPACE = "00000";
static const std::string STOP = "1100011101011";
static const std::string LF = "10000110010";
static std::string LineMatrixToString(const BitMatrix& matrix)
{
auto result = ToString(matrix, '1', '0', false);
return result.substr(0, result.size() - 1);
}
static ZXing::Barcode Decode(const BitMatrix &matrix)
{
ReaderOptions opts;
return DecodeSingleRow(Code128Reader(opts), matrix.row(0));
}
TEST(ODCode128Writer, EncodeWithFunc1)
{
auto toEncode = L"\u00f1123";
// "12" "3" check digit 92
auto expected = QUIET_SPACE + START_CODE_C + FNC1 + "10110011100" + SWITCH_CODE_B + "11001011100" + "10101111000" + STOP + QUIET_SPACE;
auto actual = LineMatrixToString(Code128Writer().encode(toEncode, 0, 0));
EXPECT_EQ(actual, expected);
}
TEST(ODCode128Writer, EncodeWithFunc2)
{
auto toEncode = L"\u00f2123";
// "1" "2" "3" check digit 56
auto expected = QUIET_SPACE + START_CODE_B + FNC2 + "10011100110" + "11001110010" + "11001011100" + "11100010110" + STOP + QUIET_SPACE;
auto actual = LineMatrixToString(Code128Writer().encode(toEncode, 0, 0));
EXPECT_EQ(actual, expected);
}
TEST(ODCode128Writer, EncodeWithFunc3)
{
auto toEncode = L"\u00f3123";
// "1" "2" "3" check digit 51
auto expected = QUIET_SPACE + START_CODE_B + FNC3 + "10011100110" + "11001110010" + "11001011100" + "11101000110" + STOP + QUIET_SPACE;
auto actual = LineMatrixToString(Code128Writer().encode(toEncode, 0, 0));
EXPECT_EQ(actual, expected);
}
TEST(ODCode128Writer, EncodeWithFunc4)
{
auto toEncode = L"\u00f4123";
// "1" "2" "3" check digit 59
auto expected = QUIET_SPACE + START_CODE_B + FNC4B + "10011100110" + "11001110010" + "11001011100" + "11100011010" + STOP + QUIET_SPACE;
auto actual = LineMatrixToString(Code128Writer().encode(toEncode, 0, 0));
EXPECT_EQ(actual, expected);
}
TEST(ODCode128Writer, EncodeWithFncsAndNumberInCodesetA)
{
auto toEncode = L"\n\u00f1\u00f41\n";
auto expected = QUIET_SPACE + START_CODE_A + LF + FNC1 + FNC4A + "10011100110" + LF + "10101111000" + STOP + QUIET_SPACE;
auto actual = LineMatrixToString(Code128Writer().encode(toEncode, 0, 0));
EXPECT_EQ(actual, expected);
}
TEST(ODCode128Writer, RoundtripGS1)
{
auto toEncode = L"\u00f110958\u00f117160526";
auto decResult = Decode(Code128Writer().encode(toEncode, 0, 0));
EXPECT_EQ(decResult.text(TextMode::HRI), "(10)958(17)160526");
EXPECT_EQ(decResult.symbologyIdentifier(), "]C1");
}
TEST(ODCode128Writer, RoundtripFNC1)
{
auto toEncode = L"1\u00f10958\u00f117160526";
auto encResult = Code128Writer().encode(toEncode, 0, 0);
auto decResult = Decode(encResult);
EXPECT_EQ(decResult.bytes().asString(), "1\u001D0958\u001D17160526");
EXPECT_EQ(decResult.symbologyIdentifier(), "]C0");
}
TEST(ODCode128Writer, EncodeSwitchCodesetFromAToB)
{
// start with A switch to B and back to A
auto toEncode = std::string("\0ABab\u0010", 6);
// "\0" "A" "B" Switch to B "a" "b" Switch to A "\u0010" check digit
auto expected = QUIET_SPACE + START_CODE_A + "10100001100" + "10100011000" + "10001011000" + SWITCH_CODE_B + "10010110000" + "10010000110" + SWITCH_CODE_A + "10100111100" + "11001110100" + STOP + QUIET_SPACE;
auto encoded = Code128Writer().encode(toEncode, 0, 0);
auto actual = LineMatrixToString(encoded);
EXPECT_EQ(actual, expected);
auto actualRoundTrip = Decode(encoded).text(TextMode::Plain);
EXPECT_EQ(actualRoundTrip, toEncode);
}
TEST(ODCode128Writer, EncodeSwitchCodesetFromBToA)
{
// start with B switch to A and back to B
auto toEncode = std::string("ab\0ab", 5);
// "a" "b" Switch to A "\0 "Switch to B" "a" "b" check digit
auto expected = QUIET_SPACE + START_CODE_B + "10010110000" + "10010000110" + SWITCH_CODE_A + "10100001100" + SWITCH_CODE_B + "10010110000" + "10010000110" + "11010001110" + STOP + QUIET_SPACE;
auto encoded = Code128Writer().encode(toEncode, 0, 0);
auto actual = LineMatrixToString(encoded);
EXPECT_EQ(actual, expected);
auto actualRoundTrip = Decode(encoded).text(TextMode::Plain);
EXPECT_EQ(actualRoundTrip, toEncode);
}
```
|
/content/code_sandbox/test/unit/oned/ODCode128WriterTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 1,513
|
```c++
/*
*/
#include "oned/ODCode93Writer.h"
#include "BitMatrixIO.h"
#include "gtest/gtest.h"
namespace ZXing { namespace OneD {
std::string Code93ConvertToExtended(const std::wstring& contents);
}}
using namespace ZXing;
using namespace ZXing::OneD;
namespace {
std::string Encode(const std::wstring& input)
{
auto result = ToString(Code93Writer().encode(input, 0, 0), '1', '0', false);
return result.substr(0, result.size() - 1); // remove the \n at the end
}
}
TEST(ODCode93WriterTest, Encode)
{
EXPECT_EQ(Encode(L"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"),
your_sha256_hash10101011010001011001"
your_sha256_hash01000101101101101001"
your_sha256_hash01101101001110101000"
your_sha256_hash00001000100101000010"
"10100111010101000010101011110100000");
}
TEST(ODCode93WriterTest, EncodeExtended)
{
auto encoded = Encode(std::wstring(L"\x00\x01\x1a\x1b\x1f $%+!,09:;@AZ[_`az{\x7f", 25));
auto expected =
"00000" "101011110"
"111011010" "110010110" "100100110" "110101000" // bU aA
"100100110" "100111010" "111011010" "110101000" // aZ bA
"111011010" "110010010" "111010010" "111001010" // bE space $
"110101110" "101110110" "111010110" "110101000" // % + cA
"111010110" "101011000" "100010100" "100001010" // cL 0 9
"111010110" "100111010" "111011010" "110001010" // cZ bF
"111011010" "110011010" "110101000" "100111010" // bV A Z
"111011010" "100011010" "111011010" "100101100" // bK bO
"111011010" "101101100" "100110010" "110101000" // bW dA
"100110010" "100111010" "111011010" "100010110" // dZ bP
"111011010" "110100110" // bT
"110100010" "110101100" // checksum: 12 28
"101011110" "100000";
EXPECT_EQ(encoded, expected);
}
TEST(ODCode93WriterTest, ConvertToExtended)
{
// non-extended chars are not changed.
std::string src = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%";
std::string dst = Code93ConvertToExtended(std::wstring(src.begin(), src.end()));
EXPECT_EQ(src, dst);
}
```
|
/content/code_sandbox/test/unit/oned/ODCode93WriterTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 701
|
```c++
/*
*/
#include "oned/ODCode39Reader.h"
#include "ReaderOptions.h"
#include "Barcode.h"
#include "gtest/gtest.h"
using namespace ZXing;
using namespace ZXing::OneD;
// Helper to call decodePattern()
static Barcode parse(PatternRow row, ReaderOptions opts = {})
{
Code39Reader reader(opts);
row.insert(row.begin(), { 0, 1, 2, 1, 1, 2, 1, 2, 1, 1, 0 });
row.insert(row.end(), { 0, 1, 2, 1, 1, 2, 1, 2, 1, 1, 0 });
std::unique_ptr<RowReader::DecodingState> state;
PatternView next(row);
return reader.decodePattern(0, next, state);
}
TEST(ODCode39ReaderTest, SymbologyIdentifier)
{
{
// Plain "A"
PatternRow row({ 2, 1, 1, 1, 1, 2, 1, 1, 2 });
auto result = parse(row);
EXPECT_EQ(result.symbologyIdentifier(), "]A0");
EXPECT_EQ(result.text(), "A");
}
{
// "A" with checksum
PatternRow row({ 2, 1, 1, 1, 1, 2, 1, 1, 2, 0, 2, 1, 1, 1, 1, 2, 1, 1, 2 });
auto result = parse(row);
EXPECT_EQ(result.symbologyIdentifier(), "]A1");
EXPECT_EQ(result.text(), "AA");
}
{
// Extended "a"
PatternRow row({ 1, 2, 1, 1, 1, 2, 1, 2, 1, 0, 2, 1, 1, 1, 1, 2, 1, 1, 2 });
auto result = parse(row);
EXPECT_EQ(result.symbologyIdentifier(), "]A4");
EXPECT_EQ(result.text(), "a");
}
{
// Extended "a" with checksum
PatternRow row({ 1, 2, 1, 1, 1, 2, 1, 2, 1, 0, 2, 1, 1, 1, 1, 2, 1, 1, 2, 0, 2, 1, 1, 2, 1, 1, 2, 1, 1 });
auto result = parse(row);
EXPECT_EQ(result.symbologyIdentifier(), "]A5");
EXPECT_EQ(result.text(), "a8");
}
}
```
|
/content/code_sandbox/test/unit/oned/ODCode39ReaderTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 613
|
```c++
/*
*/
#include "oned/ODDataBarReader.h"
#include "ReaderOptions.h"
#include "Barcode.h"
#include "gtest/gtest.h"
using namespace ZXing;
using namespace ZXing::OneD;
// Helper to call decodePattern()
static Barcode parse(PatternRow row, ReaderOptions opts = {})
{
DataBarReader reader(opts);
row.insert(row.begin(), { 1, 1 }); // Left guard
row.insert(row.end(), { 1, 1 }); // Right guard
std::unique_ptr<RowReader::DecodingState> state;
PatternView next(row);
return reader.decodePattern(0, next, state);
}
TEST(ODDataBarReaderTest, Composite)
{
{
// With 2D linkage flag (GS1 Composite) in checksum
PatternRow row = { 2, 3, 1, 2, 1, 2, 4, 1, 3, 3, 7, 1, 1, 3, 1, 2, 1, 1, 1, 4, 2, 4, 1, 1, 2, 3, 1, 1, 2, 1, 1, 2, 8, 3, 3, 2, 2, 1, 4, 1, 1, 2 };
auto result = parse(row);
EXPECT_TRUE(result.isValid());
EXPECT_EQ(result.text(), "01234567890128");
}
}
```
|
/content/code_sandbox/test/unit/oned/ODDataBarReaderTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 326
|
```c++
/*
*/
#include "oned/ODCode93Reader.h"
#include "BitArray.h"
#include "BitArrayUtility.h"
#include "ReaderOptions.h"
#include "Barcode.h"
#include "gtest/gtest.h"
using namespace ZXing;
using namespace ZXing::OneD;
static std::string Decode(std::string_view input)
{
ReaderOptions opts;
auto row = Utility::ParseBitArray(input, '1');
auto result = DecodeSingleRow(Code93Reader(opts), row.range());
return result.text(TextMode::Plain);
}
TEST(ODCode93ReaderTest, Decode)
{
auto expected = std::string("Code93!\n$%/+ :\x1b;[{\x7f\x00@`\x7f\x7f\x7f", 25);
auto decoded = Decode(
your_sha256_hash1001011001001010"
your_sha256_hash1011101011011101"
your_sha256_hash0001010111011010"
your_sha256_hash1101101011001101"
your_sha256_hash1001110101001100"
"10110101000101011110100000");
EXPECT_EQ(expected, decoded);
}
```
|
/content/code_sandbox/test/unit/oned/ODCode93ReaderTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 252
|
```c++
/*
*/
#include "oned/ODCodabarWriter.h"
#include "BitMatrixIO.h"
#include "ReaderOptions.h"
#include "Barcode.h"
#include "oned/ODCodabarReader.h"
#include "gtest/gtest.h"
#include <stdexcept>
using namespace ZXing;
using namespace ZXing::OneD;
namespace {
std::string Encode(const std::string& input)
{
auto result = ToString(CodabarWriter().encode(input, 0, 0), '1', '0', false);
return result.substr(0, result.size() - 1); // remove the \n at the end
}
}
TEST(ODCodaBarWriterTest, Encode)
{
EXPECT_EQ(Encode("B515-3/B"),
"00000"
"1001001011" "0110101001" "0101011001" "0110101001" "0101001101"
"0110010101" "01101101011" "01001001011"
"00000");
}
TEST(ODCodaBarWriterTest, Encode2)
{
EXPECT_EQ(Encode("T123T"),
"00000"
"1011001001" "0101011001" "0101001011" "0110010101" "01011001001"
"00000");
}
TEST(ODCodaBarWriterTest, AltStartEnd)
{
EXPECT_EQ(Encode("T123456789-$T"), Encode("A123456789-$A"));
}
TEST(ODCodaBarWriterTest, FullCircle)
{
std::string text = "A0123456789-$:/.+A";
auto matrix = CodabarWriter().encode(text, 0, 0);
auto opts = ReaderOptions();
auto res = OneD::DecodeSingleRow(CodabarReader(opts), matrix.row(0));
EXPECT_EQ(text, res.text());
}
TEST(ODCodaBarWriterTest, InvalidChars)
{
EXPECT_THROW({Encode("AxA");}, std::invalid_argument );
EXPECT_THROW({Encode("a0a");}, std::invalid_argument );
}
```
|
/content/code_sandbox/test/unit/oned/ODCodaBarWriterTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 440
|
```c++
/*
*/
#include "oned/ODEAN8Writer.h"
#include "BitMatrixIO.h"
#include "gtest/gtest.h"
using namespace ZXing;
using namespace ZXing::OneD;
namespace {
std::string Encode(const std::string& input)
{
auto result = ToString(EAN8Writer().encode(input, 0, 0), '1', '0', false);
return result.substr(0, result.size() - 1); // remove the \n at the end
}
}
TEST(ODEAN8WriterTest, Encode1)
{
std::string toEncode = "96385074";
std::string expected = your_sha256_hash110010100000";
EXPECT_EQ(Encode(toEncode), expected);
}
TEST(ODEAN8WriterTest, AddChecksumAndEncode)
{
std::string toEncode = "9638507";
std::string expected = your_sha256_hash110010100000";
EXPECT_EQ(Encode(toEncode), expected);
}
TEST(ODEAN8WriterTest, EncodeIllegalCharacters)
{
EXPECT_THROW({ Encode("96385abc"); }, std::invalid_argument);
}
```
|
/content/code_sandbox/test/unit/oned/ODEAN8WriterTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 233
|
```c++
/*
*/
#include "oned/ODITFWriter.h"
#include "BitMatrixIO.h"
#include "gtest/gtest.h"
#include <stdexcept>
using namespace ZXing;
using namespace ZXing::OneD;
namespace {
std::string Encode(const std::wstring& input)
{
auto result = ToString(ITFWriter().encode(input, 0, 0), '1', '0', false);
return result.substr(0, result.size() - 1); // remove the \n at the end
}
}
TEST(ODITFWriterTest, Encode)
{
EXPECT_EQ(Encode(L"00123456789012"),
your_sha256_hash110100011"
your_sha256_hash10100000");
}
TEST(ODITFWriterTest, EncodeIllegalCharacters)
{
EXPECT_THROW({ Encode(L"00123456789abc"); }, std::invalid_argument);
}
```
|
/content/code_sandbox/test/unit/oned/ODITFWriterTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 185
|
```c++
/*
*/
#include "BitArray.h"
#include "BitArrayUtility.h"
#include "ReaderOptions.h"
#include "Barcode.h"
#include "oned/ODCode39Reader.h"
#include "gtest/gtest.h"
using namespace ZXing;
using namespace ZXing::OneD;
static std::string Decode(std::string_view encoded)
{
auto opts = ReaderOptions();
BitArray row = Utility::ParseBitArray(encoded, '1');
auto result = DecodeSingleRow(Code39Reader(opts), row.range());
return result.text(TextMode::Plain);
}
TEST(ODCode39FullASCIITest, Decode)
{
EXPECT_EQ(Decode(
your_sha256_hash0101101001001001"
your_sha256_hash0110100100100101"
your_sha256_hash1010010010010101"
your_sha256_hash1001001001010110"
your_sha256_hash0100100101010101"
your_sha256_hash0010010101010101"
your_sha256_hash1001010101011011"
your_sha256_hash0101011001101010"
your_sha256_hash0101001101101010"
your_sha256_hash0110110100101010"
your_sha256_hash000"),
std::string("\x0\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f", 0x20));
EXPECT_EQ(Decode(
your_sha256_hash0100101011010010"
your_sha256_hash0010110101100101"
your_sha256_hash1011010100110101"
your_sha256_hash1101010100110100"
your_sha256_hash0101101001010100"
your_sha256_hash0011010101011001"
your_sha256_hash1101010101001001"
your_sha256_hash1101010100100100"
"1010110100110101010010010010101011001101010010110110100000"),
" !\"#$%&'()*+,-./0123456789:;<=>?");
EXPECT_EQ(Decode(
your_sha256_hash1011011011010010"
your_sha256_hash0101011010011010"
your_sha256_hash0110101101001010"
your_sha256_hash1001010101101001"
your_sha256_hash0010010010110101"
your_sha256_hash1001001010101101"
"001101010010010010110101101001010010110110100000"),
"@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_");
EXPECT_EQ(Decode(
your_sha256_hash0101101001010010"
your_sha256_hash0110100101001001"
your_sha256_hash1010010100100101"
your_sha256_hash1001010010010110"
your_sha256_hash0101001001010101"
your_sha256_hash0100100101010101"
your_sha256_hash0010010101011011"
your_sha256_hash1001011001101010"
your_sha256_hash0101001101101010"
your_sha256_hash0110101011001010"
your_sha256_hash000"),
"`abcdefghijklmnopqrstuvwxyz{|}~");
}
```
|
/content/code_sandbox/test/unit/oned/ODCode39ExtendedModeTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 764
|
```c++
/*
*/
#include "CharacterSet.h"
#include "pdf417/PDFCompaction.h"
#include "pdf417/PDFHighLevelEncoder.h"
#include "gtest/gtest.h"
using namespace ZXing;
using namespace ZXing::Pdf417;
TEST(PDF417HighLevelEncoderTest, EncodeAuto)
{
auto encoded = HighLevelEncoder::EncodeHighLevel(L"ABCD", Compaction::AUTO, CharacterSet::UTF8);
EXPECT_EQ(encoded, std::vector<int>({ 0x39f, 0x1A, 0x385, 'A', 'B', 'C', 'D' }));
}
TEST(PDF417HighLevelEncoderTest, EncodeAutoWithSpecialChars)
{
//Just check if this does not throw an exception
HighLevelEncoder::EncodeHighLevel(L"1%\xA7""s ?aG$", Compaction::AUTO, CharacterSet::UTF8);
}
TEST(PDF417HighLevelEncoderTest, EncodeIso88591WithSpecialChars)
{
// Just check if this does not throw an exception
HighLevelEncoder::EncodeHighLevel(L"asdfg\xA7""asd", Compaction::AUTO, CharacterSet::ISO8859_1);
}
TEST(PDF417HighLevelEncoderTest, EncodeText)
{
auto encoded = HighLevelEncoder::EncodeHighLevel(L"ABCD", Compaction::TEXT, CharacterSet::UTF8);
EXPECT_EQ(encoded, std::vector<int>({ 0x39f, 0x1a, 1, '?' }));
}
TEST(PDF417HighLevelEncoderTest, EncodeNumeric)
{
auto encoded = HighLevelEncoder::EncodeHighLevel(L"1234", Compaction::NUMERIC, CharacterSet::UTF8);
EXPECT_EQ(encoded, std::vector<int>({ 0x39f, 0x1a, 0x386, '\f', 0x1b2 }));
}
TEST(PDF417HighLevelEncoderTest, EncodeByte)
{
auto encoded = HighLevelEncoder::EncodeHighLevel(L"abcd", Compaction::BYTE, CharacterSet::UTF8);
EXPECT_EQ(encoded, std::vector<int>({ 0x39f, 0x1a, 0x385, 'a', 'b', 'c', 'd' }));
}
TEST(PDF417HighLevelEncoderTest, EncodeByteBINARYECI)
{
auto encoded = HighLevelEncoder::EncodeHighLevel(L"\u00E9", Compaction::BYTE, CharacterSet::BINARY);
EXPECT_EQ(encoded, std::vector<int>({ 927, 899, 901, 0xe9 }));
}
TEST(PDF417HighLevelEncoderTest, EncodeByteUnknown)
{
EXPECT_THROW(HighLevelEncoder::EncodeHighLevel(L"\u00E9", Compaction::BYTE, CharacterSet::Unknown), std::invalid_argument);
}
```
|
/content/code_sandbox/test/unit/pdf417/PDF417HighLevelEncoderTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 587
|
```c++
/*
*/
#include "PseudoRandom.h"
#include "ZXAlgorithms.h"
#include "gtest/gtest.h"
namespace ZXing {
namespace Pdf417 {
bool DecodeErrorCorrection(std::vector<int>& received, int numECCodewords, const std::vector<int>& erasures, int& nbErrors);
}
}
using namespace ZXing;
using namespace ZXing::Pdf417;
static const int PDF417_TEST[] = {
48, 901, 56, 141, 627, 856, 330, 69, 244, 900, 852, 169, 843, 895, 852, 895, 913, 154, 845, 778, 387, 89, 869,
901, 219, 474, 543, 650, 169, 201, 9, 160, 35, 70, 900, 900, 900, 900, 900, 900, 900, 900, 900, 900, 900, 900,
900, 900 };
static const int PDF417_TEST_WITH_EC[] = {
48, 901, 56, 141, 627, 856, 330, 69, 244, 900, 852, 169, 843, 895, 852, 895, 913, 154, 845, 778, 387, 89, 869,
901, 219, 474, 543, 650, 169, 201, 9, 160, 35, 70, 900, 900, 900, 900, 900, 900, 900, 900, 900, 900, 900, 900,
900, 900, 769, 843, 591, 910, 605, 206, 706, 917, 371, 469, 79, 718, 47, 777, 249, 262, 193, 620, 597, 477, 450,
806, 908, 309, 153, 871, 686, 838, 185, 674, 68, 679, 691, 794, 497, 479, 234, 250, 496, 43, 347, 582, 882, 536,
322, 317, 273, 194, 917, 237, 420, 859, 340, 115, 222, 808, 866, 836, 417, 121, 833, 459, 64, 159 };
static const int ECC_BYTES = Size(PDF417_TEST_WITH_EC) - Size(PDF417_TEST);
static const int ERROR_LIMIT = ECC_BYTES;
static const int MAX_ERRORS = ERROR_LIMIT / 2;
static const int MAX_ERASURES = ERROR_LIMIT;
static void CheckDecode(std::vector<int>& received, const std::vector<int>& erasures)
{
int nbError = 0;
bool corrected = DecodeErrorCorrection(received, ECC_BYTES, erasures, nbError);
EXPECT_TRUE(corrected);
for (int i = 0; i < Size(PDF417_TEST); i++) {
EXPECT_EQ(received[i], PDF417_TEST[i]);
}
}
static void CheckDecode(std::vector<int>& received)
{
CheckDecode(received, std::vector<int>());
}
static void Corrupt(std::vector<int>& received, int howMany, PseudoRandom& random, int max)
{
std::vector<bool> corrupted(received.size(), false);
for (int j = 0; j < howMany; j++) {
int location = random.next(0, Size(received) - 1);
int value = random.next(0, max - 1);
if (corrupted[location] || received[location] == value) {
j--;
}
else {
corrupted[location] = true;
received[location] = value;
}
}
}
TEST(PDF417ErrorCorrectionTest, NoError)
{
std::vector<int> received(PDF417_TEST_WITH_EC, PDF417_TEST_WITH_EC + Size(PDF417_TEST_WITH_EC));
// no errors
CheckDecode(received);
}
TEST(PDF417ErrorCorrectionTest, OneError)
{
PseudoRandom random(0x12345678);
for (int i = 0; i < Size(PDF417_TEST_WITH_EC); i++) {
std::vector<int> received(PDF417_TEST_WITH_EC, PDF417_TEST_WITH_EC + Size(PDF417_TEST_WITH_EC));
received[i] = random.next(0, 255);
CheckDecode(received);
}
}
TEST(PDF417ErrorCorrectionTest, MaxErrors)
{
PseudoRandom random(0x12345678);
for (int testIterations = 0; testIterations < 100; testIterations++) { // # iterations is kind of arbitrary
std::vector<int> received(PDF417_TEST_WITH_EC, PDF417_TEST_WITH_EC + Size(PDF417_TEST_WITH_EC));
Corrupt(received, MAX_ERRORS, random, 929);
CheckDecode(received);
}
}
TEST(PDF417ErrorCorrectionTest, TooManyErrors)
{
std::vector<int> received(PDF417_TEST_WITH_EC, PDF417_TEST_WITH_EC + Size(PDF417_TEST_WITH_EC));
PseudoRandom random(0x12345678);
Corrupt(received, MAX_ERRORS + 1, random, 929);
int nbError = 0;
EXPECT_FALSE(DecodeErrorCorrection(received, ECC_BYTES, std::vector<int>(), nbError));
}
```
|
/content/code_sandbox/test/unit/pdf417/PDF417ErrorCorrectionTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 1,220
|
```c++
/*
*/
#include "DecoderResult.h"
#include "pdf417/PDFScanningDecoder.h"
#include "gtest/gtest.h"
using namespace ZXing;
using namespace ZXing::Pdf417;
// Shorthand for DecodeCodewords()
static DecoderResult decode(std::vector<int>& codewords)
{
std::vector<int> erasures;
auto result = DecodeCodewords(codewords, NumECCodeWords(0));
return result;
}
TEST(PDF417ScanningDecoderTest, BadSymbolLengthDescriptor)
{
{
std::vector<int> codewords = { 4, 1, 449, 394 }; // 4 should be 2
auto result = decode(codewords);
EXPECT_TRUE(result.isValid());
EXPECT_EQ(result.text(), L"AB");
EXPECT_EQ(codewords[0], 2);
}
{
std::vector<int> codewords = { 1, 1, 800, 351 }; // 1 should be 2
auto result = decode(codewords);
EXPECT_TRUE(result.isValid());
EXPECT_EQ(result.text(), L"AB");
EXPECT_EQ(codewords[0], 2);
}
{
std::vector<int> codewords = { 0, 1, 917, 27 }; // 0 should be 2
auto result = decode(codewords);
EXPECT_TRUE(result.isValid());
EXPECT_EQ(result.text(), L"AB");
EXPECT_EQ(codewords[0], 2);
}
}
```
|
/content/code_sandbox/test/unit/pdf417/PDF417ScanningDecoderTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 331
|
```c++
/*
*/
#include "BitMatrixIO.h"
#include "pdf417/PDFWriter.h"
#include "gtest/gtest.h"
using namespace ZXing;
using namespace ZXing::Pdf417;
TEST(PDF417WriterTest, DataMatrixImageWriter)
{
Writer writer;
writer.setMargin(0);
int size = 64;
BitMatrix matrix = writer.encode(L"Hello Google", size, size);
auto actual = ToString(matrix, 'X', ' ', true);
EXPECT_EQ(actual,
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n");
}
```
|
/content/code_sandbox/test/unit/pdf417/PDF417WriterTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 2,957
|
```c++
/*
*/
#include "aztec/AZHighLevelEncoder.h"
#include "BitArray.h"
#include "BitArrayUtility.h"
#include "DecoderResult.h"
#include "StructuredAppend.h"
#include "gtest/gtest.h"
#include <algorithm>
namespace ZXing::Aztec {
DecoderResult Decode(const BitArray& bits);
}
using namespace ZXing;
namespace {
std::string StripSpaces(std::string str) {
str.erase(std::remove_if(str.begin(), str.end(), isspace), str.end());
return str;
}
void TestHighLevelEncodeString(const std::string& s, const std::string& expectedBits) {
BitArray bits = Aztec::HighLevelEncoder::Encode(s);
EXPECT_EQ(Utility::ToString(bits), StripSpaces(expectedBits)) << "highLevelEncode() failed for input string: " + s;
EXPECT_EQ(ByteArray(s), Aztec::Decode(bits).content().bytes);
}
void TestHighLevelEncodeString(const std::string& s, int expectedReceivedBits) {
BitArray bits = Aztec::HighLevelEncoder::Encode(s);
int receivedBitCount = Size(Utility::ToString(bits));
EXPECT_EQ(receivedBitCount, expectedReceivedBits) << "highLevelEncode() failed for input string: " + s;
EXPECT_EQ(ByteArray(s), Aztec::Decode(bits).content().bytes);
}
}
TEST(AZHighLevelEncoderTest, HighLevelEncode)
{
TestHighLevelEncodeString("A. b.",
// 'A' P/S '. ' L/L b D/L '.'
"...X. ..... ...XX XXX.. ...XX XXXX. XX.X");
TestHighLevelEncodeString("Lorem ipsum.",
// 'L' L/L 'o' 'r' 'e' 'm' ' ' 'i' 'p' 's' 'u' 'm' D/L '.'
".XX.X XXX.. X.... X..XX ..XX. .XXX. ....X .X.X. X...X X.X.. X.XX. .XXX. XXXX. XX.X");
TestHighLevelEncodeString("Lo. Test 123.",
// 'L' L/L 'o' P/S '. ' U/S 'T' 'e' 's' 't' D/L ' ' '1' '2' '3' '.'
".XX.X XXX.. X.... ..... ...XX XXX.. X.X.X ..XX. X.X.. X.X.X XXXX. ...X ..XX .X.. .X.X XX.X");
TestHighLevelEncodeString("Lo...x",
// 'L' L/L 'o' D/L '.' '.' '.' U/L L/L 'x'
".XX.X XXX.. X.... XXXX. XX.X XX.X XX.X XXX. XXX.. XX..X");
TestHighLevelEncodeString(". x://abc/.",
//P/S '. ' L/L 'x' P/S ':' P/S '/' P/S '/' 'a' 'b' 'c' P/S '/' D/L '.'
"..... ...XX XXX.. XX..X ..... X.X.X ..... X.X.. ..... X.X.. ...X. ...XX ..X.. ..... X.X.. XXXX. XX.X");
// Uses Binary/Shift rather than Lower/Shift to save two bits.
TestHighLevelEncodeString("ABCdEFG",
//'A' 'B' 'C' B/S =1 'd' 'E' 'F' 'G'
"...X. ...XX ..X.. XXXXX ....X .XX..X.. ..XX. ..XXX .X...");
TestHighLevelEncodeString(
// Found on an airline boarding pass. Several stretches of Binary shift are
// necessary to keep the bitcount so low.
"09 UAG ^160MEUCIQC0sYS/HpKxnBELR1uB85R20OoqqwFGa0q2uEi"
"Ygh6utAIgLl1aBVM4EOTQtMQQYH9M2Z3Dp4qnA/fwWuQ+M8L3V8U=",
823);
}
TEST(AZHighLevelEncoderTest, HighLevelEncodeBinary)
{
// binary short form single byte
TestHighLevelEncodeString(std::string("N\0N", 3),
// 'N' B/S =1 '\0' N
".XXXX XXXXX ....X ........ .XXXX"); // Encode "N" in UPPER
TestHighLevelEncodeString(std::string("N\0n", 3),
// 'N' B/S =2 '\0' 'n'
".XXXX XXXXX ...X. ........ .XX.XXX."); // Encode "n" in BINARY
// binary short form consecutive bytes
TestHighLevelEncodeString(std::string("N\0\x80 A", 5),
// 'N' B/S =2 '\0' \u0080 ' ' 'A'
".XXXX XXXXX ...X. ........ X....... ....X ...X.");
// binary skipping over single character
TestHighLevelEncodeString(std::string("\0a\xff\x80 A", 6),
// B/S =4 '\0' 'a' '\3ff' '\200' ' ' 'A'
"XXXXX ..X.. ........ .XX....X XXXXXXXX X....... ....X ...X.");
// getting into binary mode from digit mode
TestHighLevelEncodeString(std::string("1234\0", 5),
//D/L '1' '2' '3' '4' U/L B/S =1 \0
"XXXX. ..XX .X.. .X.X .XX. XXX. XXXXX ....X ........"
);
// Create a string in which every character requires binary
std::string sb;
sb.reserve(3000);
for (int i = 0; i <= 3000; i++) {
sb.push_back((char)(128 + (i % 30)));
}
// Test the output generated by Binary/Switch, particularly near the
// places where the encoding changes: 31, 62, and 2047+31=2078
for (int i : { 1, 2, 3, 10, 29, 30, 31, 32, 33, 60, 61, 62, 63, 64, 2076, 2077, 2078, 2079, 2080, 2100 }) {
// This is the expected length of a binary string of length "i"
int expectedLength = (8 * i) +
((i <= 31) ? 10 : (i <= 62) ? 20 : (i <= 2078) ? 21 : 31);
// Verify that we are correct about the length.
TestHighLevelEncodeString(sb.substr(0, i), expectedLength);
if (i != 1 && i != 32 && i != 2079) {
// The addition of an 'a' at the beginning or end gets merged into the binary code
// in those cases where adding another binary character only adds 8 or 9 bits to the result.
// So we exclude the border cases i=1,32,2079
// A lower case letter at the beginning will be merged into binary mode
TestHighLevelEncodeString('a' + sb.substr(0, i - 1), expectedLength);
// A lower case letter at the end will also be merged into binary mode
TestHighLevelEncodeString(sb.substr(0, i - 1) + 'a', expectedLength);
}
// A lower case letter at both ends will enough to latch us into LOWER.
TestHighLevelEncodeString('a' + sb.substr(0, i) + 'b', expectedLength + 15);
}
sb.clear();
for (int i = 0; i < 32; i++) {
sb.push_back('\xA7'); // forces binary encoding
}
sb[1] = 'A';
// expect B/S(1) A B/S(30)
TestHighLevelEncodeString(sb, 5 + 20 + 31 * 8);
sb.clear();
for (int i = 0; i < 31; i++) {
sb.push_back('\xA7');
}
sb[1] = 'A';
// expect B/S(31)
TestHighLevelEncodeString(sb, 10 + 31 * 8);
sb.clear();
for (int i = 0; i < 34; i++) {
sb.push_back('\xA7');
}
sb[1] = 'A';
// expect B/S(31) B/S(3)
TestHighLevelEncodeString(sb, 20 + 34 * 8);
sb.clear();
for (int i = 0; i < 64; i++) {
sb.push_back('\xA7');
}
sb[30] = 'A';
// expect B/S(64)
TestHighLevelEncodeString(sb, 21 + 64 * 8);
}
TEST(AZHighLevelEncoderTest, HighLevelEncodePairs)
{
// Typical usage
TestHighLevelEncodeString("ABC. DEF\r\n",
// A B C P/S .<sp> D E F P/S \r\n
"...X. ...XX ..X.. ..... ...XX ..X.X ..XX. ..XXX ..... ...X.");
// We should latch to PUNCT mode, rather than shift. Also check all pairs
TestHighLevelEncodeString("A. : , \r\n",
// 'A' M/L P/L ". " ": " ", " "\r\n"
"...X. XXX.X XXXX. ...XX ..X.X ..X.. ...X.");
// Latch to DIGIT rather than shift to PUNCT
TestHighLevelEncodeString("A. 1234",
// 'A' D/L '.' ' ' '1' '2' '3' '4'
"...X. XXXX. XX.X ...X ..XX .X.. .X.X .X X."
);
// Don't bother leaving Binary Shift.
TestHighLevelEncodeString("A\200. \200",
// 'A' B/S =2 \200 "." " " \200
"...X. XXXXX ..X.. X....... ..X.XXX. ..X..... X.......");
}
```
|
/content/code_sandbox/test/unit/aztec/AZHighLevelEncoderTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 2,407
|
```c++
/*
*/
#include "DecoderResult.h"
#include "pdf417/PDFDecoder.h"
#include "pdf417/PDFDecoderResultExtra.h"
#include "gtest/gtest.h"
namespace ZXing::Pdf417 {
int DecodeMacroBlock(const std::vector<int>& codewords, int codeIndex, DecoderResultExtra& resultMetadata);
}
using namespace ZXing;
using namespace ZXing::Pdf417;
/**
* Tests the first sample given in ISO/IEC 15438:2015(E) - Annex H.4
*/
TEST(PDF417DecoderTest, StandardSample1)
{
std::vector<int> sampleCodes = { 20, 928, 111, 100, 17, 53, 923, 1, 111, 104, 923, 3, 64, 416, 34, 923, 4, 258, 446, 67,
// we should never reach these
1000, 1000, 1000 };
DecoderResultExtra resultMetadata;
DecodeMacroBlock(sampleCodes, 2, resultMetadata);
EXPECT_EQ(0, resultMetadata.segmentIndex());
EXPECT_EQ("017053", resultMetadata.fileId());
EXPECT_EQ(false, resultMetadata.isLastSegment());
EXPECT_EQ(4, resultMetadata.segmentCount());
EXPECT_EQ("CEN BE", resultMetadata.sender());
EXPECT_EQ("ISO CH", resultMetadata.addressee());
auto optionalData = resultMetadata.optionalData();
EXPECT_EQ(1, optionalData.front()) << "first element of optional array should be the first field identifier";
EXPECT_EQ(67, optionalData.back()) << "last element of optional array should be the last codeword of the last field";
auto result = Decode(sampleCodes);
EXPECT_EQ(0, result.structuredAppend().index);
EXPECT_EQ("017053", result.structuredAppend().id);
EXPECT_EQ(4, result.structuredAppend().count);
}
/**
* Tests the second given in ISO/IEC 15438:2015(E) - Annex H.4
*/
TEST(PDF417DecoderTest, StandardSample2)
{
std::vector<int> sampleCodes = { 11, 928, 111, 103, 17, 53, 923, 1, 111, 104, 922,
// we should never reach these
1000, 1000, 1000 };
DecoderResultExtra resultMetadata;
DecodeMacroBlock(sampleCodes, 2, resultMetadata);
EXPECT_EQ(3, resultMetadata.segmentIndex());
EXPECT_EQ("017053", resultMetadata.fileId());
EXPECT_EQ(true, resultMetadata.isLastSegment());
EXPECT_EQ(4, resultMetadata.segmentCount());
EXPECT_EQ("", resultMetadata.sender());
EXPECT_EQ("", resultMetadata.addressee());
auto optionalData = resultMetadata.optionalData();
EXPECT_EQ(1, optionalData.front()) << "first element of optional array should be the first field identifier";
EXPECT_EQ(104, optionalData.back()) << "last element of optional array should be the last codeword of the last field";
auto result = Decode(sampleCodes);
EXPECT_EQ(3, result.structuredAppend().index);
EXPECT_EQ("017053", result.structuredAppend().id);
EXPECT_EQ(4, result.structuredAppend().count);
}
/**
* Tests the example given in ISO/IEC 15438:2015(E) - Annex H.6
*/
TEST(PDF417DecoderTest, StandardSample3)
{
std::vector<int> sampleCodes = { 7, 928, 111, 100, 100, 200, 300 };
DecoderResultExtra resultMetadata;
DecodeMacroBlock(sampleCodes, 2, resultMetadata);
EXPECT_EQ(0, resultMetadata.segmentIndex());
EXPECT_EQ("100200300", resultMetadata.fileId());
EXPECT_EQ(-1, resultMetadata.segmentCount());
auto result = Decode(sampleCodes);
EXPECT_EQ(0, result.structuredAppend().index);
EXPECT_EQ("100200300", result.structuredAppend().id);
EXPECT_EQ(0, result.structuredAppend().count);
}
TEST(PDF417DecoderTest, SampleWithFilename)
{
std::vector<int> sampleCodes = { 23, 477, 928, 111, 100, 0, 252, 21, 86, 923, 0, 815, 251, 133, 12, 148, 537, 593,
599, 923, 1, 111, 102, 98, 311, 355, 522, 920, 779, 40, 628, 33, 749, 267, 506, 213, 928, 465, 248, 493, 72,
780, 699, 780, 493, 755, 84, 198, 628, 368, 156, 198, 809, 19, 113 };
DecoderResultExtra resultMetadata;
DecodeMacroBlock(sampleCodes, 3, resultMetadata);
EXPECT_EQ(0, resultMetadata.segmentIndex());
EXPECT_EQ("000252021086", resultMetadata.fileId());
EXPECT_EQ(false, resultMetadata.isLastSegment());
EXPECT_EQ(2, resultMetadata.segmentCount());
EXPECT_EQ("", resultMetadata.sender());
EXPECT_EQ("", resultMetadata.addressee());
EXPECT_EQ("filename.txt", resultMetadata.fileName());
auto result = Decode(sampleCodes);
EXPECT_EQ(0, result.structuredAppend().index);
EXPECT_EQ("000252021086", result.structuredAppend().id);
EXPECT_EQ(2, result.structuredAppend().count);
}
TEST(PDF417DecoderTest, SampleWithNumericValues)
{
std::vector<int> sampleCodes = { 25, 477, 928, 111, 100, 0, 252, 21, 86, 923, 2, 2, 0, 1, 0, 0, 0, 923, 5, 130,
923, 6, 1, 500, 13 };
DecoderResultExtra resultMetadata;
DecodeMacroBlock(sampleCodes, 3, resultMetadata);
EXPECT_EQ(0, resultMetadata.segmentIndex());
EXPECT_EQ("000252021086", resultMetadata.fileId());
EXPECT_EQ(false, resultMetadata.isLastSegment());
EXPECT_EQ(180980729000000L, resultMetadata.timestamp());
EXPECT_EQ(30, resultMetadata.fileSize());
EXPECT_EQ(260013, resultMetadata.checksum());
EXPECT_EQ(-1, resultMetadata.segmentCount());
auto result = Decode(sampleCodes);
EXPECT_EQ(0, result.structuredAppend().index);
EXPECT_EQ("000252021086", result.structuredAppend().id);
EXPECT_EQ(0, result.structuredAppend().count);
}
TEST(PDF417DecoderTest, SampleWithMacroTerminatorOnly)
{
std::vector<int> sampleCodes = { 7, 477, 928, 222, 198, 0, 922 };
DecoderResultExtra resultMetadata;
DecodeMacroBlock(sampleCodes, 3, resultMetadata);
EXPECT_EQ(99998, resultMetadata.segmentIndex());
EXPECT_EQ("000", resultMetadata.fileId());
EXPECT_EQ(true, resultMetadata.isLastSegment());
EXPECT_EQ(-1, resultMetadata.segmentCount());
auto result = Decode(sampleCodes);
EXPECT_EQ(99998, result.structuredAppend().index);
EXPECT_EQ("000", result.structuredAppend().id);
EXPECT_EQ(99999, result.structuredAppend().count);
}
// Shorthand to decode and return text
static std::wstring decode(const std::vector<int>& codewords)
{
return Decode(codewords).text();
}
// Shorthand to decode and return isValid
static bool valid(const std::vector<int>& codewords)
{
return Decode(codewords).isValid();
}
TEST(PDF417DecoderTest, TextCompactionSimple)
{
// ISO/IEC 15438:2015 Figure 1
EXPECT_EQ(decode({ 16, 453, 178, 121, 236, 858, 834, 361, 431, 426, 746, 828, 570, 393, 17, 119 }),
L"PDF417 Symbology Standard");
EXPECT_EQ(decode({ 16, 453, 178, 121, 237, 807, 564, 361, 431, 426, 746, 828, 570, 393, 17, 119 }),
L"PDF417 Symbology Standard");
// Alpha
EXPECT_EQ(decode({ 15, 1, 63, 125, 187, 249, 311, 373, 435, 497, 559, 621, 683, 745, 809 }),
L"ABCDEFGHIJKLMNOPQRSTUVWXYZ ");
// Lower
EXPECT_EQ(decode({ 15, 810, 32, 94, 156, 218, 280, 342, 404, 466, 528, 590, 652, 714, 776 }),
L"abcdefghijklmnopqrstuvwxyz ");
// Mixed
EXPECT_EQ(decode({ 15, 840, 32, 94, 156, 311, 373, 435, 497, 559, 621, 683, 746, 218, 299 }),
L"0123456&\r\t,:#-.$/+%*=^ 789");
// Punctuation
EXPECT_EQ(decode({ 16, 865, 1, 63, 125, 187, 849, 311, 373, 435, 497, 559, 621, 683, 745, 809 }),
L";<>@[\\]_'~!\r\t,:\n-.$/\"|*()?{");
// Alpha Punctuation Lower Mixed
EXPECT_EQ(decode({ 27, 1, 865, 807, 896, 782, 855, 626, 807, 94, 865, 807, 896, 808, 776, 839, 176, 808, 32, 776,
839, 806, 208, 776, 839, 806, 239 }),
L"AB{} C#+ de{} {}F 12{} G{} H");
EXPECT_EQ(decode({ 25, 1, 896, 897, 806, 88, 470, 836, 783, 148, 776, 839, 806, 896, 897, 178, 806, 32, 776, 839,
806, 209, 809, 836, 787 }),
L"AB{} C#+ de{} {}F 12{} G{} H");
}
TEST(PDF417DecoderTest, TextCompactionShiftByte)
{
// Alpha ShiftByte Alpha
EXPECT_EQ(decode({ 7, 0, 0, 913, 233, 0, 0 }), L"AAAA\u00E9AAAA");
// Alpha ShiftByte Alpha(PS) (Padding)
EXPECT_EQ(decode({ 8, 0, 0, 913, 233, 0, 0, 29 }), L"AAAA\u00E9AAAAA");
// Alpha(PS) ShiftByte Alpha (Section 5.4.2.4 (b) (1) PS ignored)
EXPECT_EQ(decode({ 8, 0, 0, 29, 913, 233, 0, 0 }), L"AAAAA\u00E9AAAA");
// Alpha(PS) ShiftByte Lower(PS) (Padding)
EXPECT_EQ(decode({ 10, 0, 0, 29, 913, 233, 810, 0, 0, 29 }), L"AAAAA\u00E9aaaaaa");
// Lower ShiftByte Lower
EXPECT_EQ(decode({ 9, 810, 0, 0, 913, 233, 0, 0, 0 }), L"aaaaa\u00E9aaaaaa");
// Lower(PS) ShiftByte Lower (Section 5.4.2.4 (b) (1) PS ignored)
EXPECT_EQ(decode({ 10, 810, 0, 0, 29, 913, 233, 0, 0, 0 }), L"aaaaaa\u00E9aaaaaa");
// Mixed ShiftByte Mixed
EXPECT_EQ(decode({ 9, 840, 0, 0, 913, 233, 0, 0, 0 }), L"00000\u00E9000000");
// Mixed(PS) ShiftByte Mixed (Section 5.4.2.4 (b) (1) PS ignored)
EXPECT_EQ(decode({ 8, 840, 0, 29, 913, 233, 0, 0, }), L"0000\u00E90000");
// Punctuation ShiftByte Punctuation
EXPECT_EQ(decode({ 8, 865, 0, 0, 913, 233, 0, 0 }), L";;;;\u00E9;;;;");
// Punctuation(AL) ShiftByte (Alpha) (Section 5.4.2.4 (b) (2) AL not ignored)
EXPECT_EQ(decode({ 9, 865, 0, 0, 29, 913, 233, 0, 0 }), L";;;;;\u00E9AAAA");
// Punctuation(AL) ShiftByte Punctuation(AL) (Padding)
EXPECT_EQ(decode({ 11, 865, 0, 0, 29, 913, 233, 865, 0, 0, 29 }), L";;;;;\u00E9;;;;;");
// Punctuation(AL) ShiftByte Lower
EXPECT_EQ(decode({ 10, 865, 0, 0, 29, 913, 233, 810, 0, 0 }), L";;;;;\u00E9aaaaa");
// ShiftByte (first position, which defaults to Text Compaction)
EXPECT_EQ(decode({ 5, 913, 255, 775, 775 }), L"\u00FFZZZZ");
// Byte ShiftByte (ShiftByte can only occur in Text Compaction)
EXPECT_FALSE(valid({ 6, 901, 255, 255, 913, 255 }));
// Numeric ShiftByte (ShiftByte can only occur in Text Compaction)
EXPECT_FALSE(valid({ 7, 902, 171, 209, 268, 913, 255 }));
// Text, Numeric, Byte, ShiftByte
EXPECT_FALSE(valid({ 18, 1, 63, 125, 902, 17, 110, 836, 811, 223, 901, 127, 127, 127, 127, 913, 255, 775 }));
// Text, Numeric, ShiftByte
EXPECT_FALSE(valid({ 13, 1, 63, 125, 902, 17, 110, 836, 811, 223, 913, 255, 775 }));
}
TEST(PDF417DecoderTest, ByteCompaction)
{
// Byte (901)
EXPECT_EQ(decode({ 12, 901, 213, 598, 413, 118, 87, 127, 127, 127, 127, 127 }),
L"\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F");
// Byte6 (924) (mod 6 == 0)
EXPECT_EQ(decode({ 12, 924, 213, 598, 413, 118, 87, 213, 598, 413, 118, 87 }),
L"\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F");
// 924/901
EXPECT_EQ(decode({ 13, 924, 213, 598, 413, 118, 87, 901, 127, 127, 127, 127, 127 }),
L"\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F");
EXPECT_EQ(decode({ 17, 924, 213, 598, 413, 118, 87, 213, 598, 413, 118, 87, 901, 127, 127, 901, 127 }),
L"\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F");
// Multiple 901s
EXPECT_EQ(decode({ 15, 901, 127, 127, 127, 127, 127, 901, 127, 127, 127, 127, 901, 127, 127 }),
L"\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F");
EXPECT_EQ(decode({ 13, 901, 213, 598, 413, 118, 87, 127, 901, 127, 127, 127, 127 }),
L"\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F");
EXPECT_EQ(decode({ 13, 901, 213, 598, 413, 118, 87, 127, 127, 127, 127, 901, 127 }),
L"\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F");
EXPECT_EQ(decode({ 13, 901, 213, 598, 413, 118, 87, 127, 127, 127, 127, 127, 901 }),
L"\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F");
EXPECT_EQ(decode({ 14, 901, 213, 598, 413, 118, 87, 127, 127, 127, 127, 901, 901, 127 }),
L"\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F");
EXPECT_EQ(decode({ 15, 901, 213, 598, 413, 118, 87, 127, 127, 127, 127, 901, 901, 127, 901 }),
L"\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F");
EXPECT_EQ(decode({ 17, 901, 213, 598, 413, 118, 87, 127, 127, 127, 127, 127, 901, 127, 127, 127, 127 }),
L"\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F\x7F");
}
TEST(PDF417DecoderTest, NumericCompaction)
{
// 43 consecutive
EXPECT_EQ(decode({ 17, 902, 49, 98, 103, 675, 30, 186, 631, 467, 409, 266, 246, 677, 536, 811, 223 }),
L"1234567890123456789012345678901234567890123");
// 44 consecutive
EXPECT_EQ(decode({ 17, 902, 491, 81, 137, 450, 302, 67, 15, 174, 492, 862, 667, 475, 869, 12, 434 }),
L"12345678901234567890123456789012345678901234");
// 45 consecutive
EXPECT_EQ(decode({ 18, 902, 491, 81, 137, 450, 302, 67, 15, 174, 492, 862, 667, 475, 869, 12, 434, 15 }),
L"123456789012345678901234567890123456789012345");
// 87 consecutive
EXPECT_EQ(decode({ 32, 902, 491, 81, 137, 450, 302, 67, 15, 174, 492, 862, 667, 475, 869, 12, 434, 68, 482, 582,
185, 641, 663, 847, 653, 803, 879, 734, 537, 34, 771, 667 }),
Lyour_sha256_hash56789012345678901234567");
// 88 consecutive
EXPECT_EQ(decode({ 32, 902, 491, 81, 137, 450, 302, 67, 15, 174, 492, 862, 667, 475, 869, 12, 434, 685, 326, 422,
57, 117, 339, 377, 238, 839, 698, 145, 870, 348, 517, 378 }),
Lyour_sha256_hash567890123456789012345678");
// 89 consecutive
EXPECT_EQ(decode({ 33, 902, 491, 81, 137, 450, 302, 67, 15, 174, 492, 862, 667, 475, 869, 12, 434, 685, 326, 422,
57, 117, 339, 377, 238, 839, 698, 145, 870, 348, 517, 378, 19 }),
Lyour_sha256_hash5678901234567890123456789");
}
TEST(PDF417DecoderTest, CompactionCombos)
{
// Text, Byte, Numeric, Text
EXPECT_EQ(decode({ 19, 1, 63, 125, 901, 127, 127, 127, 127, 902, 17, 110, 836, 811, 223, 900, 652, 714, 779 }),
L"ABCDEF\x7F\x7F\x7F\x7F" L"1234567890123VWXYZ");
// Text, Numeric, Byte, Text
EXPECT_EQ(decode({ 19, 1, 63, 125, 902, 17, 110, 836, 811, 223, 901, 127, 127, 127, 127, 900, 652, 714, 779 }),
L"ABCDEF1234567890123\x7F\x7F\x7F\x7FVWXYZ");
// Byte, Text, Numeric, Text
EXPECT_EQ(decode({ 19, 901, 127, 127, 127, 900, 1, 63, 125, 902, 17, 110, 836, 811, 223, 900, 652, 714, 779 }),
L"\x7F\x7F\x7F" L"ABCDEF1234567890123VWXYZ");
// Byte, Numeric, Text
EXPECT_EQ(decode({ 17, 901, 127, 127, 127, 127, 127, 902, 17, 110, 836, 811, 223, 900, 652, 714, 779 }),
L"\x7F\x7F\x7F\x7F\x7F" L"1234567890123VWXYZ");
// Numeric, Text, Byte, Text
EXPECT_EQ(decode({ 19, 902, 17, 110, 836, 811, 223, 900, 1, 63, 125, 901, 127, 127, 127, 900, 652, 714, 779 }),
L"1234567890123ABCDEF\x7F\x7F\x7FVWXYZ");
// Numeric, Byte, Text
EXPECT_EQ(decode({ 18, 902, 17, 110, 836, 811, 223, 901, 127, 127, 127, 900, 1, 63, 125, 652, 714, 779 }),
L"1234567890123\x7F\x7F\x7F" L"ABCDEFVWXYZ");
}
TEST(PDF417DecoderTest, ECISingleText)
{
// ECI 3 "A"
EXPECT_EQ(decode({ 7, 927, 3, 900, 29, 913, 233 }), L"A\u00E9"); // ECI Text ShiftByte
EXPECT_EQ(decode({ 7, 900, 927, 3, 29, 913, 233 }), L"A\u00E9"); // Text ECI ShiftByte
EXPECT_EQ(decode({ 6, 927, 3, 29, 913, 233 }), L"A\u00E9"); // ECI (Text) ShiftByte
EXPECT_EQ(decode({ 6, 927, 3, 901, 65, 233 }), L"A\u00E9"); // ECI Byte
EXPECT_EQ(decode({ 6, 29, 913, 927, 3, 233 }), L"A\u00E9"); // (Text) ShiftByte ECI
// ECI 9 "A"
EXPECT_EQ(decode({ 7, 927, 9, 900, 29, 913, 226 }), L"A\u03B2"); // ECI Text ShiftByte
EXPECT_EQ(decode({ 7, 900, 927, 9, 29, 913, 226 }), L"A\u03B2"); // Text ECI ShiftByte
EXPECT_EQ(decode({ 6, 927, 9, 29, 913, 226 }), L"A\u03B2"); // ECI (Text) ShiftByte
EXPECT_EQ(decode({ 6, 927, 9, 901, 65, 226 }), L"A\u03B2"); // ECI Byte
EXPECT_EQ(decode({ 6, 29, 913, 927, 9, 226 }), L"A\u03B2"); // (Text) ShiftByte ECI
// "AB" ShiftByte ECI 9 ""
EXPECT_EQ(decode({ 6, 1, 913, 927, 9, 226 }), L"AB\u03B2");
}
TEST(PDF417DecoderTest, ECISingleByte)
{
// ECI 20 Byte ""
EXPECT_EQ(decode({ 8, 927, 20, 901, 147, 95, 228, 170 }), L"\u70B9\u8317");
// Byte ECI 20 ""
EXPECT_EQ(decode({ 8, 901, 927, 20, 147, 95, 228, 170 }), L"\u70B9\u8317");
// ECI 20 Byte "A"
EXPECT_EQ(decode({ 9, 927, 20, 901, 147, 95, 228, 170, 65 }), L"\u70B9\u8317A");
// Byte ECI 20 "A"
EXPECT_EQ(decode({ 9, 901, 927, 20, 147, 95, 228, 170, 65 }), L"\u70B9\u8317A");
// ECI 20 Byte6 ""
EXPECT_EQ(decode({ 9, 927, 20, 924, 246, 877, 166, 106, 797 }), L"\u70B9\u8317\u30C6");
// Byte6 ECI 20 ""
EXPECT_EQ(decode({ 9, 924, 927, 20, 246, 877, 166, 106, 797 }), L"\u70B9\u8317\u30C6");
// Byte6 ECI 20 (not allowed inside 5-codeword batch)
EXPECT_FALSE(valid({ 9, 924, 246, 877, 166, 106, 927, 20, 797 }));
// Byte ECI 20 "A"
EXPECT_EQ(decode({ 10, 901, 927, 20, 246, 877, 166, 106, 797, 65 }), L"\u70B9\u8317\u30C6A");
}
TEST(PDF417DecoderTest, ECISingleNumeric)
{
// ECIs allowed anywhere in Numeric Compaction
// Numeric ECI 20 Numeric(15)
EXPECT_EQ(decode({ 19, 902, 927, 20, 491, 81, 137, 450, 302, 67, 15, 174, 492, 862, 667, 475, 869, 12, 434 }),
L"12345678901234567890123456789012345678901234");
// Numeric(1) ECI 20 Numeric(14)
EXPECT_EQ(decode({ 19, 902, 11, 927, 20, 485, 624, 192, 160, 521, 439, 324, 737, 864, 136, 732, 282, 410, 12 }),
L"123456789012345678901234567890123456789012");
// Numeric(4) ECI 20 Numeric(11) Byte(ShiftJIS) ""
EXPECT_EQ(decode({ 24, 902, 154, 98, 332, 101, 927, 20, 354, 63, 496, 448, 236, 148, 354, 624, 335, 600, 123,
901, 147, 95, 228, 170 }),
L"1234567890123456789012345678901234567890123\u70B9\u8317");
// Numeric(11) ECI 25 Numeric(4) Byte(UnicodeBig) "A" (U+0100)
// (ASCII values of "3456789012" as UTF-16 "343536373839303132" (CJK compatibility block)
EXPECT_EQ(decode({ 24, 902, 322, 183, 750, 813, 535, 621, 854, 718, 783, 621, 112, 927, 25, 18, 413, 287, 712,
901, 0, 'A', 1, 0 }),
L"12345678901234567890123456789012\u3334\u3536\u3738\u3930\u3132A\u0100");
}
TEST(PDF417DecoderTest, ECIMultipleTextByte)
{
// Text "ABCDEFG" ECI 9 Byte "" ECI 3 "A"
EXPECT_EQ(decode({ 15, 1, 63, 125, 209, 927, 9, 901, 225, 226, 927, 3, 901, 225, 65 }),
L"ABCDEFG\u03B1\u03B2\u00E1A");
EXPECT_EQ(decode({ 14, 1, 63, 125, 209, 927, 9, 901, 225, 226, 927, 3, 225, 65 }), L"ABCDEFG\u03B1\u03B2\u00E1A");
// Text "ABCDEFG" ECI 9 Byte6 "" ECI 3 "A" ECI 7 ""
EXPECT_EQ(decode({ 24, 1, 63, 125, 209, 927, 9, 924, 378, 492, 165, 708, 390, 927, 3, 901, 225, 65, 927, 7, 901,
214, 215, 216 }),
L"ABCDEFG\u03B1\u03B2\u03B3\u03B4\u03B5\u03B6\u00E1A\u0436\u0437\u0438");
// "AB" ShiftByte ECI 9 "" ShiftByte ECI 7 ""
EXPECT_EQ(decode({ 10, 1, 913, 927, 9, 226, 913, 927, 7, 214 }), L"AB\u03B2\u0436");
}
TEST(PDF417DecoderTest, ECIMultipleByte)
{
// Byte "AB" ECI 9 Byte "" ECI 3 ""
EXPECT_EQ(decode({ 13, 901, 65, 66, 927, 9, 901, 225, 226, 927, 3, 901, 225 }), L"AB\u03B1\u03B2\u00E1");
// Byte "AB" ECI 9 "" ECI 3 ""
EXPECT_EQ(decode({ 11, 901, 65, 66, 927, 9, 225, 226, 927, 3, 225 }), L"AB\u03B1\u03B2\u00E1");
// Byte ECI 20 "" ECI 9 ""
EXPECT_EQ(decode({ 11, 901, 927, 20, 147, 95, 228, 170, 927, 9, 225 }), L"\u70B9\u8317\u03B1");
// Byte ECI 20 "" ECI 810899 ECI 9 ECI 811799 ""
EXPECT_EQ(decode({ 16, 901, 927, 20, 147, 95, 228, 170, 926, 899, 899, 927, 9, 925, 0, 225 }),
L"\u70B9\u8317\u03B1");
// Byte6 ECI 20 "" ECI 22 Byte ""
EXPECT_EQ(decode({ 13, 924, 927, 20, 246, 877, 166, 106, 797, 927, 22, 901, 0x90 }), L"\u70B9\u8317\u30C6\u0452");
// Byte ECI 20 "" ECI 9 "" ECI 22 ""
EXPECT_EQ(decode({ 15, 901, 927, 20, 246, 877, 166, 106, 797, 927, 9, 225, 927, 22, 0x90 }),
L"\u70B9\u8317\u30C6\u03B1\u0452");
// ECI 10 Byte ECI 20 "" ECI 30 ECI 29 "" ECI 8 ECI 9 "" ECI 810898 ECI 22 "" ECI 4 Text ShiftByte
// "" ECI 811800
EXPECT_EQ(decode({ 37, 927, 10, 901, 927, 20, 246, 877, 166, 106, 797, 927, 30, 927, 29, 415, 537, 357, 329, 194,
927, 8, 927, 9, 225, 926, 899, 898, 927, 22, 0x90, 927, 4, 900, 913, 0xAC, 925, 1 }),
L"\u70B9\u8317\u30C6\u9F44\u8180\u8D67\u03B1\u0452\u0179");
}
TEST(PDF417DecoderTest, ECIMultipleNumeric)
{
// Numeric(5) ECI 16 ECI 20 Numeric(10) Text(ShiftJIS) "AB"
EXPECT_EQ(decode({ 25, 902, 171, 209, 269, 12, 434, 927, 20, 404, 629, 775, 441, 213, 222, 288, 513, 400, 123,
900, 1, 913, 147, 913, 95 }),
L"1234567890123456789012345678901234567890123AB\u70B9");
// Numeric(6) ECI 16 Numeric(4) ECI 20 Numeric(5) Byte(ShiftJIS) "AB" ECI 26 ""
EXPECT_EQ(decode({ 31, 902, 190, 232, 498, 813, 782, 767, 927, 16, 259, 248, 517, 378, 927, 20, 289, 700, 317, 21,
112, 901, 'A', 'B', 147, 95, 927, 26, 0xCE, 901, 0x98 }),
L"123456789012345678901234567890123456789012AB\u70B9\u0398");
// Numeric(10) ECI 16 ECI 25 Numeric(5) Byte6(UnicodeBig) "A" ECI 26 Byte ""
EXPECT_EQ(decode({ 32, 902, 289, 885, 405, 732, 212, 109, 679, 286, 885, 289, 927, 16, 927, 25, 289, 700, 317, 21,
112, 924, 0, 382, 878, 524, 177, 927, 26, 901, 0xCE, 0x98 }),
L"12345678901234567890123456789\u3930\u3132\u3334\u3536\u3738\u3930\u3132A\u0100\u0141\u0398");
}
TEST(PDF417DecoderTest, ECIInvalid)
{
EXPECT_EQ(decode({ 4, 927, 901, 0 }), L""); // non-charset ECI > 899 -> empty text result
EXPECT_EQ(Decode({4, 927, 901, 0}).content().bytes, ByteArray("AA")); // non-charset ECI > 899 -> ignored in binary result
EXPECT_EQ(decode({ 3, 0, 927 }), L"AA"); // Malformed ECI at end silently ignored
}
TEST(PDF417DecoderTest, ECIMacroOptionalNumeric)
{
// Check that ECI 25 (UnicodeBig) in numeric field (resulting in "\u3x3x" codepoints) still parses
// File Size is "1234567890" ECI 25 "12345" ("\u3132\u3334\x35", the final odd byte gets dropped on UTF-16
// conversion)
std::vector<int> sampleCodes = { 19, 477, 928, 111, 100, 0, 252, 21, 86, 923, 5, 15, 369, 753, 190, 927, 25, 124,
745 };
DecoderResultExtra resultMetadata;
DecodeMacroBlock(sampleCodes, 3, resultMetadata);
EXPECT_EQ(0, resultMetadata.segmentIndex());
EXPECT_EQ("000252021086", resultMetadata.fileId());
EXPECT_EQ(false, resultMetadata.isLastSegment());
EXPECT_EQ(1234567890, resultMetadata.fileSize());
EXPECT_EQ(-1, resultMetadata.segmentCount());
}
TEST(PDF417DecoderTest, ECIGeneralPurpose)
{
// 2-byte
EXPECT_EQ(decode({ 5, 926, 10, 10, 0 }), L"AA"); // All General Purpose ECIs silently ignored
EXPECT_TRUE(valid({ 4, 0, 926, 10 })); // Malformed ECI at end silently ignored
EXPECT_TRUE(valid({ 3, 0, 926 })); // Malformed ECI at end silently ignored
}
TEST(PDF417DecoderTest, ECIUserDefined)
{
// 1-byte
EXPECT_EQ(decode({ 4, 925, 10, 0 }), L"AA"); // All User Defined ECIs silently ignored
EXPECT_TRUE(valid({ 3, 0, 925 })); // Malformed ECI at end silently ignored
}
TEST(PDF417DecoderTest, ReaderInit)
{
// Null
EXPECT_FALSE(Decode({2, 0}).readerInit());
EXPECT_EQ(decode({ 2, 0 }), L"AA");
// Set
EXPECT_TRUE(Decode({3, 921, 0}).readerInit());
EXPECT_EQ(decode({ 3, 921, 0 }), L"AA");
// Must be first
EXPECT_FALSE(Decode({3, 0, 921}).readerInit());
EXPECT_FALSE(valid({ 3, 0, 921 }));
EXPECT_FALSE(Decode({4, 901, 65, 921}).readerInit());
EXPECT_FALSE(valid({ 4, 901, 65, 921 }));
EXPECT_FALSE(Decode({4, 901, 921, 65}).readerInit());
EXPECT_FALSE(valid({ 4, 901, 921, 65 }));
}
TEST(PDF417DecoderTest, LinkageOther)
{
EXPECT_FALSE(valid({ 3, 918, 0 })); // Not supported
EXPECT_FALSE(valid({ 3, 0, 918 }));
}
TEST(PDF417DecoderTest, LinkageEANUCC)
{
EXPECT_TRUE(valid({ 3, 920, 0 })); // Ignored if first codeword after length
EXPECT_FALSE(valid({ 3, 0, 920 })); // But not elsewhere
}
TEST(PDF417DecoderTest, Reserved)
{
EXPECT_FALSE(valid({ 3, 903, 0 })); // Not supported
EXPECT_FALSE(valid({ 3, 0, 903 }));
}
```
|
/content/code_sandbox/test/unit/pdf417/PDF417DecoderTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 9,306
|
```c++
/*
*/
#include "BitMatrix.h"
#include "CharacterSet.h"
#include "DecoderResult.h"
#include "PseudoRandom.h"
#include "TextEncoder.h"
#include "aztec/AZDecoder.h"
#include "aztec/AZDetector.h"
#include "aztec/AZDetectorResult.h"
#include "aztec/AZEncoder.h"
#include "aztec/AZWriter.h"
#include <algorithm>
#include <utility>
namespace testing {
namespace internal {
bool operator==(const std::string& a, const std::wstring& b) {
return a.length() == b.length() && std::equal(a.begin(), a.end(), b.begin());
}
}
}
#include "gtest/gtest.h"
using namespace ZXing;
namespace {
// Shorthand to call Decode()
static DecoderResult parse(BitMatrix&& bits, bool compact, int nbDatablocks, int nbLayers)
{
return Aztec::Decode({{std::move(bits), {}}, compact, nbDatablocks, nbLayers, false /*readerInit*/, false /*isMirrored*/, 0 /*runeValue*/});
}
void TestEncodeDecode(const std::string& data, bool compact, int layers) {
Aztec::EncodeResult aztec = Aztec::Encoder::Encode(data, 25, Aztec::Encoder::DEFAULT_AZTEC_LAYERS);
ASSERT_EQ(aztec.compact, compact) << "Unexpected symbol format (compact)";
ASSERT_EQ(aztec.layers, layers) << "Unexpected nr. of layers";
DecoderResult res = parse(aztec.matrix.copy(), aztec.compact, aztec.codeWords, aztec.layers);
ASSERT_EQ(res.isValid(), true);
EXPECT_EQ(data, res.text());
// Check error correction by introducing a few minor errors
PseudoRandom random(0x12345678);
BitMatrix matrix = aztec.matrix.copy();
auto x = random.next(0, matrix.width() - 1);
auto y = random.next(0, 1);
matrix.flip(x, y);
x = random.next(0, matrix.width() - 1);
y = matrix.height() - 2 + random.next(0, 1);
matrix.flip(x, y);
x = random.next(0, 1);
y = random.next(0, matrix.height() - 1);
matrix.flip(x, y);
x = matrix.width() - 2 + random.next(0, 1);
y = random.next(0, matrix.height() - 1);
matrix.flip(x, y);
res = parse(std::move(matrix), aztec.compact, aztec.codeWords, aztec.layers);
ASSERT_EQ(res.isValid(), true);
EXPECT_EQ(data, res.text());
}
void TestWriter(const std::wstring& data, CharacterSet charset, int eccPercent, bool compact, int layers) {
// 1. Perform an encode-decode round-trip because it can be lossy.
// 2. Aztec Decoder currently always decodes the data with a LATIN-1 charset:
std::string textBytes = TextEncoder::FromUnicode(data, charset);
Aztec::Writer writer;
writer.setEncoding(charset);
writer.setEccPercent(eccPercent);
BitMatrix matrix = writer.encode(data, 0, 0);
Aztec::EncodeResult aztec = Aztec::Encoder::Encode(textBytes, eccPercent, Aztec::Encoder::DEFAULT_AZTEC_LAYERS);
EXPECT_EQ(aztec.compact, compact) << "Unexpected symbol format (compact)";
EXPECT_EQ(aztec.layers, layers) << "Unexpected nr. of layers";
EXPECT_EQ(aztec.matrix, matrix);
DecoderResult res = parse(matrix.copy(), aztec.compact, aztec.codeWords, aztec.layers);
EXPECT_EQ(res.isValid(), true);
EXPECT_EQ(res.content().bytes, ByteArray(textBytes));
// Check error correction by introducing up to eccPercent/2 errors
int ecWords = aztec.codeWords * eccPercent / 100 / 2;
PseudoRandom random(0x12345678);
for (int i = 0; i < ecWords; i++) {
// don't touch the core
int x = random.next(0, 1) == 1 ?
random.next(0, aztec.layers * 2 - 1)
: matrix.width() - 1 - random.next(0, aztec.layers * 2 - 1);
int y = random.next(0, 1) == 1 ?
random.next(0, aztec.layers * 2 - 1)
: matrix.height() - 1 - random.next(0, aztec.layers * 2 - 1);
matrix.flip(x, y);
}
res = parse(std::move(matrix), aztec.compact, aztec.codeWords, aztec.layers);
EXPECT_EQ(res.isValid(), true);
EXPECT_EQ(res.content().bytes, ByteArray(textBytes));
}
}
TEST(AZEncodeDecodeTest, EncodeDecode1)
{
TestEncodeDecode("Abc123!", true, 1);
}
TEST(AZEncodeDecodeTest, EncodeDecode2)
{
TestEncodeDecode("Lorem ipsum. path_to_url", true, 2);
}
TEST(AZEncodeDecodeTest, EncodeDecode3)
{
TestEncodeDecode("AAAANAAAANAAAANAAAANAAAANAAAANAAAANAAAANAAAANAAAAN", true, 3);
}
TEST(AZEncodeDecodeTest, EncodeDecode4)
{
TestEncodeDecode("path_to_url~!@#*^%&)__ ;:'\"[]{}\\|-+-=`1029384", true, 4);
}
TEST(AZEncodeDecodeTest, EncodeDecode5)
{
TestEncodeDecode("path_to_url~!@#*^%&)__ ;:'\"[]{}\\|-+-=`1029384756<>/?abc"
"Four score and seven our forefathers brought forth", false, 5);
}
TEST(AZEncodeDecodeTest, EncodeDecode10)
{
TestEncodeDecode("In ut magna vel mauris malesuada dictum. Nulla ullamcorper metus quis diam"
" cursus facilisis. Sed mollis quam id justo rutrum sagittis. Donec laoreet rutrum"
" est, nec convallis mauris condimentum sit amet. Phasellus gravida, justo et congue"
" auctor, nisi ipsum viverra erat, eget hendrerit felis turpis nec lorem. Nulla"
" ultrices, elit pellentesque aliquet laoreet, justo erat pulvinar nisi, id"
" elementum sapien dolor et diam.", false, 10);
}
TEST(AZEncodeDecodeTest, EncodeDecode23)
{
TestEncodeDecode("In ut magna vel mauris malesuada dictum. Nulla ullamcorper metus quis diam"
" cursus facilisis. Sed mollis quam id justo rutrum sagittis. Donec laoreet rutrum"
" est, nec convallis mauris condimentum sit amet. Phasellus gravida, justo et congue"
" auctor, nisi ipsum viverra erat, eget hendrerit felis turpis nec lorem. Nulla"
" ultrices, elit pellentesque aliquet laoreet, justo erat pulvinar nisi, id"
" elementum sapien dolor et diam. Donec ac nunc sodales elit placerat eleifend."
" Sed ornare luctus ornare. Vestibulum vehicula, massa at pharetra fringilla, risus"
" justo faucibus erat, nec porttitor nibh tellus sed est. Ut justo diam, lobortis eu"
" tristique ac, p.In ut magna vel mauris malesuada dictum. Nulla ullamcorper metus"
" quis diam cursus facilisis. Sed mollis quam id justo rutrum sagittis. Donec"
" laoreet rutrum est, nec convallis mauris condimentum sit amet. Phasellus gravida,"
" justo et congue auctor, nisi ipsum viverra erat, eget hendrerit felis turpis nec"
" lorem. Nulla ultrices, elit pellentesque aliquet laoreet, justo erat pulvinar"
" nisi, id elementum sapien dolor et diam. Donec ac nunc sodales elit placerat"
" eleifend. Sed ornare luctus ornare. Vestibulum vehicula, massa at pharetra"
" fringilla, risus justo faucibus erat, nec porttitor nibh tellus sed est. Ut justo"
" diam, lobortis eu tristique ac, p. In ut magna vel mauris malesuada dictum. Nulla"
" ullamcorper metus quis diam cursus facilisis. Sed mollis quam id justo rutrum"
" sagittis. Donec laoreet rutrum est, nec convallis mauris condimentum sit amet."
" Phasellus gravida, justo et congue auctor, nisi ipsum viverra erat, eget hendrerit"
" felis turpis nec lorem. Nulla ultrices, elit pellentesque aliquet laoreet, justo"
" erat pulvinar nisi, id elementum sapien dolor et diam.", false, 23);
}
TEST(AZEncodeDecodeTest, EncodeDecode31)
{
TestEncodeDecode("In ut magna vel mauris malesuada dictum. Nulla ullamcorper metus quis diam"
" cursus facilisis. Sed mollis quam id justo rutrum sagittis. Donec laoreet rutrum"
" est, nec convallis mauris condimentum sit amet. Phasellus gravida, justo et congue"
" auctor, nisi ipsum viverra erat, eget hendrerit felis turpis nec lorem. Nulla"
" ultrices, elit pellentesque aliquet laoreet, justo erat pulvinar nisi, id"
" elementum sapien dolor et diam. Donec ac nunc sodales elit placerat eleifend."
" Sed ornare luctus ornare. Vestibulum vehicula, massa at pharetra fringilla, risus"
" justo faucibus erat, nec porttitor nibh tellus sed est. Ut justo diam, lobortis eu"
" tristique ac, p.In ut magna vel mauris malesuada dictum. Nulla ullamcorper metus"
" quis diam cursus facilisis. Sed mollis quam id justo rutrum sagittis. Donec"
" laoreet rutrum est, nec convallis mauris condimentum sit amet. Phasellus gravida,"
" justo et congue auctor, nisi ipsum viverra erat, eget hendrerit felis turpis nec"
" lorem. Nulla ultrices, elit pellentesque aliquet laoreet, justo erat pulvinar"
" nisi, id elementum sapien dolor et diam. Donec ac nunc sodales elit placerat"
" eleifend. Sed ornare luctus ornare. Vestibulum vehicula, massa at pharetra"
" fringilla, risus justo faucibus erat, nec porttitor nibh tellus sed est. Ut justo"
" diam, lobortis eu tristique ac, p. In ut magna vel mauris malesuada dictum. Nulla"
" ullamcorper metus quis diam cursus facilisis. Sed mollis quam id justo rutrum"
" sagittis. Donec laoreet rutrum est, nec convallis mauris condimentum sit amet."
" Phasellus gravida, justo et congue auctor, nisi ipsum viverra erat, eget hendrerit"
" felis turpis nec lorem. Nulla ultrices, elit pellentesque aliquet laoreet, justo"
" erat pulvinar nisi, id elementum sapien dolor et diam. Donec ac nunc sodales elit"
" placerat eleifend. Sed ornare luctus ornare. Vestibulum vehicula, massa at"
" pharetra fringilla, risus justo faucibus erat, nec porttitor nibh tellus sed est."
" Ut justo diam, lobortis eu tristique ac, p.In ut magna vel mauris malesuada"
" dictum. Nulla ullamcorper metus quis diam cursus facilisis. Sed mollis quam id"
" justo rutrum sagittis. Donec laoreet rutrum est, nec convallis mauris condimentum"
" sit amet. Phasellus gravida, justo et congue auctor, nisi ipsum viverra erat,"
" eget hendrerit felis turpis nec lorem. Nulla ultrices, elit pellentesque aliquet"
" laoreet, justo erat pulvinar nisi, id elementum sapien dolor et diam. Donec ac"
" nunc sodales elit placerat eleifend. Sed ornare luctus ornare. Vestibulum vehicula,"
" massa at pharetra fringilla, risus justo faucibus erat, nec porttitor nibh tellus"
" sed est. Ut justo diam, lobortis eu tris. In ut magna vel mauris malesuada dictum."
" Nulla ullamcorper metus quis diam cursus facilisis. Sed mollis quam id justo rutrum"
" sagittis. Donec laoreet rutrum est, nec convallis mauris condimentum sit amet."
" Phasellus gravida, justo et congue auctor, nisi ipsum viverra erat, eget"
" hendrerit felis turpis nec lorem.", false, 31);
}
TEST(AZEncodeDecodeTest, AztecWriter)
{
//TestWriter(L"\x20AC 1 sample data.", CharacterSet::ISO8859_1, 25, true, 2);
//TestWriter(L"\x20AC 1 sample data.", CharacterSet::ISO8859_15, 25, true, 2);
TestWriter(L"\x20AC 1 sample data.", CharacterSet::UTF8, 25, true, 2);
TestWriter(L"\x20AC 1 sample data.", CharacterSet::UTF8, 100, true, 3);
TestWriter(L"\x20AC 1 sample data.", CharacterSet::UTF8, 300, true, 4);
TestWriter(L"\x20AC 1 sample data.", CharacterSet::UTF8, 500, false, 5);
// Test AztecWriter defaults
std::wstring data = L"In ut magna vel mauris malesuada";
BitMatrix matrix = Aztec::Writer().encode(data, 0, 0);
Aztec::EncodeResult aztec =
Aztec::Encoder::Encode(TextEncoder::FromUnicode(data, CharacterSet::ISO8859_1),
Aztec::Encoder::DEFAULT_EC_PERCENT, Aztec::Encoder::DEFAULT_AZTEC_LAYERS);
EXPECT_EQ(matrix, aztec.matrix);
}
TEST(AZEncodeDecodeTest, RunePure)
{
for(uint8_t word = 0; word < 255; word++) {
std::string data(1, word);
Aztec::EncodeResult aztec =
Aztec::Encoder::Encode(data, 0, Aztec::Encoder::AZTEC_RUNE_LAYERS);
auto result = Aztec::Detect(aztec.matrix, true, false);
EXPECT_TRUE(result.isValid());
EXPECT_EQ(result.nbDatablocks(), 0);
EXPECT_EQ(result.runeValue(), word);
}
}
```
|
/content/code_sandbox/test/unit/aztec/AZEncodeDecodeTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 3,499
|
```c++
/*
*/
#include "aztec/AZEncoder.h"
#include "BitArray.h"
#include "BitArrayUtility.h"
#include "BitMatrixIO.h"
#include "gtest/gtest.h"
#include <algorithm>
#include <stdexcept>
namespace ZXing {
namespace Aztec {
void GenerateModeMessage(bool compact, int layers, int messageSizeInWords, BitArray& modeMessage);
void StuffBits(const BitArray& bits, int wordSize, BitArray& out);
}
}
using namespace ZXing;
namespace {
void TestEncode(const std::string& data, bool compact, int layers, const BitMatrix& expected) {
Aztec::EncodeResult aztec = Aztec::Encoder::Encode(data, 33, Aztec::Encoder::DEFAULT_AZTEC_LAYERS);
EXPECT_EQ(aztec.compact, compact) << "Unexpected symbol format (compact)";
EXPECT_EQ(aztec.layers, layers) << "Unexpected nr. of layers";
EXPECT_EQ(aztec.matrix, expected) << "encode() failed";
}
std::string StripSpaces(std::string str) {
str.erase(std::remove_if(str.begin(), str.end(), isspace), str.end());
return str;
}
void TestModeMessage(bool compact, int layers, int words, const std::string& expected) {
BitArray bits;
Aztec::GenerateModeMessage(compact, layers, words, bits);
auto expectedBits = Utility::ParseBitArray(StripSpaces(expected));
EXPECT_EQ(bits, expectedBits) << "generateModeMessage() failed";
}
void TestStuffBits(int wordSize, const std::string& bits, const std::string& expected) {
BitArray in = Utility::ParseBitArray(StripSpaces(bits));
BitArray expectedBits = Utility::ParseBitArray(StripSpaces(expected));
BitArray stuffed;
Aztec::StuffBits(in, wordSize, stuffed);
EXPECT_EQ(stuffed, expectedBits) << "stuffBits() failed for input string: " + bits;
}
}
TEST(AZEncoderTest, GenerateModeMessage)
{
TestModeMessage(true, 2, 29, ".X .XXX.. ...X XX.. ..X .XX. .XX.X");
TestModeMessage(true, 4, 64, "XX XXXXXX .X.. ...X ..XX .X.. XX..");
TestModeMessage(false, 21, 660, "X.X.. .X.X..X..XX .XXX ..X.. .XXX. .X... ..XXX");
TestModeMessage(false, 32, 4096, "XXXXX XXXXXXXXXXX X.X. ..... XXX.X ..X.. X.XXX");
}
TEST(AZEncoderTest, StuffBits)
{
TestStuffBits(5, ".X.X. X.X.X .X.X.",
".X.X. X.X.X .X.X.");
TestStuffBits(5, ".X.X. ..... .X.X",
".X.X. ....X ..X.X");
TestStuffBits(3, "XX. ... ... ..X XXX .X. ..",
"XX. ..X ..X ..X ..X .XX XX. .X. ..X");
TestStuffBits(6, ".X.X.. ...... ..X.XX",
".X.X.. .....X. ..X.XX XXXX.");
TestStuffBits(6, ".X.X.. ...... ...... ..X.X.",
".X.X.. .....X .....X ....X. X.XXXX");
TestStuffBits(6, ".X.X.. XXXXXX ...... ..X.XX",
".X.X.. XXXXX. X..... ...X.X XXXXX.");
TestStuffBits(6,
"...... ..XXXX X..XX. .X.... .X.X.X .....X .X.... ...X.X .....X ....XX ..X... ....X. X..XXX X.XX.X",
".....X ...XXX XX..XX ..X... ..X.X. X..... X.X... ....X. X..... X....X X..X.. .....X X.X..X XXX.XX .XXXXX");
}
TEST(AZEncoderTest, Encode1)
{
TestEncode(
"This is an example Aztec symbol for Wikipedia.",
true, 3, ParseBitMatrix(
"X X X X X X X X \n"
"X X X X X X X X X X \n"
"X X X X X X X X X X X \n"
"X X X X X X X X X X X \n"
" X X X X X X X X X X X \n"
" X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X \n"
"X X X X X X X X X X \n"
" X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X \n"
" X X X X X X X X \n"
" X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X \n"
" X X X \n"
" X X X X X X X X X X \n"
" X X X X X X X X X X \n"
, 'X', true)
);
}
TEST(AZEncoderTest, Encode2)
{
TestEncode(
"Aztec Code is a public domain 2D matrix barcode symbology"
" of nominally square symbols built on a square grid with a "
"distinctive square bullseye pattern at their center.",
false, 6, ParseBitMatrix(
" X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X \n"
, 'X', true)
);
}
TEST(AZEncoderTest, UserSpecifiedLayers)
{
std::string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Aztec::EncodeResult aztec;
aztec = Aztec::Encoder::Encode(alphabet, 25, -2);
EXPECT_EQ(aztec.layers, 2);
EXPECT_TRUE(aztec.compact);
aztec = Aztec::Encoder::Encode(alphabet, 25, 32);
EXPECT_EQ(aztec.layers, 32);
EXPECT_FALSE(aztec.compact);
EXPECT_THROW({Aztec::Encoder::Encode(alphabet, 25, 33);}, std::invalid_argument );
EXPECT_THROW({Aztec::Encoder::Encode(alphabet, 25, -1);}, std::invalid_argument );
}
TEST(AZEncoderTest, BorderCompact4Case)
{
// Compact(4) con hold 608 bits of information, but at most 504 can be data. Rest must
// be error correction
std::string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
// encodes as 26 * 5 * 4 = 520 bits of data
std::string alphabet4 = alphabet + alphabet + alphabet + alphabet;
EXPECT_THROW({Aztec::Encoder::Encode(alphabet4, 0, -4);}, std::invalid_argument );
// If we just try to encode it normally, it will go to a non-compact 4 layer
auto aztec = Aztec::Encoder::Encode(alphabet4, 0, Aztec::Encoder::DEFAULT_AZTEC_LAYERS);
EXPECT_FALSE(aztec.compact);
EXPECT_EQ(aztec.layers, 4);
// But shortening the string to 100 bytes (500 bits of data), compact works fine, even if we
// include more error checking.
aztec = Aztec::Encoder::Encode(alphabet4.substr(0, 100), 10, Aztec::Encoder::DEFAULT_AZTEC_LAYERS);
EXPECT_TRUE(aztec.compact);
EXPECT_EQ(aztec.layers, 4);
}
TEST(AZEncoderTest, Rune)
{
{
Aztec::EncodeResult aztec = Aztec::Encoder::Encode("\x19", 0, Aztec::Encoder::AZTEC_RUNE_LAYERS);
EXPECT_EQ(aztec.layers, 0);
EXPECT_EQ(aztec.matrix, ParseBitMatrix(
"X X X X X X X \n"
"X X X X X X X X X X X \n"
" X X X \n"
" X X X X X X X X \n"
" X X X X \n"
"X X X X X X X \n"
"X X X X X X \n"
"X X X X X X X X \n"
"X X X X \n"
" X X X X X X X X X X \n"
" X X \n"
));
}
{
Aztec::EncodeResult aztec = Aztec::Encoder::Encode("\xFF", 0, Aztec::Encoder::AZTEC_RUNE_LAYERS);
EXPECT_EQ(aztec.layers, 0);
EXPECT_EQ(aztec.matrix, ParseBitMatrix(
"X X X X X X \n"
"X X X X X X X X X X X \n"
" X X X \n"
"X X X X X X X X X \n"
"X X X X X X \n"
" X X X X X X \n"
" X X X X \n"
"X X X X X X X X X \n"
"X X X \n"
" X X X X X X X X X X \n"
" X X X X X \n"
));
}
{
Aztec::EncodeResult aztec = Aztec::Encoder::Encode("\x44", 0, Aztec::Encoder::AZTEC_RUNE_LAYERS);
std::cout << ToString(aztec.matrix, 'X', ' ', true);
}
}
```
|
/content/code_sandbox/test/unit/aztec/AZEncoderTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 4,002
|
```c++
/*
*/
#include "aztec/AZDecoder.h"
#include "BitArray.h"
#include "BitMatrixIO.h"
#include "DecoderResult.h"
#include "aztec/AZDetectorResult.h"
#include "gtest/gtest.h"
#include <string_view>
#include <utility>
namespace ZXing::Aztec {
DecoderResult Decode(const BitArray& bits);
}
using namespace ZXing;
// Shorthand to call Decode()
static DecoderResult parse(BitMatrix&& bits, bool compact, int nbDatablocks, int nbLayers)
{
return Aztec::Decode({{std::move(bits), {}}, compact, nbDatablocks, nbLayers, false /*readerInit*/, false /*isMirrored*/, 0 /*runeValue*/});
}
TEST(AZDecoderTest, AztecResult)
{
auto bits = ParseBitMatrix(
"X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X \n"
" X X X X X X X X X X \n"
" X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X \n"
" X X X X X X X X X X X \n"
" X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X \n"
" X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X \n"
"X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X \n"
, 'X', true);
DecoderResult result = parse(std::move(bits), false, 30, 2);
EXPECT_EQ(result.isValid(), true);
EXPECT_EQ(result.text(), L"88888TTTTTTTTTTTTTTTTTTTTTTTTTTTTTT");
EXPECT_EQ(result.symbologyIdentifier(), "]z0");
}
TEST(AZDecoderTest, DecodeTooManyErrors)
{
auto bits = ParseBitMatrix(
"X X . X . . . X X . . . X . . X X X . X . X X X X X . \n"
"X X . . X X . . . . . X X . . . X X . . . X . X . . X \n"
"X . . . X X . . X X X . X X . X X X X . X X . . X . . \n"
". . . . X . X X . . X X . X X . X . X X X X . X . . X \n"
"X X X . . X X X X X . . . . . X X . . . X . X . X . X \n"
"X X . . . . . . . . X . . . X . X X X . X . . X . . . \n"
"X X . . X . . . . . X X . . . . . X . . . . X . . X X \n"
". . . X . X . X . . . . . X X X X X X . . . . . . X X \n"
"X . . . X . X X X X X X . . X X X . X . X X X X X X . \n"
"X . . X X X . X X X X X X X X X X X X X . . . X . X X \n"
". . . . X X . . . X . . . . . . . X X . . . X X . X . \n"
". . . X X X . . X X . X X X X X . X . . X . . . . . . \n"
"X . . . . X . X . X . X . . . X . X . X X . X X . X X \n"
"X . X . . X . X . X . X . X . X . X . . . . . X . X X \n"
"X . X X X . . X . X . X . . . X . X . X X X . . . X X \n"
"X X X X X X X X . X . X X X X X . X . X . X . X X X . \n"
". . . . . . . X . X . . . . . . . X X X X . . . X X X \n"
"X X . . X . . X . X X X X X X X X X X X X X . . X . X \n"
"X X X . X X X X . . X X X X . . X . . . . X . . X X X \n"
". . . . X . X X X . . . . X X X X . . X X X X . . . . \n"
". . X . . X . X . . . X . X X . X X . X . . . X . X . \n"
"X X . . X . . X X X X X X X . . X . X X X X X X X . . \n"
"X . X X . . X X . . . . . X . . . . . . X X . X X X . \n"
"X . . X X . . X X . X . X . . . . X . X . . X . . X . \n"
"X . X . X . . X . X X X X X X X X . X X X X . . X X . \n"
"X X X X . . . X . . X X X . X X . . X . . . . X X X . \n"
"X X . X . X . . . X . X . . . . X X . X . . X X . . . \n"
, 'X', true);
DecoderResult result = parse(std::move(bits), true, 16, 4);
EXPECT_EQ(result.error(), Error::Checksum);
}
TEST(AZDecoderTest, DecodeTooManyErrors2)
{
auto bits = ParseBitMatrix(
". X X . . X . X X . . . X . . X X X . . . X X . X X . \n"
"X X . X X . . X . . . X X . . . X X . X X X . X . X X \n"
". . . . X . . . X X X . X X . X X X X . X X . . X . . \n"
"X . X X . . X . . . X X . X X . X . X X . . . . . X . \n"
"X X . X . . X . X X . . . . . X X . . . . . X . . . X \n"
"X . . X . . . . . . X . . . X . X X X X X X X . . . X \n"
"X . . X X . . X . . X X . . . . . X . . . . . X X X . \n"
". . X X X X . X . . . . . X X X X X X . . . . . . X X \n"
"X . . . X . X X X X X X . . X X X . X . X X X X X X . \n"
"X . . X X X . X X X X X X X X X X X X X . . . X . X X \n"
". . . . X X . . . X . . . . . . . X X . . . X X . X . \n"
". . . X X X . . X X . X X X X X . X . . X . . . . . . \n"
"X . . . . X . X . X . X . . . X . X . X X . X X . X X \n"
"X . X . . X . X . X . X . X . X . X . . . . . X . X X \n"
"X . X X X . . X . X . X . . . X . X . X X X . . . X X \n"
"X X X X X X X X . X . X X X X X . X . X . X . X X X . \n"
". . . . . . . X . X . . . . . . . X X X X . . . X X X \n"
"X X . . X . . X . X X X X X X X X X X X X X . . X . X \n"
"X X X . X X X X . . X X X X . . X . . . . X . . X X X \n"
". . X X X X X . X . . . . X X X X . . X X X . X . X . \n"
". . X X . X . X . . . X . X X . X X . . . . X X . . . \n"
"X . . . X . X . X X X X X X . . X . X X X X X . X . . \n"
". X . . . X X X . . . . . X . . . . . X X X X X . X . \n"
"X . . X . X X X X . X . X . . . . X . X X . X . . X . \n"
"X . . . X X . X . X X X X X X X X . X X X X . . X X . \n"
". X X X X . . X . . X X X . X X . . X . . . . X X X . \n"
"X X . . . X X . . X . X . . . . X X . X . . X . X . X \n"
, 'X', true);
DecoderResult result = parse(std::move(bits), true, 16, 4);
EXPECT_EQ(result.error(), Error::Checksum);
}
// Helper taking bit string to call GetEncodedData()
static DecoderResult getData(std::string_view bitStr)
{
BitArray bits;
for (auto b : bitStr)
bits.appendBit(b == '1');
return Aztec::Decode(bits);
}
TEST(AZDecoderTest, SymbologyIdentifier)
{
{
// Plain
auto data = getData("00010");
EXPECT_EQ(data.symbologyIdentifier(), "]z0");
EXPECT_EQ(data.text(), L"A");
}
{
// GS1 ("PS FLGN(0) DL (20)01")
auto data = getData("0000000000000111100100001000100011");
EXPECT_EQ(data.symbologyIdentifier(), "]z1");
EXPECT_EQ(data.text(), L"2001");
}
{
// AIM ("A PS FLGN(0) B")
auto data = getData("00010000000000000000011");
EXPECT_EQ(data.symbologyIdentifier(), "]z2");
EXPECT_EQ(data.text(), L"AB");
}
{
// AIM ("DL 99 UL PS FLGN(0) B")
auto data = getData("11110101110111110000000000000000011");
EXPECT_EQ(data.symbologyIdentifier(), "]z2");
EXPECT_EQ(data.text(), L"99B");
}
{
// Structured Append ("UL ML A D A")
auto data = getData("1110111101000100010100010");
EXPECT_EQ(data.symbologyIdentifier(), "]z6");
EXPECT_EQ(data.text(), L"A");
EXPECT_EQ(data.structuredAppend().index, 0);
EXPECT_EQ(data.structuredAppend().count, 4);
}
{
// Structured Append with GS1 ("UL ML A D PS FLGN(0) DL (20)01")
auto data = getData("111011110100010001010000000000000111100100001000100011");
EXPECT_EQ(data.symbologyIdentifier(), "]z7");
EXPECT_EQ(data.text(), L"2001");
EXPECT_EQ(data.structuredAppend().index, 0);
EXPECT_EQ(data.structuredAppend().count, 4);
}
{
// Structured Append with AIM ("UL ML A D A PS FLGN(0) B")
auto data = getData("1110111101000100010100010000000000000000011");
EXPECT_EQ(data.symbologyIdentifier(), "]z8");
EXPECT_EQ(data.text(), L"AB");
EXPECT_EQ(data.structuredAppend().index, 0);
EXPECT_EQ(data.structuredAppend().count, 4);
}
{
// Plain with FNC1 not in first/second position ("A B PS FLGN(0) C")
auto data = getData("0001000011000000000000000100");
EXPECT_EQ(data.symbologyIdentifier(), "]z0");
EXPECT_EQ(data.text(), L"AB\u001DC"); // "AB<GS>C"
}
{
// Plain with FNC1 not in first/second position ("A B C PS FLGN(0) D")
auto data = getData("000100001100100000000000000000101");
EXPECT_EQ(data.symbologyIdentifier(), "]z0");
EXPECT_EQ(data.text(), L"ABC\u001DD"); // "ABC<GS>D"
}
{
// Plain with FNC1 not in first/second position ("DL 1 UL PS FLGN(0) A")
auto data = getData("1111000111110000000000000000010");
EXPECT_EQ(data.symbologyIdentifier(), "]z0");
EXPECT_EQ(data.text(), L"1\u001DA"); // "1<GS>D"
}
}
// Helper taking 5-bit word array to call GetEncodedData()
static DecoderResult getData(const ByteArray& bytes)
{
BitArray bits; // 5-bit words (assuming no digits/binary)
for (auto b : bytes)
bits.appendBits(b, 5);
return Aztec::Decode(bits);
}
// Shorthand to return Structured Append given 5-bit word array
static StructuredAppendInfo sai(const ByteArray& bytes)
{
return getData(bytes).structuredAppend();
}
// Shorthand to return string result given 5-bit word array
static std::wstring text(const ByteArray& bytes)
{
return getData(bytes).text();
}
TEST(AZDecoderTest, StructuredAppend)
{
// Null
EXPECT_EQ(sai({2}).index, -1);
EXPECT_EQ(sai({2}).count, -1);
EXPECT_TRUE(sai({2}).id.empty());
EXPECT_EQ(text({2}), L"A");
// Example from ISO/IEC 24778:2008 Section 8
EXPECT_EQ(sai({29, 29, 2, 5, 2}).index, 0); // AD
EXPECT_EQ(sai({29, 29, 2, 5, 2}).count, 4);
EXPECT_TRUE(sai({29, 29, 2, 5, 2}).id.empty());
EXPECT_EQ(text({29, 29, 2, 5, 2}), L"A");
EXPECT_EQ(sai({29, 29, 3, 5, 2}).index, 1); // BD
EXPECT_EQ(sai({29, 29, 3, 5, 2}).count, 4);
EXPECT_TRUE(sai({29, 29, 3, 5, 2}).id.empty());
EXPECT_EQ(text({29, 29, 3, 5, 2}), L"A");
EXPECT_EQ(sai({29, 29, 4, 5, 2}).index, 2); // CD
EXPECT_EQ(sai({29, 29, 4, 5, 2}).count, 4);
EXPECT_TRUE(sai({29, 29, 4, 5, 2}).id.empty());
EXPECT_EQ(text({29, 29, 4, 5, 2}), L"A");
EXPECT_EQ(sai({29, 29, 5, 5, 2}).index, 3); // DD
EXPECT_EQ(sai({29, 29, 5, 5, 2}).count, 4);
EXPECT_TRUE(sai({29, 29, 5, 5, 2}).id.empty());
EXPECT_EQ(text({29, 29, 5, 5, 2}), L"A");
// Sequencing field
EXPECT_EQ(sai({29, 29, 2, 27, 2}).index, 0); // AZ
EXPECT_EQ(sai({29, 29, 2, 27, 2}).count, 26);
EXPECT_EQ(sai({29, 29, 14, 27, 2}).index, 12); // MZ
EXPECT_EQ(sai({29, 29, 14, 27, 2}).count, 26);
EXPECT_EQ(sai({29, 29, 27, 27, 2}).index, 25); // ZZ
EXPECT_EQ(sai({29, 29, 27, 27, 2}).count, 26);
// Id
EXPECT_EQ(sai({29, 29, 1, 10, 5, 1, 2, 5, 2}).id, "ID");
EXPECT_EQ(text({29, 29, 1, 10, 5, 1, 2, 5, 2}), L"A");
// Invalid sequencing
EXPECT_EQ(sai({29, 29, 2, 2, 2}).index, 0); // AA
EXPECT_EQ(sai({29, 29, 2, 2, 2}).count, 0); // Count 1 so set to 0
EXPECT_EQ(text({29, 29, 2, 2, 2}), L"A");
EXPECT_EQ(sai({29, 29, 6, 5, 2}).index, 4); // ED
EXPECT_EQ(sai({29, 29, 6, 5, 2}).count, 0); // Count 4 <= index 4 so set to 0
EXPECT_EQ(text({29, 29, 6, 5, 2}), L"A");
EXPECT_EQ(sai({29, 29, 1, 5, 2}).index, -1); // Index < 'A'
EXPECT_EQ(sai({29, 29, 1, 5, 2}).count, -1);
EXPECT_EQ(text({29, 29, 1, 5, 2}), L" DA"); // Bad sequencing left in result
EXPECT_EQ(sai({29, 29, 28, 5, 2}).index, -1); // Index > 'Z' (LL)
EXPECT_EQ(sai({29, 29, 28, 5, 2}).count, -1);
EXPECT_EQ(text({29, 29, 28, 5, 2}), L"da");
EXPECT_EQ(sai({29, 29, 2, 1, 2}).index, -1); // Count < 'A'
EXPECT_EQ(sai({29, 29, 2, 1, 2}).count, -1);
EXPECT_EQ(text({29, 29, 2, 1, 2}), L"A A");
EXPECT_EQ(sai({29, 29, 2, 28, 2}).index, -1); // Count > 'Z'
EXPECT_EQ(sai({29, 29, 2, 28, 2}).count, -1);
EXPECT_EQ(text({29, 29, 2, 28, 2}), L"Aa");
EXPECT_EQ(sai({29, 29, 2, 5}).index, -1); // Sequencing but no data
EXPECT_EQ(sai({29, 29, 2, 5}).count, -1);
EXPECT_EQ(text({29, 29, 2, 5}), L"AD");
// Invalid Ids
{
auto data = getData({29, 29, 1, 10, 5, 2, 5, 2}); // No terminating space
EXPECT_TRUE(data.structuredAppend().id.empty());
EXPECT_EQ(data.structuredAppend().index, -1); // Not recognized as sequence
EXPECT_EQ(data.structuredAppend().count, -1);
EXPECT_EQ(data.text(), L" IDADA"); // Bad ID and sequencing left in result
}
{
auto data = getData({29, 29, 1, 1, 2, 5, 2}); // Blank
EXPECT_TRUE(data.structuredAppend().id.empty());
EXPECT_EQ(data.structuredAppend().index, 0); // Recognized as sequence
EXPECT_EQ(data.structuredAppend().count, 4);
EXPECT_EQ(data.text(), L"A");
}
{
auto data = getData({29, 29, 1, 10, 1, 5, 1, 2, 5, 2}); // Space in "I D"
EXPECT_TRUE(data.structuredAppend().id.empty());
EXPECT_EQ(data.structuredAppend().index, -1); // Not recognized as sequence as sequence count invalid (space)
EXPECT_EQ(data.structuredAppend().count, -1);
EXPECT_EQ(data.text(), L" I D ADA"); // Bad ID and sequencing left in result
}
{
auto data = getData({29, 29, 1, 10, 1, 2, 5, 1, 2, 5, 2}); // "I AD" (happens to have valid sequencing at end)
EXPECT_EQ(data.structuredAppend().id, "I");
EXPECT_EQ(data.structuredAppend().index, 0);
EXPECT_EQ(data.structuredAppend().count, 4);
EXPECT_EQ(data.text(), L" ADA"); // Trailing space and "real" sequencing left in result
}
}
```
|
/content/code_sandbox/test/unit/aztec/AZDecoderTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 5,309
|
```c++
/*
*/
#include "BitMatrixIO.h"
#include "DecoderResult.h"
#include "datamatrix/DMDecoder.h"
#include "datamatrix/DMWriter.h"
#include "gtest/gtest.h"
using namespace ZXing;
namespace {
void TestEncodeDecode(const std::wstring& data, DataMatrix::SymbolShape shape = DataMatrix::SymbolShape::NONE)
{
BitMatrix matrix = DataMatrix::Writer().setMargin(0).setShapeHint(shape).encode(data, 0, 0);
ASSERT_EQ(matrix.empty(), false);
DecoderResult res = DataMatrix::Decode(matrix);
#ifndef NDEBUG
if (!res.isValid() || data != res.text())
SaveAsPBM(matrix, "failed-datamatrix.pbm", 4);
#endif
ASSERT_EQ(res.isValid(), true) << "text size: " << data.size() << ", code size: " << matrix.height() << "x"
<< matrix.width() << ", shape: " << static_cast<int>(shape) << "\n"
<< (matrix.width() < 80 ? ToString(matrix) : std::string());
EXPECT_EQ(data, res.text()) << "text size: " << data.size() << ", code size: " << matrix.height() << "x"
<< matrix.width() << ", shape: " << static_cast<int>(shape) << "\n"
<< (matrix.width() < 80 ? ToString(matrix) : std::string());
}
}
TEST(DMEncodeDecodeTest, EncodeDecodeSquare)
{
std::wstring text[] = {
L"Abc123!",
L"Lorem ipsum. path_to_url",
L"AAAANAAAANAAAANAAAANAAAANAAAANAAAANAAAANAAAANAAAAN",
L"path_to_url~!@#*^%&)__ ;:'\"[]{}\\|-+-=`1029384",
L"path_to_url~!@#*^%&)__ ;:'\"[]{}\\|-+-=`1029384756<>/?abc"
"Four score and seven our forefathers brought forth",
L"In ut magna vel mauris malesuada dictum. Nulla ullamcorper metus quis diam"
" cursus facilisis. Sed mollis quam id justo rutrum sagittis. Donec laoreet rutrum"
" est, nec convallis mauris condimentum sit amet. Phasellus gravida, justo et congue"
" auctor, nisi ipsum viverra erat, eget hendrerit felis turpis nec lorem. Nulla"
" ultrices, elit pellentesque aliquet laoreet, justo erat pulvinar nisi, id"
" elementum sapien dolor et diam.",
L"In ut magna vel mauris malesuada dictum. Nulla ullamcorper metus quis diam"
" cursus facilisis. Sed mollis quam id justo rutrum sagittis. Donec laoreet rutrum"
" est, nec convallis mauris condimentum sit amet. Phasellus gravida, justo et congue"
" auctor, nisi ipsum viverra erat, eget hendrerit felis turpis nec lorem. Nulla"
" ultrices, elit pellentesque aliquet laoreet, justo erat pulvinar nisi, id"
" elementum sapien dolor et diam. Donec ac nunc sodales elit placerat eleifend."
" Sed ornare luctus ornare. Vestibulum vehicula, massa at pharetra fringilla, risus"
" justo faucibus erat, nec porttitor nibh tellus sed est. Ut justo diam, lobortis eu"
" tristique ac, p.In ut magna vel mauris malesuada dictum. Nulla ullamcorper metus"
" quis diam cursus facilisis. Sed mollis quam id justo rutrum sagittis. Donec"
" laoreet rutrum est, nec convallis mauris condimentum sit amet. Phasellus gravida,"
" justo et congue auctor, nisi ipsum viverra erat, eget hendrerit felis turpis nec"
" lorem. Nulla ultrices, elit pellentesque aliquet laoreet, justo erat pulvinar"
" nisi, id elementum sapien dolor et diam. Donec ac nunc sodales elit placerat"
" eleifend. Sed ornare luctus ornare. Vestibulum vehicula, massa at pharetra"
" fringilla, risus justo faucibus erat, nec porttitor nibh tellus sed est. Ut justo"
" diam, lobortis eu tristique ac, p. In ut magna vel mauris malesuada dictum. Nulla"
" ullamcorper metus quis diam cursus facilisis. Sed mollis quam id justo rutrum"
" sagittis. Donec laoreet rutrum est, nec convallis mauris condimentum sit amet."
" Phasellus gravida, justo et congue auctor, nisi ipsum viverra erat, eget hendrerit"
" felis turpis nec lorem. Nulla ultrices, elit pellentesque aliquet laoreet, justo"
" erat pulvinar nisi, id elementum sapien dolor et diam.",
};
for (auto& data : text)
TestEncodeDecode(data, DataMatrix::SymbolShape::SQUARE);
}
TEST(DMEncodeDecodeTest, EncodeDecodeRectangle)
{
std::wstring text[] = {
L"Abc123!",
L"Lorem ipsum. path_to_url",
L"3i0QnD^RcZO[\\#!]1,9zIJ{1z3qrvsq",
L"AAAANAAAANAAAANAAAANAAAANAAAANAAAANAAAANAAAANAAAAN",
L"path_to_url~!@#*^%&)__ ;:'\"[]{}\\|-+-=`1029384",
L"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
};
for (auto& data : text)
for (size_t len = 1; len <= data.size(); ++len)
TestEncodeDecode(data.substr(0, len), DataMatrix::SymbolShape::RECTANGLE);
}
TEST(DMEncodeDecodeTest, EDIFACTWithEOD)
{
using namespace DataMatrix;
std::wstring text[] = {
L"path_to_url~[******]_",
L"abc<->ABCDE",
L"<ABCDEFG><ABCDEFGK>",
L"*CH/GN1/022/00",
};
for (auto& data : text)
for (auto shape : {SymbolShape::NONE, SymbolShape::SQUARE, SymbolShape::RECTANGLE})
TestEncodeDecode(data, shape);
}
```
|
/content/code_sandbox/test/unit/datamatrix/DMEncodeDecodeTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 1,483
|
```c++
/*
*/
#include "datamatrix/DMSymbolInfo.h"
#include "gtest/gtest.h"
using namespace ZXing::DataMatrix;
TEST(DMSymbolInfoTest, SymbolInfo)
{
auto info = SymbolInfo::Lookup(3);
EXPECT_EQ(5, info->errorCodewords());
EXPECT_EQ(8, info->matrixWidth());
EXPECT_EQ(8, info->matrixHeight());
EXPECT_EQ(10, info->symbolWidth());
EXPECT_EQ(10, info->symbolHeight());
info = SymbolInfo::Lookup(3, SymbolShape::RECTANGLE);
EXPECT_EQ(7, info->errorCodewords());
EXPECT_EQ(16, info->matrixWidth());
EXPECT_EQ(6, info->matrixHeight());
EXPECT_EQ(18, info->symbolWidth());
EXPECT_EQ(8, info->symbolHeight());
info = SymbolInfo::Lookup(9);
EXPECT_EQ(11, info->errorCodewords());
EXPECT_EQ(14, info->matrixWidth());
EXPECT_EQ(6, info->matrixHeight());
EXPECT_EQ(32, info->symbolWidth());
EXPECT_EQ(8, info->symbolHeight());
info = SymbolInfo::Lookup(9, SymbolShape::SQUARE);
EXPECT_EQ(12, info->errorCodewords());
EXPECT_EQ(14, info->matrixWidth());
EXPECT_EQ(14, info->matrixHeight());
EXPECT_EQ(16, info->symbolWidth());
EXPECT_EQ(16, info->symbolHeight());
info = SymbolInfo::Lookup(1559);
EXPECT_EQ(nullptr, info) << "There's no rectangular symbol for more than 1558 data codewords";
info = SymbolInfo::Lookup(50, SymbolShape::RECTANGLE);
EXPECT_EQ(nullptr, info) << "There's no rectangular symbol for 50 data codewords";
info = SymbolInfo::Lookup(35);
EXPECT_EQ(24, info->symbolWidth());
EXPECT_EQ(24, info->symbolHeight());
int minWidth = 26;
int minHeight = 26;
int maxWidth = 26;
int maxHeight = 26;
info = SymbolInfo::Lookup(35, SymbolShape::NONE, minWidth, minHeight, maxWidth, maxHeight);
EXPECT_EQ(26, info->symbolWidth());
EXPECT_EQ(26, info->symbolHeight());
info = SymbolInfo::Lookup(45, SymbolShape::NONE, minWidth, minHeight, maxWidth, maxHeight);
EXPECT_EQ(nullptr, info);
maxWidth = 32;
maxHeight = 32;
info = SymbolInfo::Lookup(35, SymbolShape::NONE, minWidth, minHeight, maxWidth, maxHeight);
EXPECT_EQ(26, info->symbolWidth());
EXPECT_EQ(26, info->symbolHeight());
info = SymbolInfo::Lookup(40, SymbolShape::NONE, minWidth, minHeight, maxWidth, maxHeight);
EXPECT_EQ(26, info->symbolWidth());
EXPECT_EQ(26, info->symbolHeight());
info = SymbolInfo::Lookup(45, SymbolShape::NONE, minWidth, minHeight, maxWidth, maxHeight);
EXPECT_EQ(32, info->symbolWidth());
EXPECT_EQ(32, info->symbolHeight());
info = SymbolInfo::Lookup(63, SymbolShape::NONE, minWidth, minHeight, maxWidth, maxHeight);
EXPECT_EQ(nullptr, info);
}
```
|
/content/code_sandbox/test/unit/datamatrix/DMSymbolInfoTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 656
|
```c++
/*
*/
#include "ByteArray.h"
#include "DecoderResult.h"
#include "gtest/gtest.h"
#include <utility>
namespace ZXing::DataMatrix::DecodedBitStreamParser {
DecoderResult Decode(ByteArray&& bytes, const bool isDMRE);
}
using namespace ZXing;
// Helper to call Decode()
static DecoderResult parse(ByteArray bytes, const bool isDMRE = false)
{
return DataMatrix::DecodedBitStreamParser::Decode(std::move(bytes), isDMRE);
}
// Shorthand to return text
static std::wstring decode(ByteArray bytes, const bool isDMRE = false)
{
return parse(std::move(bytes), isDMRE).text();
}
// Shorthand to return symbology identifier
static std::string id(ByteArray bytes, const bool isDMRE = false)
{
return parse(std::move(bytes), isDMRE).symbologyIdentifier();
}
// Shorthand to return Structured Append
static StructuredAppendInfo info(ByteArray bytes, const bool isDMRE = false)
{
return parse(std::move(bytes), isDMRE).structuredAppend();
}
TEST(DMDecodeTest, Ascii)
{
// ASCII characters 0-127 are encoded as the value + 1
EXPECT_EQ(decode({'b', 'c', 'd', 'B', 'C', 'D'}), L"abcABC");
// ASCII double digit (00 - 99) Numeric Value + 130
EXPECT_EQ(decode({130, 131, 228, 229}), L"00019899");
}
TEST(DMDecodeTest, AsciiError)
{
// ASCII err on invalid code word
EXPECT_EQ(parse({66, 250, 68}).error(), Error::Format);
// ASCII err on invalid code word at end (currently failing)
EXPECT_EQ(parse({66, 67, 68, 250}).error(), Error::Format);
// ASCII accept extra (illegal) unlatch at end
EXPECT_FALSE(parse({66, 67, 68, 254}).error());
}
// Most of the following examples are taken from the DMHighLevelEncodeTest.cpp tests.
// For an explanation of the different cases, see there.
TEST(DMDecodeTest, C40)
{
EXPECT_EQ(decode({230, 91, 11, 91, 11, 91, 11, 254}), L"AIMAIMAIM");
EXPECT_EQ(decode({66, 74, 78, 66, 74, 66, 99, 129}), L"AIMAIAb");
EXPECT_EQ(decode({230, 91, 11, 91, 11, 91, 11, 254, 235, 76}), L"AIMAIMAIM\xCB");
EXPECT_EQ(decode({230, 91, 11, 91, 11, 91, 11, 254, 235, 108}), L"AIMAIMAIM\xEB");
EXPECT_EQ(decode({230, 88, 88, 40, 8, 107, 147, 59, 67, 126, 206, 78, 126, 144, 121, 35, 47, 254}), L"A1B2C3D4E5F6G7H8I9J0K1L2");
EXPECT_EQ(decode({230, 91, 11, 91, 11, 91, 11, 91, 11, 91, 11, 91, 11}), L"AIMAIMAIMAIMAIMAIM");
EXPECT_EQ(decode({230, 91, 11, 91, 11, 91, 11, 91, 11, 91, 11, 90, 241}), L"AIMAIMAIMAIMAIMAI");
EXPECT_EQ(decode({230, 91, 11, 91, 11, 91, 11, 91, 11, 91, 11, 254, 66}), L"AIMAIMAIMAIMAIMA");
EXPECT_EQ(decode({230, 91, 11, 91, 11, 91, 11, 91, 11, 91, 11, 254, 66, 74, 129, 237}), L"AIMAIMAIMAIMAIMAI");
EXPECT_EQ(decode({230, 91, 11, 91, 11, 91, 11, 66}), L"AIMAIMAIMA");
EXPECT_EQ(decode({230, 91, 11, 91, 11, 91, 11, 91, 11, 91, 11, 91, 11, 254, 66, 74}), L"AIMAIMAIMAIMAIMAIMAI");
}
TEST(DMDecodeTest, Text)
{
EXPECT_EQ(decode({239, 91, 11, 91, 11, 91, 11, 254}), L"aimaimaim");
EXPECT_EQ(decode({239, 91, 11, 91, 11, 91, 11, 254, 40, 129}), L"aimaimaim'");
EXPECT_EQ(decode({239, 91, 11, 91, 11, 87, 218, 110}), L"aimaimaIm");
EXPECT_EQ(decode({239, 91, 11, 91, 11, 91, 11, 254, 67, 129}), L"aimaimaimB");
EXPECT_EQ(decode({239, 91, 11, 91, 11, 91, 11, 16, 218, 236, 107, 181, 69, 254, 129, 237}), L"aimaimaim{txt}\x04");
}
TEST(DMDecodeTest, C40AndTextShiftUpper)
{
// additional shiftUpper test: (1->shift 2, 30->upperShift, 3->' '+128==0xa0) == 2804 == 0x0af4
EXPECT_EQ(decode({230, 0x0a, 0xf4}), L"\xA0"); // C40
EXPECT_EQ(decode({239, 0x0a, 0xf4}), L"\xA0"); // Text
}
TEST(DMDecodeTest, X12)
{
EXPECT_EQ(decode({238, 89, 233, 14, 192, 100, 207, 44, 31, 67}), L"ABC>ABC123>AB");
EXPECT_EQ(decode({238, 89, 233, 14, 192, 100, 207, 44, 31, 254, 67, 68}), L"ABC>ABC123>ABC");
EXPECT_EQ(decode({238, 89, 233, 14, 192, 100, 207, 44, 31, 96, 82, 254}), L"ABC>ABC123>ABCD");
EXPECT_EQ(decode({238, 89, 233, 14, 192, 100, 207, 44, 31, 96, 82, 70}), L"ABC>ABC123>ABCDE");
EXPECT_EQ(decode({238, 89, 233, 14, 192, 100, 207, 44, 31, 96, 82, 254, 70, 71, 129, 237}), L"ABC>ABC123>ABCDEF");
// EXPECT_EQ(decode({}), L"");
}
TEST(DMDecodeTest, SymbologyIdentifier)
{
// Plain
EXPECT_EQ(id({50}), "]d1");
EXPECT_EQ(decode({50}), L"1");
// GS1 "FNC1 (20)01"
EXPECT_EQ(id({232, 150, 131}), "]d2");
EXPECT_EQ(decode({232, 150, 131}), L"2001");
// "LatchC40 Shift2 FNC1 LatchASCII 2001" not recognized as FNC1 in first position
EXPECT_EQ(id({230, 0x0A, 0x79, 254, 150, 131}), "]d1"); // shift2FNC1 = (1600 * 1) + (40 * 27) + 0 + 1 == 0x0A79
EXPECT_EQ(decode({230, 0x0A, 0x79, 254, 150, 131}), L"\u001D2001");
// AIM "A FNC1 B"
EXPECT_EQ(id({66, 232, 67}), "]d3");
EXPECT_EQ(decode({66, 232, 67}), L"AB");
// AIM "9 FNC1 A"
EXPECT_EQ(id({58, 232, 66}), "]d3");
EXPECT_EQ(decode({58, 232, 66}), L"9A");
// AIM "99 FNC1 A" (double digit + 130)
EXPECT_EQ(id({99 + 130, 232, 66}), "]d3");
EXPECT_EQ(decode({99 + 130, 232, 66}), L"99A");
// AIM "? FNC1 A" (ISO/IEC 16022:2006 11.2 does not specify any restrictions on single first character)
EXPECT_EQ(id({64, 232, 66}), "]d3");
EXPECT_EQ(decode({64, 232, 66}), L"?A");
// "LatchC40 A Shift2 FNC1 B" not recognized as FNC1 in second position
EXPECT_EQ(id({230, 0x57, 0xC4, 254, 67}), "]d1"); // shift2FNC1 = 1600 * 14 + (40 * 1) + 27 + 1 == 0x57C4
EXPECT_EQ(decode({230, 0x57, 0xC4, 254, 67}), L"A\u001DB");
// "99 FNC1 A" (2 single digits before FNC1 not recognized as AIM)
EXPECT_EQ(id({58, 58, 232, 66}), "]d1");
EXPECT_EQ(decode({58, 58, 232, 66}), L"99\u001DA");
// GS1 "StructuredAppend FNC1 (20)01"
EXPECT_EQ(id({233, 42, 1, 1, 232, 150, 131}), "]d2");
EXPECT_EQ(decode({233, 42, 1, 1, 232, 150, 131}), L"2001");
// AIM "StructuredAppend A FNC1 B"
EXPECT_EQ(id({233, 42, 1, 1, 66, 232, 67}), "]d3");
EXPECT_EQ(decode({233, 42, 1, 1, 66, 232, 67}), L"AB");
}
TEST(DMDecodeTest, DMRESymbologyIdentifier)
{
// Plain
EXPECT_EQ(id({50}, true /*isDMRE*/), "]d7");
EXPECT_EQ(decode({50}, true /*isDMRE*/), L"1");
// GS1 "FNC1 (20)01"
EXPECT_EQ(id({232, 150, 131}, true /*isDMRE*/), "]d8");
EXPECT_EQ(decode({232, 150, 131}, true /*isDMRE*/), L"2001");
// AIM "A FNC1 B"
EXPECT_EQ(id({66, 232, 67}, true /*isDMRE*/), "]d9");
EXPECT_EQ(decode({66, 232, 67}, true /*isDMRE*/), L"AB");
// AIM "9 FNC1 A"
EXPECT_EQ(id({58, 232, 66}, true /*isDMRE*/), "]d9");
EXPECT_EQ(decode({58, 232, 66}, true /*isDMRE*/), L"9A");
// AIM "99 FNC1 A" (double digit + 130)
EXPECT_EQ(id({99 + 130, 232, 66}, true /*isDMRE*/), "]d9");
EXPECT_EQ(decode({99 + 130, 232, 66}, true /*isDMRE*/), L"99A");
// AIM "? FNC1 A" (ISO/IEC 16022:2006 11.2 does not specify any restrictions on single first character)
EXPECT_EQ(id({64, 232, 66}, true /*isDMRE*/), "]d9");
EXPECT_EQ(decode({64, 232, 66}, true /*isDMRE*/), L"?A");
// "99 FNC1 A" (2 single digits before FNC1 not recognized as AIM)
EXPECT_EQ(id({58, 58, 232, 66}, true /*isDMRE*/), "]d7");
EXPECT_EQ(decode({58, 58, 232, 66}, true /*isDMRE*/), L"99\u001DA");
// GS1 "StructuredAppend FNC1 (20)01"
EXPECT_EQ(id({233, 42, 1, 1, 232, 150, 131}, true /*isDMRE*/), "]d8");
EXPECT_EQ(decode({233, 42, 1, 1, 232, 150, 131}, true /*isDMRE*/), L"2001");
// AIM "StructuredAppend A FNC1 B"
EXPECT_EQ(id({233, 42, 1, 1, 66, 232, 67}, true /*isDMRE*/), "]d9");
EXPECT_EQ(decode({233, 42, 1, 1, 66, 232, 67}, true /*isDMRE*/), L"AB");
}
TEST(DMDecodeTest, StructuredAppend)
{
// Null
EXPECT_EQ(info({50}).index, -1);
EXPECT_EQ(info({50}).count, -1);
EXPECT_TRUE(info({50}).id.empty());
EXPECT_EQ(id({50}), "]d1");
// Structured Append "233" must be first ISO 16022:2006 5.6.1
EXPECT_FALSE(parse({50, 233, 42, 1, 1}).isValid());
// ISO/IEC 16022:2006 5.6.2 sequence indicator example
EXPECT_TRUE(parse({233, 42, 1, 1, 50}).isValid());
EXPECT_EQ(info({233, 42, 1, 1, 50}).index, 2); // 1-based position 3 == index 2
EXPECT_EQ(info({233, 42, 1, 1, 50}).count, 7);
EXPECT_EQ(info({233, 42, 1, 1, 50}).id, "257");
EXPECT_EQ(id({233, 42, 1, 1, 50}), "]d1");
// Sequence indicator
EXPECT_EQ(info({233, 0, 1, 1, 50}).index, 0);
EXPECT_EQ(info({233, 0, 1, 1, 50}).count, 0); // Count 17 set to 0
EXPECT_EQ(info({233, 1, 1, 1, 50}).index, 0);
EXPECT_EQ(info({233, 1, 1, 1, 50}).count, 16);
EXPECT_EQ(info({233, 0x81, 1, 1, 50}).index, 8);
EXPECT_EQ(info({233, 0x81, 1, 1, 50}).count, 16);
EXPECT_EQ(info({233, 0xFF, 1, 1, 50}).index, 15);
EXPECT_EQ(info({233, 0xFF, 1, 1, 50}).count, 0); // Count 2 <= index so set to 0
EXPECT_EQ(info({233, 0xF1, 1, 1, 50}).index, 15);
EXPECT_EQ(info({233, 0xF1, 1, 1, 50}).count, 16);
// File identification
EXPECT_EQ(info({233, 42, 1, 12, 50}).id, "268");
EXPECT_EQ(info({233, 42, 12, 34, 50}).id, "3106");
EXPECT_EQ(info({233, 42, 12, 123, 50}).id, "3195");
EXPECT_EQ(info({233, 42, 254, 254, 50}).id, "65278");
// Values outside 1-254 allowed (i.e. tolerated)
EXPECT_EQ(info({233, 42, 0, 0, 50}).id, "0");
EXPECT_EQ(info({233, 42, 0, 255, 50}).id, "255");
EXPECT_EQ(info({233, 42, 255, 0, 50}).id, "65280");
EXPECT_EQ(info({233, 42, 255, 255, 50}).id, "65535");
}
TEST(DMDecodeTest, ReaderInit)
{
// Null
EXPECT_FALSE(parse({50}).readerInit());
EXPECT_TRUE(parse({50}).isValid());
// Reader Programming "234" must be first ISO 16022:2006 5.2.4.9
EXPECT_FALSE(parse({50, 234}).isValid());
// Set
EXPECT_TRUE(parse({234, 50}).isValid());
EXPECT_TRUE(parse({234, 50}).readerInit());
EXPECT_FALSE(parse({235, 234, 50}).isValid());
// Can't be used with Structured Append "233"
EXPECT_TRUE(parse({233, 42, 1, 1, 50}).isValid()); // Null
EXPECT_FALSE(parse({233, 42, 1, 1, 234, 50}).isValid());
}
```
|
/content/code_sandbox/test/unit/datamatrix/DMDecodedBitStreamParserTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 3,870
|
```c++
/*
*/
#include "datamatrix/DMWriter.h"
#include "BitMatrixIO.h"
#include "gtest/gtest.h"
using namespace ZXing;
using namespace ZXing::DataMatrix;
TEST(DMWriterTest, ImageWriter)
{
int bigEnough = 64;
Writer writer;
writer.setMargin(0).setShapeHint(SymbolShape::SQUARE);
auto matrix = writer.encode(L"Hello Google", bigEnough, bigEnough);
EXPECT_LE(matrix.width(), bigEnough);
EXPECT_LE(matrix.height(), bigEnough);
}
TEST(DMWriterTest, Writer2)
{
int bigEnough = 14;
Writer writer;
writer.setMargin(0).setShapeHint(SymbolShape::SQUARE);
auto matrix = writer.encode(L"Hello Me", bigEnough, bigEnough);
EXPECT_EQ(matrix.width(), bigEnough);
EXPECT_EQ(matrix.height(), bigEnough);
}
TEST(DMWriterTest, TooSmallSize)
{
// The DataMatrix will not fit in this size, so the matrix should come back bigger
int tooSmall = 8;
Writer writer;
writer.setMargin(0);
auto matrix = writer.encode(L"path_to_url", tooSmall, tooSmall);
EXPECT_GT(matrix.width(), tooSmall);
EXPECT_GT(matrix.height(), tooSmall);
}
static void DoTest(const std::wstring& text, SymbolShape shape, const char* expected)
{
Writer writer;
writer.setMargin(0).setShapeHint(shape);
auto matrix = writer.encode(text, 0, 0);
auto actual = ToString(matrix, 'X', ' ', true);
EXPECT_EQ(expected, actual);
}
TEST(DMWriterTest, Small)
{
DoTest(L"0", SymbolShape::SQUARE,
"X X X X X \n"
"X X X X X X \n"
"X X X X \n"
"X X X \n"
"X X X X X X \n"
"X X X X X X X \n"
"X X X \n"
"X X X X X X X \n"
"X X X \n"
"X X X X X X X X X X \n" );
}
TEST(DMWriterTest, Rectangle)
{
DoTest(L"abcde", SymbolShape::RECTANGLE,
"X X X X X X X X X \n"
"X X X X X X X X X \n"
"X X X X X X X X \n"
"X X X X X X X X X X X \n"
"X X X X X X X X X X X X X \n"
"X X X X X X X X X X \n"
"X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X \n");
}
TEST(DMWriterTest, Large)
{
auto text = Lyour_sha256_hash56789-123456789-123456789-123456789-"
Lyour_sha256_hash56789-123456789-123456789-123456789-"
Lyour_sha256_hash56789-123456789-123456789-123456789-";
auto expected =
"X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n";
DoTest(text, SymbolShape::SQUARE, expected);
}
```
|
/content/code_sandbox/test/unit/datamatrix/DMWriterTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 3,212
|
```c++
/*
*/
#include "ByteArray.h"
#include "CharacterSet.h"
#include "ZXAlgorithms.h"
#include "datamatrix/DMHighLevelEncoder.h"
#include "datamatrix/DMSymbolInfo.h"
#include "gtest/gtest.h"
namespace ZXing {
namespace DataMatrix {
void OverrideSymbolSet(const SymbolInfo* symbols, size_t count);
void UseDefaultSymbolSet();
}
}
using namespace ZXing;
//private static void useTestSymbols() {
// SymbolInfo.overrideSymbolSet(TEST_SYMBOLS);
//}
//private static void resetSymbols() {
// SymbolInfo.overrideSymbolSet(SymbolInfo.PROD_SYMBOLS);
//}
namespace {
static DataMatrix::SymbolInfo TEST_SYMBOLS[] = {
{ false, 3, 5, 8, 8, 1 },
{ false, 5, 7, 10, 10, 1 },
{ true, 5, 7, 16, 6, 1 },
{ false, 8, 10, 12, 12, 1 },
{ true, 10, 11, 14, 6, 2 },
{ false, 13, 0, 0, 0, 1 },
{ false, 77, 0, 0, 0, 1 },
//The last entries are fake entries to test special conditions with C40 encoding
};
/**
* Convert a string of char codewords into a different string which lists each character
* using its decimal value.
*
* @param codewords the codewords
* @return the visualized codewords
*/
static std::string Visualize(const ByteArray& codewords) {
std::stringstream buf;
for (int i = 0; i < Size(codewords); i++) {
if (i > 0) {
buf << ' ';
}
buf << (int)codewords[i];
}
return buf.str();
}
std::string Encode(const std::wstring& text) {
return Visualize(DataMatrix::Encode(text));
}
std::wstring CreateBinaryMessage(int len) {
std::wstring buf;
buf.append(L"\xAB\xE4\xF6\xFC\xE9\xE0\xE1-");
for (int i = 0; i < len - 9; i++) {
buf.push_back(L'\xB7');
}
buf.push_back(L'\xBB');
return buf;
}
}
TEST(DMHighLevelEncodeTest, ASCIIEncodation)
{
std::string visualized = Encode(L"123456");
EXPECT_EQ(visualized, "142 164 186");
visualized = Encode(L"123456\xA3");
EXPECT_EQ(visualized, "142 164 186 235 36");
visualized = Encode(L"30Q324343430794<OQQ");
EXPECT_EQ(visualized, "160 82 162 173 173 173 137 224 61 80 82 82");
}
TEST(DMHighLevelEncodeTest, C40EncodationBasic1)
{
std::string visualized = Encode(L"AIMAIMAIM");
EXPECT_EQ(visualized, "230 91 11 91 11 91 11 254");
//230 shifts to C40 encodation, 254 unlatches, "else" case
}
TEST(DMHighLevelEncodeTest, C40EncodationBasic2)
{
std::string visualized = Encode(L"AIMAIAB");
EXPECT_EQ(visualized, "230 91 11 90 255 254 67 129");
//"B" is normally encoded as "15" (one C40 value)
//"else" case: "B" is encoded as ASCII
visualized = Encode(L"AIMAIAb");
EXPECT_EQ(visualized, "66 74 78 66 74 66 99 129"); //Encoded as ASCII
//Alternative solution:
//EXPECT_EQ(visualized, "230 91 11 90 255 254 99 129", visualized);
//"b" is normally encoded as "Shift 3, 2" (two C40 values)
//"else" case: "b" is encoded as ASCII
visualized = Encode(L"AIMAIMAIM\xCB");
EXPECT_EQ(visualized, "230 91 11 91 11 91 11 254 235 76");
//Alternative solution:
//EXPECT_EQ(visualized, "230 91 11 91 11 91 11 11 9 254", visualized);
//Expl: 230 = shift to C40, "91 11" = "AIM",
//"11 9" = "" = "Shift 2, UpperShift, <char>
//"else" case
visualized = Encode(L"AIMAIMAIM\xEB");
EXPECT_EQ(visualized, "230 91 11 91 11 91 11 254 235 108"); //Activate when additional rectangulars are available
//Expl: 230 = shift to C40, "91 11" = "AIM",
//"" in C40 encodes to: 1 30 2 11 which doesn't fit into a triplet
//"10 243" =
//254 = unlatch, 235 = Upper Shift, 108 = = 0xEB/235 - 128 + 1
//"else" case
}
TEST(DMHighLevelEncodeTest, C40EncodationSpecExample)
{
//Example in Figure 1 in the spec
std::string visualized = Encode(L"A1B2C3D4E5F6G7H8I9J0K1L2");
EXPECT_EQ(visualized, "230 88 88 40 8 107 147 59 67 126 206 78 126 144 121 35 47 254");
}
TEST(DMHighLevelEncodeTest, C40EncodationSpecialCases1)
{
//Special tests avoiding ultra-long test strings because these tests are only used
//with the 16x48 symbol (47 data codewords)
DataMatrix::OverrideSymbolSet(TEST_SYMBOLS, Size(TEST_SYMBOLS));
std::string visualized = Encode(L"AIMAIMAIMAIMAIMAIM");
EXPECT_EQ(visualized, "230 91 11 91 11 91 11 91 11 91 11 91 11");
//case "a": Unlatch is not required
visualized = Encode(L"AIMAIMAIMAIMAIMAI");
EXPECT_EQ(visualized, "230 91 11 91 11 91 11 91 11 91 11 90 241");
// case "b": Add trailing shift 0 and Unlatch is not required
visualized = Encode(L"AIMAIMAIMAIMAIMA");
EXPECT_EQ(visualized, "230 91 11 91 11 91 11 91 11 91 11 254 66");
// case "c": Unlatch and write last character in ASCII
DataMatrix::UseDefaultSymbolSet();
visualized = Encode(L"AIMAIMAIMAIMAIMAI");
EXPECT_EQ(visualized, "230 91 11 91 11 91 11 91 11 91 11 254 66 74 129 237");
visualized = Encode(L"AIMAIMAIMA");
EXPECT_EQ(visualized, "230 91 11 91 11 91 11 66");
// case "d": Skip Unlatch and write last character in ASCII
}
TEST(DMHighLevelEncodeTest, C40EncodationSpecialCases2) {
std::string visualized = Encode(L"AIMAIMAIMAIMAIMAIMAI");
EXPECT_EQ(visualized, "230 91 11 91 11 91 11 91 11 91 11 91 11 254 66 74");
//available > 2, rest = 2 --> unlatch and encode as ASCII
}
TEST(DMHighLevelEncodeTest, TextEncodation)
{
std::string visualized = Encode(L"aimaimaim");
EXPECT_EQ(visualized, "239 91 11 91 11 91 11 254");
//239 shifts to Text encodation, 254 unlatches
visualized = Encode(L"aimaimaim'");
EXPECT_EQ(visualized, "239 91 11 91 11 91 11 254 40 129");
// EXPECT_EQ(visualized, "239 91 11 91 11 91 11 7 49 254");
// This is an alternative, but doesn't strictly follow the rules in the spec.
visualized = Encode(L"aimaimaIm");
EXPECT_EQ(visualized, "239 91 11 91 11 87 218 110");
visualized = Encode(L"aimaimaimB");
EXPECT_EQ(visualized, "239 91 11 91 11 91 11 254 67 129");
visualized = Encode(L"aimaimaim{txt}\x04");
EXPECT_EQ(visualized, "239 91 11 91 11 91 11 16 218 236 107 181 69 254 129 237");
}
TEST(DMHighLevelEncodeTest, X12Encodation)
{
// 238 shifts to X12 encodation, 254 unlatches
std::string visualized = Encode(L"ABC>ABC123>AB");
EXPECT_EQ(visualized, "238 89 233 14 192 100 207 44 31 67");
visualized = Encode(L"ABC>ABC123>ABC");
EXPECT_EQ(visualized, "238 89 233 14 192 100 207 44 31 254 67 68");
visualized = Encode(L"ABC>ABC123>ABCD");
EXPECT_EQ(visualized, "238 89 233 14 192 100 207 44 31 96 82 254");
visualized = Encode(L"ABC>ABC123>ABCDE");
EXPECT_EQ(visualized, "238 89 233 14 192 100 207 44 31 96 82 70");
visualized = Encode(L"ABC>ABC123>ABCDEF");
EXPECT_EQ(visualized, "238 89 233 14 192 100 207 44 31 96 82 254 70 71 129 237");
}
TEST(DMHighLevelEncodeTest, EDIFACTEncodation)
{
// 240 shifts to EDIFACT encodation
std::string visualized = Encode(L".A.C1.3.DATA.123DATA.123DATA");
EXPECT_EQ(visualized, "240 184 27 131 198 236 238 16 21 1 187 28 179 16 21 1 187 28 179 16 21 1");
visualized = Encode(L".A.C1.3.X.X2..");
EXPECT_EQ(visualized, "240 184 27 131 198 236 238 98 230 50 47 47");
visualized = Encode(L".A.C1.3.X.X2.");
EXPECT_EQ(visualized, "240 184 27 131 198 236 238 98 230 50 47 129");
visualized = Encode(L".A.C1.3.X.X2");
EXPECT_EQ(visualized, "240 184 27 131 198 236 238 98 230 50");
visualized = Encode(L".A.C1.3.X.X");
EXPECT_EQ(visualized, "240 184 27 131 198 236 238 98 230 31");
visualized = Encode(L".A.C1.3.X.");
EXPECT_EQ(visualized, "240 184 27 131 198 236 238 98 231 192");
visualized = Encode(L".A.C1.3.X");
EXPECT_EQ(visualized, "240 184 27 131 198 236 238 89");
// Checking temporary unlatch from EDIFACT
visualized = Encode(L".XXX.XXX.XXX.XXX.XXX.XXX.\xFCXX.XXX.XXX.XXX.XXX.XXX.XXX");
EXPECT_EQ(visualized, "240 185 134 24 185 134 24 185 134 24 185 134 24 185 134 24 185 134 24"
" 124 47 235 125 240" // <- this is the temporary unlatch
" 97 139 152 97 139 152 97 139 152 97 139 152 97 139 152 97 139 152 89 89");
}
TEST(DMHighLevelEncodeTest, Base256Encodation)
{
// 231 shifts to Base256 encodation
std::string visualized = Encode(L"\xAB\xE4\xF6\xFC\xE9\xBB");
EXPECT_EQ(visualized, "231 44 108 59 226 126 1 104");
visualized = Encode(L"\xAB\xE4\xF6\xFC\xE9\xE0\xBB");
EXPECT_EQ(visualized, "231 51 108 59 226 126 1 141 254 129");
visualized = Encode(L"\xAB\xE4\xF6\xFC\xE9\xE0\xE1\xBB");
EXPECT_EQ(visualized, "231 44 108 59 226 126 1 141 36 147");
visualized = Encode(L" 23\xA3"); // ASCII only (for reference)
EXPECT_EQ(visualized, "33 153 235 36 129");
visualized = Encode(L"\xAB\xE4\xF6\xFC\xE9\xBB 234"); // Mixed Base256 + ASCII
EXPECT_EQ(visualized, "231 51 108 59 226 126 1 104 99 153 53 129");
visualized = Encode(L"\xAB\xE4\xF6\xFC\xE9\xBB 23\xA3 1234567890123456789");
EXPECT_EQ(visualized, "231 55 108 59 226 126 1 104 99 10 161 167 185 142 164 186 208"
" 220 142 164 186 208 58 129 59 209 104 254 150 45");
visualized = Encode(CreateBinaryMessage(20));
EXPECT_EQ(visualized, "231 44 108 59 226 126 1 141 36 5 37 187 80 230 123 17 166 60 210 103 253 150");
visualized = Encode(CreateBinaryMessage(19)); // padding necessary at the end
EXPECT_EQ(visualized, "231 63 108 59 226 126 1 141 36 5 37 187 80 230 123 17 166 60 210 103 1 129");
visualized = Encode(CreateBinaryMessage(276));
std::string expectedStart = "231 38 219 2 208 120 20 150 35";
std::string epxectedEnd = "146 40 194 129";
EXPECT_EQ(visualized.substr(0, expectedStart.length()), expectedStart);
EXPECT_EQ(visualized.substr(visualized.length() - epxectedEnd.length()), epxectedEnd);
visualized = Encode(CreateBinaryMessage(277));
expectedStart = "231 38 220 2 208 120 20 150 35";
epxectedEnd = "146 40 190 87";
EXPECT_EQ(visualized.substr(0, expectedStart.length()), expectedStart);
EXPECT_EQ(visualized.substr(visualized.length() - epxectedEnd.length()), epxectedEnd);
}
TEST(DMHighLevelEncodeTest, UnlatchingFromC40)
{
std::string visualized = Encode(L"AIMAIMAIMAIMaimaimaim");
EXPECT_EQ(visualized, "230 91 11 91 11 91 11 254 66 74 78 239 91 11 91 11 91 11");
}
TEST(DMHighLevelEncodeTest, UnlatchingFromText)
{
std::string visualized = Encode(L"aimaimaimaim12345678");
EXPECT_EQ(visualized, "239 91 11 91 11 91 11 91 11 254 142 164 186 208 129 237");
}
TEST(DMHighLevelEncodeTest, tHelloWorld)
{
std::string visualized = Encode(L"Hello World!");
EXPECT_EQ(visualized, "73 239 116 130 175 123 148 64 158 233 254 34");
}
TEST(DMHighLevelEncodeTest, Bug1664266)
{
// There was an exception and the encoder did not handle the unlatching from
// EDIFACT encoding correctly
std::string visualized = Encode(L"CREX-TAN:h");
EXPECT_EQ(visualized, "240 13 33 88 181 64 78 124 59 105");
visualized = Encode(L"CREX-TAN:hh");
EXPECT_EQ(visualized, "240 13 33 88 181 64 78 124 59 105 105 129");
visualized = Encode(L"CREX-TAN:hhh");
EXPECT_EQ(visualized, "240 13 33 88 181 64 78 124 59 105 105 105");
}
TEST(DMHighLevelEncodeTest, X12Unlatch)
{
std::string visualized = Encode(L"*DTCP01");
EXPECT_EQ(visualized, "238 9 10 104 141 254 50 129");
}
TEST(DMHighLevelEncodeTest, X12Unlatch2)
{
std::string visualized = Encode(L"*DTCP0");
EXPECT_EQ(visualized, "238 9 10 104 141");
}
TEST(DMHighLevelEncodeTest, Bug3048549)
{
// There was an IllegalArgumentException for an illegal character here because
// of an encoding problem of the character 0x0060 in Java source code.
std::string visualized = Encode(L"fiykmj*Rh2`,e6");
EXPECT_EQ(visualized, "239 122 87 154 40 7 171 115 207 12 130 71 155 254 129 237");
}
TEST(DMHighLevelEncodeTest, MacroCharacters)
{
std::string visualized = Encode(L"[)>\x1E""05\x1D""5555\x1C""6666\x1E\x04");
//EXPECT_EQ(visualized, "92 42 63 31 135 30 185 185 29 196 196 31 5 129 87 237");
EXPECT_EQ(visualized, "236 185 185 29 196 196 129 56");
}
TEST(DMHighLevelEncodeTest, EncodingWithStartAsX12AndLatchToEDIFACTInTheMiddle)
{
std::string visualized = Encode(L"*MEMANT-1F-MESTECH");
EXPECT_EQ(visualized, "238 10 99 164 204 254 240 82 220 70 180 209 83 80 80 200");
}
TEST(DMHighLevelEncodeTest, EDIFACTWithEODBug)
{
std::string visualized = Visualize(
DataMatrix::Encode(L"abc<->ABCDE", CharacterSet::ISO8859_1, DataMatrix::SymbolShape::SQUARE, -1, -1, -1, -1));
// switch to EDIFACT on '<', uses 10 code words + 2 padding. Buggy code introduced invalid 254 after the 5
EXPECT_EQ(visualized, "98 99 100 240 242 223 129 8 49 5 129 147");
}
// @Ignore
// @Test
// public void testDataURL() {
//
// byte[] data = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A,
// 0x7E, 0x7F, (byte) 0x80, (byte) 0x81, (byte) 0x82};
// String expected = encodeHighLevel(new String(data, StandardCharsets.ISO_8859_1));
// String visualized = encodeHighLevel("url(data:text/plain;charset=iso-8859-1,"
// + "%00%01%02%03%04%05%06%07%08%09%0A%7E%7F%80%81%82)");
// assertEquals(expected, visualized);
// assertEquals("1 2 3 4 5 6 7 8 9 10 11 231 153 173 67 218 112 7", visualized);
//
// visualized = encodeHighLevel("url(data:;base64,flRlc3R+)");
// assertEquals("127 85 102 116 117 127 129 56", visualized);
// }
//
// private static String encodeHighLevel(String msg) {
// CharSequence encoded = HighLevelEncoder.encodeHighLevel(msg);
// //DecodeHighLevel.decode(encoded);
// return visualize(encoded);
// }
//
// /**
// * Convert a string of char codewords into a different string which lists each character
// * using its decimal value.
// *
// * @param codewords the codewords
// * @return the visualized codewords
// */
// static String visualize(CharSequence codewords) {
// StringBuilder sb = new StringBuilder();
// for (int i = 0; i < codewords.length(); i++) {
// if (i > 0) {
// sb.append(' ');
// }
// sb.append((int) codewords.charAt(i));
// }
// return sb.toString();
// }
//
//}
```
|
/content/code_sandbox/test/unit/datamatrix/DMHighLevelEncodeTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 4,936
|
```c++
/*
*/
#include "aztec/AZDetector.h"
#include "BitMatrixIO.h"
#include "DecoderResult.h"
#include "PseudoRandom.h"
#include "Utf.h"
#include "aztec/AZDecoder.h"
#include "aztec/AZDetectorResult.h"
#include "gtest/gtest.h"
#include <string_view>
#include <vector>
using namespace ZXing;
namespace {
struct Point {
int x;
int y;
};
std::vector<Point> GetOrientationPoints(const BitMatrix& matrix, bool isCompact) {
int center = matrix.width() / 2;
int offset = isCompact ? 5 : 7;
std::vector<Point> result;
result.reserve(12);
for (int xSign : { -1, 1}) {
for (int ySign : { -1, 1}) {
result.push_back({ center + xSign * offset, center + ySign * offset });
result.push_back({ center + xSign * (offset - 1), center + ySign * offset });
result.push_back({ center + xSign * offset, center + ySign * (offset - 1) });
}
}
return result;
}
// Test that we can tolerate errors in the parameter locator bits
void TestErrorInOrientationBits(std::string_view data, int nbLayers, bool isCompact, const BitMatrix &matrix_)
{
PseudoRandom random(std::hash<std::string_view>()(data));
auto orientationPoints = GetOrientationPoints(matrix_, isCompact);
for (bool mirror : { false, true }) {
BitMatrix matrix = matrix_.copy();
if (mirror)
matrix.mirror();
for (int i = 0; i < 4; ++i) {
Aztec::DetectorResult r = Aztec::Detect(matrix, true, false);
EXPECT_EQ(r.isValid(), true);
EXPECT_EQ(r.nbLayers(), nbLayers);
EXPECT_EQ(r.isCompact(), isCompact);
EXPECT_EQ(r.isMirrored(), mirror);
EXPECT_EQ(data, ToUtf8(Aztec::Decode(r).text()));
// Systematically try every possible 1- and 2-bit error.
for (int error1 = 0; error1 < Size(orientationPoints); error1++) {
for (int error2 = error1; error2 < Size(orientationPoints); error2++) {
BitMatrix copy = matrix.copy();
copy.flip(orientationPoints[error1].x, orientationPoints[error1].y);
if (error2 > error1 && (nbLayers > 1 || !mirror)) { // in ErrorInModeMessageZero and mirror==true test only 1-bit errors
// if error2 == error1, we only test a single error
copy.flip(orientationPoints[error2].x, orientationPoints[error2].y);
}
Aztec::DetectorResult r = Aztec::Detect(copy, true, false);
EXPECT_EQ(r.isValid(), true);
EXPECT_EQ(r.nbLayers(), nbLayers);
EXPECT_EQ(r.isCompact(), isCompact);
EXPECT_EQ(r.isMirrored(), mirror);
EXPECT_EQ(data, ToUtf8(Aztec::Decode(r).text()));
}
}
// here used to be a test for 3-bit errors but since we determine both the rotation and the mirrored info
// from the orentation bits (as suggested in the specification) this does not work anymore.
matrix.rotate90();
}
}
}
} // anonymous
TEST(AZDetectorTest, ErrorInModeMessageZero)
{
// Layers=1, CodeWords=1. So the ModeMessage and its Reed-Solomon bits will be completely zero!
TestErrorInOrientationBits("X", 1, true, ParseBitMatrix(
" X X X X X X X X X X X X \n"
"X X X X X X X X \n"
" X X X X \n"
"X X X X X X X X X X X X X X \n"
"X X X X X \n"
"X X X X X X X X X X \n"
"X X X X X X X X \n"
" X X X X X X \n"
"X X X X X X X X \n"
" X X X X X X X X \n"
"X X X X \n"
" X X X X X X X X X X X X \n"
" X X \n"
"X X X X X X X \n"
"X X X X X X X \n"
, 'X', true)
);
}
TEST(AZDetectorTest, ErrorInOrientationBitsCompact)
{
TestErrorInOrientationBits("This is an example Aztec symbol for Wikipedia.", 3, true, ParseBitMatrix(
"X X X X X X X X \n"
"X X X X X X X X X X \n"
"X X X X X X X X X X X \n"
"X X X X X X X X X X X \n"
" X X X X X X X X X X X \n"
" X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X \n"
"X X X X X X X X X X \n"
" X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X \n"
" X X X X X X X X \n"
" X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X \n"
" X X X \n"
" X X X X X X X X X X \n"
" X X X X X X X X X X \n"
, 'X', true)
);
}
TEST(AZDetectorTest, ErrorInOrientationBitsNotCompact)
{
std::string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxyz";
TestErrorInOrientationBits(alphabet + alphabet + alphabet, 6, false, ParseBitMatrix(
" X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X \n"
, 'X', true)
);
}
TEST(AZDetectorTest, ReaderInitFull2Layers)
{
{
// Null (not set)
auto r = Aztec::Detect(ParseBitMatrix(
" X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X \n"
" X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X \n"
"X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X \n"
" X X X X X X X X X X X \n"
" X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X \n"
"X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X \n"
"X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X \n"
" X X X X X X X X X X X \n"
" X X X X X X X X X \n"
" X X X X X X X X X X \n"
" X X X X X X X X \n"
), false /*isPure*/, false /*tryHarder*/);
EXPECT_TRUE(r.isValid());
EXPECT_FALSE(r.readerInit());
EXPECT_FALSE(r.isCompact());
EXPECT_EQ(r.nbLayers(), 2);
}
{
// Set
auto r = Aztec::Detect(ParseBitMatrix(
" X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X \n"
"X X X X X X X X X X X X X X \n"
"X X X X X X X X X \n"
"X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X \n"
" X X X X X X X X X X X \n"
" X X X X X X X X X X X \n"
"X X X X X X X X X X X X \n"
"X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X \n"
"X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X \n"
" X X X X X X X X X X X \n"
" X X X X X X X X X \n"
" X X X X X X X X X X \n"
" X X X X X X X X \n"
), true /*isPure*/, false /*tryHarder*/);
EXPECT_TRUE(r.isValid());
EXPECT_TRUE(r.readerInit());
EXPECT_FALSE(r.isCompact());
EXPECT_EQ(r.nbLayers(), 2);
}
}
TEST(AZDetectorTest, ReaderInitFull22Layers)
{
// Set
auto r = Aztec::Detect(ParseBitMatrix(
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
" X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
"X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X \n"
), true /*isPure*/, false /*tryHarder*/);
EXPECT_TRUE(r.isValid());
EXPECT_TRUE(r.readerInit());
EXPECT_FALSE(r.isCompact());
EXPECT_EQ(r.nbLayers(), 22);
}
TEST(AZDetectorTest, ReaderInitCompact)
{
{
// Null (not set)
auto r = Aztec::Detect(ParseBitMatrix(
" X X X X \n"
" X X X X X X X X X \n"
" X X X X \n"
" X X X X X X X X X X X X \n"
" X X X \n"
" X X X X X X X X X \n"
"X X X X X X \n"
"X X X X X X X \n"
"X X X X X X X \n"
"X X X X X X X X X X X X \n"
" X X X X \n"
" X X X X X X X X X X X \n"
"X X X X X \n"
"X X X X X \n"
"X X X X X X X X X \n"
), true /*isPure*/, false /*tryHarder*/);
EXPECT_TRUE(r.isValid());
EXPECT_FALSE(r.readerInit());
EXPECT_TRUE(r.isCompact());
EXPECT_EQ(r.nbLayers(), 1);
}
{
// Set
auto r = Aztec::Detect(ParseBitMatrix(
" X X X X \n"
" X X X X X X X X X \n"
" X X X X X \n"
" X X X X X X X X X X X X \n"
" X X X X \n"
" X X X X X X X X X X \n"
"X X X X X X X \n"
"X X X X X X X \n"
"X X X X X X \n"
"X X X X X X X X X X X \n"
" X X X X \n"
" X X X X X X X X X X X \n"
"X X X X X X X X \n"
"X X X X X \n"
"X X X X X X X X X \n"
), true /*isPure*/, false /*tryHarder*/);
EXPECT_TRUE(r.isValid());
EXPECT_TRUE(r.readerInit());
EXPECT_TRUE(r.isCompact());
EXPECT_EQ(r.nbLayers(), 1);
}
}
TEST(AZDetectorTest, Rune)
{
{
auto r = Aztec::Detect(ParseBitMatrix(
"X X X X X X X \n"
"X X X X X X X X X X X \n"
" X X \n"
"X X X X X X X X X \n"
" X X X X \n"
"X X X X X X X \n"
" X X X X \n"
"X X X X X X X X X \n"
" X X \n"
" X X X X X X X X X X \n"
" X X X X \n"
), false /*isPure*/, false /*tryHarder*/);
EXPECT_TRUE(r.isValid());
EXPECT_EQ(r.nbDatablocks(), 0);
EXPECT_EQ(r.runeValue(), 0);
}
{
auto r = Aztec::Detect(ParseBitMatrix(
"X X X X X X X \n"
"X X X X X X X X X X X \n"
" X X X \n"
" X X X X X X X X \n"
" X X X X \n"
"X X X X X X X \n"
"X X X X X X \n"
"X X X X X X X X \n"
"X X X X \n"
" X X X X X X X X X X \n"
" X X \n"
), true /*isPure*/, false /*tryHarder*/);
EXPECT_TRUE(r.isValid());
EXPECT_EQ(r.nbDatablocks(), 0);
EXPECT_EQ(r.runeValue(), 25);
}
{
auto r = Aztec::Detect(ParseBitMatrix(
"X X X X \n"
"X X X X X X X X X X X \n"
" X X \n"
"X X X X X X X X \n"
" X X X X X \n"
" X X X X X \n"
" X X X X X \n"
" X X X X X X X X \n"
"X X X \n"
" X X X X X X X X X X \n"
" X X \n"
), true /*isPure*/, false /*tryHarder*/);
// This is just the core of a regular compact code, and not a valid rune
EXPECT_FALSE(r.isValid());
}
}
```
|
/content/code_sandbox/test/unit/aztec/AZDetectorTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 15,758
|
```unknown
Thanks to Enrique G-S for contributing many of the EAN-13 test images.
```
|
/content/code_sandbox/test/samples/README
|
unknown
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 18
|
```c++
/*
*/
#include <stdint.h>
#include <stddef.h>
#include "BitArray.h"
#include "Error.h"
#include "oned/ODDataBarExpandedBitDecoder.h"
using namespace ZXing;
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
{
if (size < 2)
return 0;
BitArray bits;
for (size_t i = 0; i < size; ++i)
bits.appendBits(data[i], 8);
try {
OneD::DataBar::DecodeExpandedBits(bits);
} catch (std::out_of_range) {
} catch (Error) {
}
return 0;
}
```
|
/content/code_sandbox/test/fuzz/fuzzDBEDecoder.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 148
|
```c++
/*
*/
#include "BitMatrixIO.h"
#include "ByteArray.h"
#include "datamatrix/DMBitLayout.h"
#include "gtest/gtest.h"
#include <algorithm>
#include <iterator>
#include <sstream>
using namespace ZXing;
using namespace ZXing::DataMatrix;
namespace {
ByteArray Unvisualize(const char* visualized) {
std::istringstream input(visualized);
ByteArray result;
std::copy(std::istream_iterator<int>(input), std::istream_iterator<int>(), std::back_inserter(result));
return result;
}
}
TEST(DMPlacementTest, Placement)
{
auto codewords = Unvisualize("66 74 78 66 74 78 129 56 35 102 192 96 226 100 156 1 107 221"); //"AIMAIM" encoded
auto matrix = BitMatrixFromCodewords(codewords, 12, 12);
std::string expected =
"011100001111\n"
"001010101000\n"
"010001010100\n"
"001010100010\n"
"000111000100\n"
"011000010100\n"
"000100001101\n"
"011000010000\n"
"001100001101\n"
"100010010111\n"
"011101011010\n"
"001011001010\n";
EXPECT_EQ(expected, ToString(matrix, '1', '0', false));
}
```
|
/content/code_sandbox/test/unit/datamatrix/DMPlacementTest.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 330
|
```c++
/*
*/
#include "ReadBarcode.h"
#include <csignal>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
using namespace ZXing;
uint64_t Expand(uint8_t b)
{
uint64_t shift = 0x0000040810204081ul; // bits set: 0, 7, 14, 21, 28, 35, 42
uint64_t mask = 0x0001010101010101ul; // bits set: 0, 8, 16, 24, 32, 40, 48
return ((uint64_t)(b & 127) * shift & mask) | (uint64_t)(b & 128) << 49;
}
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
{
if (size < 3)
return 0;
static auto opts = ReaderOptions()
.setFormats(BarcodeFormat::MatrixCodes)
.setBinarizer(Binarizer::BoolCast)
.setReturnErrors(true)
.setTryInvert(false)
.setTryRotate(false);
int ratio = data[0] + 1;
int nBits = (size - 1) * 8;
int width = std::clamp(nBits * ratio / 256, 1, nBits);
int height = std::clamp(nBits / width, 1, nBits);
assert(width * height <= nBits);
ByteArray buffer(nBits);
for (size_t i = 1; i < size; ++i)
*reinterpret_cast<uint64_t*>(&buffer[(i - 1) * 8]) = Expand(data[i]);
#ifdef PRINT_DEBUG
printf("s: %zu, r: %d, n: %d -> %d x %d\n", size, ratio, nBits, width, height);
#endif
auto image = ImageView(buffer.data(), width, height, ImageFormat::Lum);
auto res = ReadBarcodes(image, opts);
#ifdef PRINT_DEBUG
for (const auto& r : res)
printf("%s: %s / %s\n", ToString(r.format()).c_str(), r.text().c_str(), ToString(r.error()).c_str());
#endif
static int detectedSybols = 0;
detectedSybols += Size(res);
if (!res.empty() && detectedSybols % 100 == 0)
printf("detected barcode symbols: %d\n", detectedSybols);
return 0;
}
```
|
/content/code_sandbox/test/fuzz/fuzzReadMatrix.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 538
|
```c++
/*
*/
#include "BitArray.h"
#include "ByteArray.h"
#include "DecoderResult.h"
#include "qrcode/QRErrorCorrectionLevel.h"
#include "qrcode/QRVersion.h"
#include "pdf417/PDFDecoder.h"
#include <algorithm>
#include <cstddef>
#include <cstdint>
using namespace ZXing;
namespace ZXing::Aztec {
DecoderResult Decode(const BitArray& bits);
}
namespace ZXing::DataMatrix::DecodedBitStreamParser {
DecoderResult Decode(ByteArray&& bytes, const bool isDMRE);
}
namespace ZXing::QRCode {
DecoderResult DecodeBitStream(ByteArray&& bytes, const Version& version, ErrorCorrectionLevel ecLevel);
}
void az(const uint8_t* data, size_t size)
{
BitArray bits;
for (size_t i = 1; i < size - 1; ++i)
bits.appendBits(data[i], 8);
bits.appendBits(data[size - 1], (data[0] & 0x7) + 1);
Aztec::Decode(bits);
}
void dm(const uint8_t* data, size_t size)
{
ByteArray ba;
ba.insert(ba.begin(), data, data + size);
try {
DataMatrix::DecodedBitStreamParser::Decode(std::move(ba), false);
} catch (...) {
}
}
void qr(const uint8_t* data, size_t size)
{
auto version = QRCode::Version::Model2(std::clamp(data[0] & 0x3F, 1, 40));
auto ecLevel = QRCode::ECLevelFromBits(data[0] >> 6);
ByteArray ba;
ba.insert(ba.begin(), data, data + size);
QRCode::DecodeBitStream(std::move(ba), *version, ecLevel);
}
void pd(const uint8_t* data, size_t size)
{
auto codewords = std::vector<int>(size / 2);
auto u16 = reinterpret_cast<const uint16_t*>(data);
for (int i = 0; i < Size(codewords); ++i)
codewords[i] = u16[i] % 929;
codewords[0] = Size(codewords);
Pdf417::Decode(codewords);
}
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
{
if (size < 3)
return 0;
az(data, size);
dm(data, size);
qr(data, size);
pd(data, size);
return 0;
}
```
|
/content/code_sandbox/test/fuzz/fuzzDecodeMatrix.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 549
|
```c++
/*
*/
#include <stdint.h>
#include <stddef.h>
#include "ByteArray.h"
#include "datamatrix/DMHighLevelEncoder.h"
using namespace ZXing;
using namespace ZXing::DataMatrix;
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
{
std::wstring txt(data, data + size);
try {
Encode(txt);
} catch (...) {
}
return 0;
}
```
|
/content/code_sandbox/test/fuzz/fuzzDMEncoder.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 96
|
```objective-c
//
#import <Foundation/Foundation.h>
#ifndef ZXIFormat_h
#define ZXIFormat_h
typedef NS_ENUM(NSInteger, ZXIFormat) {
NONE, AZTEC, CODABAR, CODE_39, CODE_93, CODE_128, DATA_BAR, DATA_BAR_EXPANDED,
DATA_MATRIX, DX_FILM_EDGE, EAN_8, EAN_13, ITF, MAXICODE, PDF_417, QR_CODE, MICRO_QR_CODE, RMQR_CODE, UPC_A, UPC_E,
LINEAR_CODES, MATRIX_CODES, ANY
};
#endif
```
|
/content/code_sandbox/wrappers/ios/Sources/Wrapper/ZXIFormat.h
|
objective-c
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 123
|
```objective-c
//
#ifndef UmbrellaHeader_h
#define UmbrellaHeader_h
#import "Reader/ZXIBarcodeReader.h"
#import "Reader/ZXIResult.h"
#import "Reader/ZXIPosition.h"
#import "Reader/ZXIPoint.h"
#import "Reader/ZXIGTIN.h"
#import "Reader/ZXIReaderOptions.h"
#import "Writer/ZXIWriterOptions.h"
#import "Writer/ZXIBarcodeWriter.h"
#import "ZXIErrors.h"
#import "ZXIFormat.h"
#endif
```
|
/content/code_sandbox/wrappers/ios/Sources/Wrapper/UmbrellaHeader.h
|
objective-c
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 106
|
```objective-c
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
#define ZXIErrorDomain @"ZXIErrorDomain"
typedef NS_ENUM(NSInteger, ZXIBarcodeReaderError) {
ZXIReaderError,
};
typedef NS_ENUM(NSInteger, ZXIBarcodeWriterError) {
ZXIWriterError,
};
void SetNSError(NSError *__autoreleasing _Nullable* error, NSInteger code, const char* message);
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/wrappers/ios/Sources/Wrapper/ZXIErrors.h
|
objective-c
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 93
|
```c++
/*
*/
#include <stdint.h>
#include <stddef.h>
#include "oned/ODMultiUPCEANReader.h"
#include "oned/ODCode39Reader.h"
#include "oned/ODCode93Reader.h"
#include "oned/ODCode128Reader.h"
#include "oned/ODDataBarReader.h"
#include "oned/ODDataBarExpandedReader.h"
#include "oned/ODDXFilmEdgeReader.h"
#include "oned/ODITFReader.h"
#include "oned/ODCodabarReader.h"
#include "ReaderOptions.h"
#include "Barcode.h"
using namespace ZXing;
using namespace ZXing::OneD;
static std::vector<std::unique_ptr<RowReader>> readers;
bool init()
{
static ReaderOptions opts;
opts.setReturnErrors(true);
readers.emplace_back(new MultiUPCEANReader(opts));
readers.emplace_back(new Code39Reader(opts));
readers.emplace_back(new Code93Reader(opts));
readers.emplace_back(new Code128Reader(opts));
readers.emplace_back(new ITFReader(opts));
readers.emplace_back(new CodabarReader(opts));
readers.emplace_back(new DataBarReader(opts));
readers.emplace_back(new DataBarExpandedReader(opts));
readers.emplace_back(new DXFilmEdgeReader(opts));
return true;
}
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
{
if (size < 1)
return 0;
static bool inited [[maybe_unused]] = init();
std::vector<std::unique_ptr<RowReader::DecodingState>> decodingState(readers.size());
PatternRow row(size * 2 + 1);
for (size_t i = 0; i < size; ++i){
auto v = data[i];
row[i * 2 + 0] = (v & 0xf) + 1;
row[i * 2 + 1] = (v >> 4) + 1;
}
row.back() = 0;
for (size_t r = 0; r < readers.size(); ++r) {
PatternView next(row);
while (next.isValid()) {
readers[r]->decodePattern(0, next, decodingState[r]);
// make sure we make progress and we start the next try on a bar
next.shift(2 - (next.index() % 2));
next.extend();
}
}
return 0;
}
```
|
/content/code_sandbox/test/fuzz/fuzzReadLinear.cpp
|
c++
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 506
|
```unknown
module ZXingCpp {
umbrella header "UmbrellaHeader.h"
export *
module * { export * }
}
```
|
/content/code_sandbox/wrappers/ios/Sources/Wrapper/module.modulemap
|
unknown
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 27
|
```objective-c
//
#import <Foundation/Foundation.h>
#import "BarcodeFormat.h"
#import "ZXIFormat.h"
NS_ASSUME_NONNULL_BEGIN
ZXing::BarcodeFormat BarcodeFormatFromZXIFormat(ZXIFormat format);
ZXIFormat ZXIFormatFromBarcodeFormat(ZXing::BarcodeFormat format);
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/wrappers/ios/Sources/Wrapper/ZXIFormatHelper.h
|
objective-c
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 64
|
```xml
//
#import "ZXIErrors.h"
void SetNSError(NSError *__autoreleasing _Nullable* error,
NSInteger code,
const char* message) {
if (error == nil) {
return;
}
NSString *errorDescription = @"Unknown C++ error";
if (message && strlen(message) > 0) {
errorDescription = [NSString stringWithUTF8String: message];
if (errorDescription == nil) {
errorDescription = [NSString stringWithCString: message
encoding: NSASCIIStringEncoding];
}
}
NSDictionary *userInfo = @{ NSLocalizedDescriptionKey: errorDescription };
*error = [NSError errorWithDomain:ZXIErrorDomain
code:code
userInfo:userInfo];
}
```
|
/content/code_sandbox/wrappers/ios/Sources/Wrapper/ZXIErrors.mm
|
xml
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 157
|
```objective-c
//
#import <Foundation/Foundation.h>
#import <CoreGraphics/CoreGraphics.h>
#import <CoreImage/CoreImage.h>
#import "ZXIResult.h"
#import "ZXIReaderOptions.h"
NS_ASSUME_NONNULL_BEGIN
@interface ZXIBarcodeReader : NSObject
@property(nonatomic, strong) ZXIReaderOptions *options;
-(instancetype)initWithOptions:(ZXIReaderOptions*)options;
-(nullable NSArray<ZXIResult *> *)readCIImage:(nonnull CIImage *)image
error:(NSError *__autoreleasing _Nullable *)error;
-(nullable NSArray<ZXIResult *> *)readCGImage:(nonnull CGImageRef)image
error:(NSError *__autoreleasing _Nullable *)error;
-(nullable NSArray<ZXIResult *> *)readCVPixelBuffer:(nonnull CVPixelBufferRef)pixelBuffer
error:(NSError *__autoreleasing _Nullable *)error;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/wrappers/ios/Sources/Wrapper/Reader/ZXIBarcodeReader.h
|
objective-c
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 190
|
```objective-c
//
#import "ZXIPosition.h"
@implementation ZXIPosition
- (instancetype)initWithTopLeft:(ZXIPoint *)topLeft
topRight:(ZXIPoint *)topRight
bottomRight:(ZXIPoint *)bottomRight
bottomLeft:(ZXIPoint *)bottomLeft {
self = [super init];
self.topLeft = topLeft;
self.topRight = topRight;
self.bottomRight = bottomRight;
self.bottomLeft = bottomLeft;
return self;
}
@end
```
|
/content/code_sandbox/wrappers/ios/Sources/Wrapper/Reader/ZXIPosition.m
|
objective-c
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 106
|
```xml
//
#import "ZXIFormatHelper.h"
ZXing::BarcodeFormat BarcodeFormatFromZXIFormat(ZXIFormat format) {
switch (format) {
case ZXIFormat::ANY:
return ZXing::BarcodeFormat::Any;
case ZXIFormat::MATRIX_CODES:
return ZXing::BarcodeFormat::MatrixCodes;
case ZXIFormat::LINEAR_CODES:
return ZXing::BarcodeFormat::LinearCodes;
case ZXIFormat::UPC_E:
return ZXing::BarcodeFormat::UPCE;
case ZXIFormat::UPC_A:
return ZXing::BarcodeFormat::UPCA;
case ZXIFormat::QR_CODE:
return ZXing::BarcodeFormat::QRCode;
case ZXIFormat::PDF_417:
return ZXing::BarcodeFormat::PDF417;
case ZXIFormat::MAXICODE:
return ZXing::BarcodeFormat::MaxiCode;
case ZXIFormat::ITF:
return ZXing::BarcodeFormat::ITF;
case ZXIFormat::EAN_13:
return ZXing::BarcodeFormat::EAN13;
case ZXIFormat::EAN_8:
return ZXing::BarcodeFormat::EAN8;
case ZXIFormat::DATA_MATRIX:
return ZXing::BarcodeFormat::DataMatrix;
case ZXIFormat::DATA_BAR_EXPANDED:
return ZXing::BarcodeFormat::DataBarExpanded;
case ZXIFormat::DATA_BAR:
return ZXing::BarcodeFormat::DataBar;
case ZXIFormat::DX_FILM_EDGE:
return ZXing::BarcodeFormat::DXFilmEdge;
case ZXIFormat::CODE_128:
return ZXing::BarcodeFormat::Code128;
case ZXIFormat::CODE_93:
return ZXing::BarcodeFormat::Code93;
case ZXIFormat::CODE_39:
return ZXing::BarcodeFormat::Code39;
case ZXIFormat::CODABAR:
return ZXing::BarcodeFormat::Codabar;
case ZXIFormat::AZTEC:
return ZXing::BarcodeFormat::Aztec;
case ZXIFormat::MICRO_QR_CODE:
return ZXing::BarcodeFormat::MicroQRCode;
case ZXIFormat::RMQR_CODE:
return ZXing::BarcodeFormat::RMQRCode;
case ZXIFormat::NONE:
return ZXing::BarcodeFormat::None;
}
NSLog(@"ZXIWrapper: Received invalid ZXIFormat, returning format: None");
return ZXing::BarcodeFormat::None;
}
ZXIFormat ZXIFormatFromBarcodeFormat(ZXing::BarcodeFormat format) {
switch (format) {
case ZXing::BarcodeFormat::None:
return ZXIFormat::NONE;
case ZXing::BarcodeFormat::Aztec:
return ZXIFormat::AZTEC;
case ZXing::BarcodeFormat::Codabar:
return ZXIFormat::CODABAR;
case ZXing::BarcodeFormat::Code39:
return ZXIFormat::CODE_39;
case ZXing::BarcodeFormat::Code93:
return ZXIFormat::CODE_93;
case ZXing::BarcodeFormat::Code128:
return ZXIFormat::CODE_128;
case ZXing::BarcodeFormat::DataBar:
return ZXIFormat::DATA_BAR;
case ZXing::BarcodeFormat::DataBarExpanded:
return ZXIFormat::DATA_BAR_EXPANDED;
case ZXing::BarcodeFormat::DataMatrix:
return ZXIFormat::DATA_MATRIX;
case ZXing::BarcodeFormat::DXFilmEdge:
return ZXIFormat::DX_FILM_EDGE;
case ZXing::BarcodeFormat::EAN8:
return ZXIFormat::EAN_8;
case ZXing::BarcodeFormat::EAN13:
return ZXIFormat::EAN_13;
case ZXing::BarcodeFormat::ITF:
return ZXIFormat::ITF;
case ZXing::BarcodeFormat::MaxiCode:
return ZXIFormat::MAXICODE;
case ZXing::BarcodeFormat::PDF417:
return ZXIFormat::PDF_417;
case ZXing::BarcodeFormat::QRCode:
return ZXIFormat::QR_CODE;
case ZXing::BarcodeFormat::UPCA:
return ZXIFormat::UPC_A;
case ZXing::BarcodeFormat::UPCE:
return ZXIFormat::UPC_E;
case ZXing::BarcodeFormat::LinearCodes:
return ZXIFormat::LINEAR_CODES;
case ZXing::BarcodeFormat::MatrixCodes:
return ZXIFormat::MATRIX_CODES;
case ZXing::BarcodeFormat::MicroQRCode:
return ZXIFormat::MICRO_QR_CODE;
case ZXing::BarcodeFormat::RMQRCode:
return ZXIFormat::RMQR_CODE;
case ZXing::BarcodeFormat::Any:
return ZXIFormat::ANY;
}
NSLog(@"ZXIWrapper: Received invalid BarcodeFormat, returning format: None");
return ZXIFormat::NONE;
}
```
|
/content/code_sandbox/wrappers/ios/Sources/Wrapper/ZXIFormatHelper.mm
|
xml
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 1,088
|
```objective-c
//
#import <Foundation/Foundation.h>
#import "ZXIPoint.h"
NS_ASSUME_NONNULL_BEGIN
@interface ZXIPosition : NSObject
@property(nonatomic, nonnull)ZXIPoint *topLeft;
@property(nonatomic, nonnull)ZXIPoint *topRight;
@property(nonatomic, nonnull)ZXIPoint *bottomRight;
@property(nonatomic, nonnull)ZXIPoint *bottomLeft;
- (instancetype)initWithTopLeft:(ZXIPoint *)topLeft
topRight:(ZXIPoint *)topRight
bottomRight:(ZXIPoint *)bottomRight
bottomLeft:(ZXIPoint *)bottomLeft;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/wrappers/ios/Sources/Wrapper/Reader/ZXIPosition.h
|
objective-c
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 133
|
```objective-c
//
#import "ZXIPoint.h"
@implementation ZXIPoint
- (instancetype)initWithX:(NSInteger)x y:(NSInteger)y {
self = [super init];
self.x = x;
self.y = y;
return self;
}
@end
```
|
/content/code_sandbox/wrappers/ios/Sources/Wrapper/Reader/ZXIPoint.m
|
objective-c
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 53
|
```objective-c
//
#import <Foundation/Foundation.h>
#import "ZXIPosition.h"
#import "Barcode.h"
NS_ASSUME_NONNULL_BEGIN
@interface ZXIPosition(Helper)
- (instancetype)initWithPosition:(ZXing::Position)position;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/wrappers/ios/Sources/Wrapper/Reader/ZXIPosition+Helper.h
|
objective-c
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 52
|
```objective-c
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface ZXIPoint : NSObject
@property(nonatomic) NSInteger x;
@property(nonatomic) NSInteger y;
- (instancetype)initWithX:(NSInteger)x y:(NSInteger)y;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/wrappers/ios/Sources/Wrapper/Reader/ZXIPoint.h
|
objective-c
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 52
|
```objective-c
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
typedef NS_ENUM(NSInteger, ZXIBinarizer) {
ZXIBinarizerLocalAverage,
ZXIBinarizerGlobalHistogram,
ZXIBinarizerFixedThreshold,
ZXIBinarizerBoolCast
};
typedef NS_ENUM(NSInteger, ZXIEanAddOnSymbol) {
ZXIEanAddOnSymbolIgnore,
ZXIEanAddOnSymbolRead,
ZXIEanAddOnSymbolRequire
};
typedef NS_ENUM(NSInteger, ZXITextMode) {
ZXITextModePlain,
ZXITextModeECI,
ZXITextModeHRI,
ZXITextModeHex,
ZXITextModeEscaped
};
@interface ZXIReaderOptions : NSObject
@property(nonatomic, strong) NSArray<NSNumber*> *formats;
@property(nonatomic) BOOL tryHarder;
@property(nonatomic) BOOL tryRotate;
@property(nonatomic) BOOL tryInvert;
@property(nonatomic) BOOL tryDownscale;
@property(nonatomic) BOOL isPure;
@property(nonatomic) ZXIBinarizer binarizer;
@property(nonatomic) NSInteger downscaleFactor;
@property(nonatomic) NSInteger downscaleThreshold;
@property(nonatomic) NSInteger minLineCount;
@property(nonatomic) NSInteger maxNumberOfSymbols;
@property(nonatomic) BOOL tryCode39ExtendedMode;
@property(nonatomic) BOOL validateCode39CheckSum;
@property(nonatomic) BOOL validateITFCheckSum;
@property(nonatomic) BOOL returnCodabarStartEnd;
@property(nonatomic) BOOL returnErrors;
@property(nonatomic) ZXIEanAddOnSymbol eanAddOnSymbol;
@property(nonatomic) ZXITextMode textMode;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/wrappers/ios/Sources/Wrapper/Reader/ZXIReaderOptions.h
|
objective-c
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 331
|
```xml
//
#import "ZXIPosition+Helper.h"
#import "ZXIPoint.h"
@implementation ZXIPosition(Helper)
-(instancetype)initWithPosition:(ZXing::Position)position {
return [self initWithTopLeft:[[ZXIPoint alloc] initWithX:position.topLeft().x y:position.topLeft().y]
topRight:[[ZXIPoint alloc] initWithX:position.topRight().x y:position.topRight().y]
bottomRight:[[ZXIPoint alloc] initWithX:position.bottomRight().x y:position.bottomRight().y]
bottomLeft:[[ZXIPoint alloc] initWithX:position.bottomLeft().x y:position.bottomLeft().y]];
}
@end
```
|
/content/code_sandbox/wrappers/ios/Sources/Wrapper/Reader/ZXIPosition+Helper.mm
|
xml
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 144
|
```objective-c
//
#import <Foundation/Foundation.h>
#import "ZXIFormat.h"
#import "ZXIPosition.h"
#import "ZXIGTIN.h"
NS_ASSUME_NONNULL_BEGIN
@interface ZXIResult : NSObject
@property(nonatomic, strong) NSString *text;
@property(nonatomic, strong) NSData *bytes;
@property(nonatomic, strong) ZXIPosition *position;
@property(nonatomic) ZXIFormat format;
@property(nonatomic) NSInteger orientation;
@property(nonatomic, strong) NSString *ecLevel;
@property(nonatomic, strong) NSString *symbologyIdentifier;
@property(nonatomic) NSInteger sequenceSize;
@property(nonatomic) NSInteger sequenceIndex;
@property(nonatomic, strong) NSString *sequenceId;
@property(nonatomic) BOOL readerInit;
@property(nonatomic) NSInteger lineCount;
@property(nonatomic, strong) ZXIGTIN *gtin;
- (instancetype)init:(NSString *)text
format:(ZXIFormat)format
bytes:(NSData *)bytes
position:(ZXIPosition *)position
orientation:(NSInteger)orientation
ecLevel:(NSString *)ecLevel
symbologyIdentifier:(NSString *)symbologyIdentifier
sequenceSize:(NSInteger)sequenceSize
sequenceIndex:(NSInteger)sequenceIndex
sequenceId:(NSString *)sequenceId
readerInit:(BOOL)readerInit
lineCount:(NSInteger)lineCount
gtin:(ZXIGTIN *)gtin;
@end
NS_ASSUME_NONNULL_END
```
|
/content/code_sandbox/wrappers/ios/Sources/Wrapper/Reader/ZXIResult.h
|
objective-c
| 2016-04-12T22:33:06
| 2024-08-15T07:35:29
|
zxing-cpp
|
zxing-cpp/zxing-cpp
| 1,205
| 282
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.