mirror of
https://github.com/zxing/zxing.git
synced 2024-11-09 20:44:03 -08:00
For 3.0.0, retire iphone/, cpp/, objc/ and remove temporary pointers in csharp/, qt/
git-svn-id: https://zxing.googlecode.com/svn/trunk@2978 59b500cc-1b3d-0410-9834-0bbf25fbcc57
This commit is contained in:
parent
00f634024c
commit
4856e86a46
6
CHANGES
6
CHANGES
|
@ -328,4 +328,8 @@
|
|||
- Barcode Scanner Android up requires Android 4 and is updated to use Android 4+ APIs
|
||||
- javase/ and zxingorg/ modules now use Java 7
|
||||
- Many small fixes and improvements
|
||||
- (Last release including cpp/ and iphone/ code)
|
||||
- (Last release including cpp/ and iphone/ code)
|
||||
|
||||
3.0.0 (??)
|
||||
|
||||
- iphone/, cpp/ and objc/ are retired
|
66
NOTICE
66
NOTICE
|
@ -18,69 +18,3 @@ Copyright 2002-2010 The Apache Software Foundation
|
|||
|
||||
This product includes software developed by
|
||||
The Apache Software Foundation (http://www.apache.org/).
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
NOTICES FOR ISO C9x compliant stdint.h for Microsoft Visual Studio
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124
|
||||
|
||||
Copyright (c) 2006-2008 Alexander Chemeris
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright notice,
|
||||
this list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
|
||||
3. The name of the author may be used to endorse or promote products
|
||||
derived from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
|
||||
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
|
||||
EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
|
||||
OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
|
||||
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
|
||||
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
NOTICES FOR LodePNG
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
Copyright (c) 2005-2013 Lode Vandevenne
|
||||
|
||||
This software is provided 'as-is', without any express or implied
|
||||
warranty. In no event will the authors be held liable for any damages
|
||||
arising from the use of this software.
|
||||
|
||||
Permission is granted to anyone to use this software for any purpose,
|
||||
including commercial applications, and to alter it and redistribute it
|
||||
freely, subject to the following restrictions:
|
||||
|
||||
1. The origin of this software must not be misrepresented; you must not
|
||||
claim that you wrote the original software. If you use this software
|
||||
in a product, an acknowledgment in the product documentation would be
|
||||
appreciated but is not required.
|
||||
|
||||
2. Altered source versions must be plainly marked as such, and must not be
|
||||
misrepresented as being the original software.
|
||||
|
||||
3. This notice may not be removed or altered from any source
|
||||
distribution.
|
||||
|
||||
--------------------------------------------------------------------------------
|
||||
NOTICES FOR C++ Big Integer Library
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
I, Matt McCutchen, the sole author of the original Big Integer
|
||||
Library, waive my copyright to it, placing it in the public domain.
|
||||
The library comes with absolutely no warranty.
|
||||
|
||||
|
|
|
@ -41,14 +41,9 @@
|
|||
<exclude name="androidtest/libs/**"/>
|
||||
<include name="core/**"/>
|
||||
<exclude name="core/src/test/resources/**"/> <!-- included separately below -->
|
||||
<include name="cpp/**"/>
|
||||
<include name="csharp/**"/>
|
||||
<include name="glass-mirror/**"/>
|
||||
<include name="iphone/**"/>
|
||||
<include name="javase/**"/>
|
||||
<include name="jruby/**"/>
|
||||
<include name="objc/**"/>
|
||||
<include name="qt/**"/>
|
||||
<include name="zxing.appspot.com/**"/>
|
||||
<include name="zxingorg/**"/>
|
||||
<exclude name="**/private/**"/>
|
||||
|
|
|
@ -1,3 +0,0 @@
|
|||
set history save on
|
||||
b __cxa_throw
|
||||
r
|
7
cpp/.gitignore
vendored
7
cpp/.gitignore
vendored
|
@ -1,7 +0,0 @@
|
|||
/build
|
||||
/.sconsign.dblite
|
||||
xcuserdata
|
||||
callgrind.out.*
|
||||
contents.xcworkspacedata
|
||||
*.pyc
|
||||
/.rbenv-version
|
|
@ -1,5 +0,0 @@
|
|||
testout
|
||||
build
|
||||
report.html
|
||||
.sconsign.dblite
|
||||
|
|
@ -1,94 +0,0 @@
|
|||
{
|
||||
dlsym
|
||||
Memcheck:Value8
|
||||
fun:_simple_salloc
|
||||
fun:_ZN4dyld9mkstringfEPKcz
|
||||
|
||||
}
|
||||
{
|
||||
dlsym
|
||||
Memcheck:Cond
|
||||
fun:_ZN4dyld9mkstringfEPKcz
|
||||
}
|
||||
|
||||
{
|
||||
osx
|
||||
Memcheck:Leak
|
||||
fun:malloc_zone_malloc
|
||||
fun:recursive_mutex_init
|
||||
fun:_objc_init
|
||||
fun:libSystem_initializer
|
||||
}
|
||||
|
||||
{
|
||||
throws
|
||||
Memcheck:Leak
|
||||
fun:calloc
|
||||
fun:__cxa_get_globals
|
||||
fun:__cxa_throw
|
||||
}
|
||||
|
||||
{
|
||||
osx
|
||||
Memcheck:Leak
|
||||
fun:malloc_zone_calloc
|
||||
...
|
||||
fun:map_images
|
||||
}
|
||||
|
||||
{
|
||||
c++
|
||||
Memcheck:Leak
|
||||
...
|
||||
fun:__cxa_get_globals
|
||||
}
|
||||
|
||||
{
|
||||
stdio
|
||||
Memcheck:Leak
|
||||
...
|
||||
fun:sprintf
|
||||
}
|
||||
|
||||
{
|
||||
objc
|
||||
Memcheck:Leak
|
||||
...
|
||||
fun:prepareForMethodLookup
|
||||
fun:lookUpMethod
|
||||
}
|
||||
|
||||
{
|
||||
os
|
||||
Memcheck:Leak
|
||||
...
|
||||
fun:dlopen
|
||||
}
|
||||
|
||||
{
|
||||
osx
|
||||
Memcheck:Leak
|
||||
...
|
||||
fun:map_images
|
||||
}
|
||||
|
||||
{
|
||||
at_exit
|
||||
Memcheck:Leak
|
||||
...
|
||||
fun:atexit_register
|
||||
}
|
||||
|
||||
{
|
||||
osx
|
||||
Memcheck:Value8
|
||||
...
|
||||
fun:dlsym
|
||||
}
|
||||
|
||||
{
|
||||
osx
|
||||
Memcheck:Cond
|
||||
...
|
||||
fun:dlsym
|
||||
}
|
|
@ -1 +0,0 @@
|
|||
--memcheck:leak-check=full --memcheck:suppressions=.valgrind.supp --memcheck:gen-suppressions=all
|
|
@ -1,84 +0,0 @@
|
|||
#
|
||||
# CMake listfile to specify the build process, see:
|
||||
# http://www.cmake.org/cmake/help/documentation.html
|
||||
#
|
||||
project(zxing)
|
||||
cmake_minimum_required(VERSION 2.8.0)
|
||||
|
||||
set(CMAKE_LIBRARY_PATH /opt/local/lib ${CMAKE_LIBRARY_PATH})
|
||||
|
||||
# Check for polluted source tree.
|
||||
if(EXISTS ${CMAKE_SOURCE_DIR}/CMakeCache.txt OR
|
||||
EXISTS ${CMAKE_SOURCE_DIR}/CMakeFiles)
|
||||
message(FATAL_ERROR
|
||||
"Source directory is polluted:"
|
||||
"\n * remove CMakeCache.txt"
|
||||
"\n * remove CMakeFiles directory")
|
||||
endif()
|
||||
|
||||
# Suppress in-source builds.
|
||||
if(${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_BINARY_DIR})
|
||||
message(FATAL_ERROR
|
||||
"CMake generation is not allowed within the source directory:"
|
||||
"\n * mkdir build"
|
||||
"\n * cd build"
|
||||
"\n * Unix-like: cmake -G \"Unix Makefiles\" .."
|
||||
"\n * Windows: cmake -G \"Visual Studio 10\" ..")
|
||||
endif()
|
||||
|
||||
# Adjust CMake's module path.
|
||||
set(CMAKE_MODULE_PATH ${CMAKE_SOURCE_DIR}/cmake/)
|
||||
|
||||
# Suppress MSVC CRT warnings.
|
||||
if(MSVC)
|
||||
add_definitions(-D_CRT_SECURE_NO_WARNINGS)
|
||||
add_definitions(/Za)
|
||||
endif()
|
||||
|
||||
# Add libzxing library.
|
||||
file(GLOB_RECURSE LIBZXING_FILES
|
||||
"./core/src/*.cpp"
|
||||
"./core/src/*.h"
|
||||
"./core/src/*.cc"
|
||||
"./core/src/*.hh"
|
||||
)
|
||||
if(WIN32)
|
||||
file(GLOB LIBZXING_WIN32_FILES
|
||||
"./core/lib/win32/*.c"
|
||||
"./core/lib/win32/*.h"
|
||||
)
|
||||
set(LIBZXING_FILES ${LIBZXING_FILES} ${LIBZXING_WIN32_FILES})
|
||||
include_directories(SYSTEM "./core/lib/win32/")
|
||||
endif()
|
||||
include_directories("./core/src/")
|
||||
add_library(libzxing STATIC ${LIBZXING_FILES})
|
||||
set_target_properties(libzxing PROPERTIES PREFIX "")
|
||||
find_package(Iconv)
|
||||
if(ICONV_FOUND)
|
||||
include_directories(${ICONV_INCLUDE_DIR})
|
||||
target_link_libraries(libzxing ${ICONV_LIBRARIES})
|
||||
else()
|
||||
add_definitions(-DNO_ICONV=1)
|
||||
endif()
|
||||
|
||||
# Add cli executable.
|
||||
file(GLOB_RECURSE ZXING_FILES
|
||||
"./cli/src/*.cpp"
|
||||
"./cli/src/*.h"
|
||||
)
|
||||
add_executable(zxing ${ZXING_FILES})
|
||||
target_link_libraries(zxing libzxing)
|
||||
|
||||
# Add testrunner executable.
|
||||
find_package(CPPUNIT)
|
||||
if(CPPUNIT_FOUND)
|
||||
file(GLOB_RECURSE TESTRUNNER_FILES
|
||||
"./core/tests/src/*.cpp"
|
||||
"./core/tests/src/*.h"
|
||||
)
|
||||
add_executable(testrunner ${TESTRUNNER_FILES})
|
||||
include_directories(${CPPUNIT_INCLUDE_DIR})
|
||||
target_link_libraries(testrunner libzxing ${CPPUNIT_LIBRARIES})
|
||||
else()
|
||||
message(WARNING "Not building testrunner, because CppUnit is missing")
|
||||
endif()
|
|
@ -1,67 +0,0 @@
|
|||
# ZXing C++ Port
|
||||
|
||||
This is a manual port of ZXing to C++. It has been tested on Linux, Mac OS X and Windows.
|
||||
|
||||
## Building using SCons
|
||||
|
||||
SCons is a build tool written in Python. You'll need to have Python
|
||||
installed, but scons installation is optional: a run time copy of
|
||||
SCons (called `scons-local`) is included. To use the included copy,
|
||||
replace `scons` with `python scons/scons.py` in the instructions below.
|
||||
|
||||
To build the library only:
|
||||
|
||||
1. Install libiconv (optional; included in many operating systems)
|
||||
2. `cd` to the `cpp` folder
|
||||
3. Run `scons lib`
|
||||
|
||||
To build the command line utility utility:
|
||||
|
||||
1. Run `scons zxing`
|
||||
2. Run `build/zxing` for a command line reference
|
||||
|
||||
To build the unit tests (optional):
|
||||
|
||||
1. Install CppUnit (`libcppunit-dev` on Ubuntu)
|
||||
2. Run `scons tests`
|
||||
3. Run `build/testrunner`
|
||||
|
||||
To clean:
|
||||
|
||||
1. Run `scons -c all`
|
||||
|
||||
# Building using CMake
|
||||
|
||||
CMake is a tool, that generates native makefiles and workspaces. It
|
||||
integrates well with a number of IDEs including Qt Creator and Visual
|
||||
Studio.
|
||||
|
||||
Usage with Qt Creator:
|
||||
|
||||
1. Open `CMakeLists.txt` as new project
|
||||
2. Specify command line arguments (see below) and press _Finish_
|
||||
|
||||
Usage with Makefiles, Visual Studio, etc. (see `cmake --help` for a complete list of generators):
|
||||
|
||||
1. `cd` to `cpp/build`
|
||||
3. Unix: run `cmake -G "Unix Makefiles" ..`
|
||||
3. Windows: run `cmake -G "Visual Studio 10" ..`
|
||||
|
||||
You can switch between build modes by specifying:
|
||||
|
||||
- `-DCMAKE_BUILD_TYPE=Debug` or
|
||||
- `-DCMAKE_BUILD_TYPE=Release`
|
||||
|
||||
# Development tips
|
||||
|
||||
To profile the code (very useful to optimize the code):
|
||||
|
||||
1. Install Valgrind
|
||||
2. Run `valgrind --tool=callgrind build/zxing - path/to/test/data/*.jpg > report.html`
|
||||
3. Analyze output using KCachegrind
|
||||
|
||||
To run the black box tests and check for changes:
|
||||
|
||||
1. Build `zxing-img`, e.g., scons zxing
|
||||
2. Run the tests: `bash blackboxtest.sh 2>&1 | tee bb.results`
|
||||
3. Diff them with the known results: `diff bb.results blackboxtest.results`
|
|
@ -1,87 +0,0 @@
|
|||
# -*- python -*-
|
||||
|
||||
#
|
||||
# SConscript file to specify the build process, see:
|
||||
# http://scons.org/doc/production/HTML/scons-man.html
|
||||
#
|
||||
Decider('MD5')
|
||||
import platform
|
||||
import fnmatch
|
||||
import os
|
||||
|
||||
vars = Variables()
|
||||
vars.Add(BoolVariable('DEBUG', 'Set to disable optimizations', True))
|
||||
vars.Add(BoolVariable('PIC', 'Set to 1 for to always generate PIC code', False))
|
||||
env = Environment(variables = vars)
|
||||
#env.Replace(CXX = 'clang++')
|
||||
|
||||
compile_options = {}
|
||||
if platform.system() is 'Windows':
|
||||
compile_options['CXXFLAGS'] = '-D_CRT_SECURE_NO_WARNINGS /fp:fast /EHsc'
|
||||
else:
|
||||
# Force ANSI (C++98) to ensure compatibility with MSVC.
|
||||
cxxflags = ['-ansi -pedantic']
|
||||
if env['DEBUG']:
|
||||
#compile_options['CPPDEFINES'] = '-DDEBUG'
|
||||
cxxflags.append('-O0 -g3 -ggdb')
|
||||
cxxflags.append('-Wall -Wextra -Werror')
|
||||
# -Werror
|
||||
else:
|
||||
cxxflags.append('-Os -g3 -ggdb -Wall -Wextra')
|
||||
if env['PIC']:
|
||||
cxxflags.append('-fPIC')
|
||||
compile_options['CXXFLAGS'] = ' '.join(cxxflags)
|
||||
compile_options['LINKFLAGS'] = '-ldl -L/usr/lib -L/opt/local/lib -L/usr/local/lib'
|
||||
|
||||
def all_files(dir, ext='.cpp', level=6):
|
||||
files = []
|
||||
for i in range(1, level):
|
||||
files += Glob(dir + ('/*' * i) + ext)
|
||||
return files
|
||||
|
||||
def all_libs(name, dir):
|
||||
matches = []
|
||||
for root, dirnames, filenames in os.walk(dir):
|
||||
for filename in fnmatch.filter(filenames, name):
|
||||
matches.append(os.path.join(root, filename))
|
||||
return matches
|
||||
|
||||
# Setup libiconv, if possible
|
||||
libiconv_include = []
|
||||
libiconv_libs = []
|
||||
if all_libs('libiconv.*', '/opt/local/lib'):
|
||||
libiconv_include.append('/opt/local/include/')
|
||||
libiconv_libs.append('iconv')
|
||||
else:
|
||||
if all_libs('libiconv.*', '/usr/lib'):
|
||||
libiconv_libs.append('iconv')
|
||||
|
||||
# Add libzxing library.
|
||||
libzxing_files = all_files('core/src')+all_files('core/src', '.cc')
|
||||
libzxing_include = ['core/src']
|
||||
if platform.system() is 'Windows':
|
||||
libzxing_files += all_files('core/src/win32')
|
||||
libzxing_include += ['core/src/win32']
|
||||
libzxing = env.Library('zxing', source=libzxing_files,
|
||||
CPPPATH=libzxing_include + libiconv_libs, **compile_options)
|
||||
|
||||
# Add cli.
|
||||
zxing_files = all_files('cli/src')
|
||||
zxing = env.Program('zxing', zxing_files,
|
||||
CPPPATH=libzxing_include,
|
||||
LIBS=libzxing + libiconv_libs, **compile_options)
|
||||
|
||||
# Setup CPPUnit.
|
||||
cppunit_include = ['/opt/local/include/']
|
||||
cppunit_libs = ['cppunit']
|
||||
|
||||
# Add testrunner program.
|
||||
test_files = all_files('core/tests/src')
|
||||
test = env.Program('testrunner', test_files,
|
||||
CPPPATH=libzxing_include + cppunit_include,
|
||||
LIBS=libzxing + cppunit_libs, **compile_options)
|
||||
|
||||
# Setup some aliases.
|
||||
Alias('lib', libzxing)
|
||||
Alias('zxing', zxing)
|
||||
Alias('tests', test)
|
|
@ -1,7 +0,0 @@
|
|||
SConscript('SConscript', variant_dir='build')
|
||||
|
||||
Alias('all', ['lib', 'tests', 'zxing'])
|
||||
Default('all')
|
||||
|
||||
# Remove build folder on "scons -c all"
|
||||
Clean('all', 'build')
|
File diff suppressed because it is too large
Load diff
|
@ -1,45 +0,0 @@
|
|||
#!/usr/bin/env bash
|
||||
|
||||
blackboxpath="../core/test/data/blackbox"
|
||||
|
||||
if [ "$*" != "" ]; then
|
||||
formats="$*"
|
||||
else
|
||||
formats="ean13 ean8 upce upca qrcode aztec"
|
||||
fi
|
||||
|
||||
passed=0;
|
||||
failed=0;
|
||||
oldcat="";
|
||||
|
||||
for format in $formats; do
|
||||
for pic in `ls ${blackboxpath}/${format}-*/*.{jpg,JPG,gif,GIF,png,PNG} 2>/dev/null | sort -n`; do
|
||||
category=${pic%/*};
|
||||
category=${category##*/};
|
||||
if [ "$oldcat" != "$category" ]; then
|
||||
echo "***** $oldcat finished - $passed of $((passed+failed)) passed **** ***** ******* ***** *********************"
|
||||
oldcat=$category;
|
||||
passed=0;
|
||||
failed=0;
|
||||
fi
|
||||
echo -n "Processing: $pic ... "
|
||||
tmp="${pic}"
|
||||
tmp="${tmp%JPG}";
|
||||
tmp="${tmp%jpg}";
|
||||
tmp="${tmp%gif}";
|
||||
tmp="${tmp%GIF}";
|
||||
tmp="${tmp%png}";
|
||||
tmp="${tmp%PNG}";
|
||||
txt="${tmp}txt";
|
||||
expected=`cat "$txt"`;
|
||||
actual=`$VALGRIND build/zxing $pic`;
|
||||
if [ "$expected" == "$actual" ]; then
|
||||
echo "passed."
|
||||
passed=$((passed+1));
|
||||
else
|
||||
echo -e "FAILED\n Expected: $expected\n Detected: $actual"
|
||||
failed=$((failed+1));
|
||||
fi
|
||||
done
|
||||
done
|
||||
echo "***** $oldcat finished - $passed of $((passed+failed)) passed **** ***** ******* ***** *********************"
|
|
@ -1,112 +0,0 @@
|
|||
/*
|
||||
* Copyright 2010-2011 ZXing authors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include "ImageReaderSource.h"
|
||||
#include <zxing/common/IllegalArgumentException.h>
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
#include <cstdlib>
|
||||
#include <algorithm>
|
||||
#include "lodepng.h"
|
||||
#include "jpgd.h"
|
||||
|
||||
using std::string;
|
||||
using std::ostringstream;
|
||||
using zxing::Ref;
|
||||
using zxing::ArrayRef;
|
||||
using zxing::LuminanceSource;
|
||||
|
||||
inline char ImageReaderSource::convertPixel(char const* pixel_) const {
|
||||
unsigned char const* pixel = (unsigned char const*)pixel_;
|
||||
if (comps == 1 || comps == 2) {
|
||||
// Gray or gray+alpha
|
||||
return pixel[0];
|
||||
} if (comps == 3 || comps == 4) {
|
||||
// Red, Green, Blue, (Alpha)
|
||||
// We assume 16 bit values here
|
||||
// 0x200 = 1<<9, half an lsb of the result to force rounding
|
||||
return (char)((306 * (int)pixel[0] + 601 * (int)pixel[1] +
|
||||
117 * (int)pixel[2] + 0x200) >> 10);
|
||||
} else {
|
||||
throw zxing::IllegalArgumentException("Unexpected image depth");
|
||||
}
|
||||
}
|
||||
|
||||
ImageReaderSource::ImageReaderSource(ArrayRef<char> image_, int width, int height, int comps_)
|
||||
: Super(width, height), image(image_), comps(comps_) {}
|
||||
|
||||
Ref<LuminanceSource> ImageReaderSource::create(string const& filename) {
|
||||
string extension = filename.substr(filename.find_last_of(".") + 1);
|
||||
std::transform(extension.begin(), extension.end(), extension.begin(), ::tolower);
|
||||
int width, height;
|
||||
int comps = 0;
|
||||
zxing::ArrayRef<char> image;
|
||||
if (extension == "png") {
|
||||
std::vector<unsigned char> out;
|
||||
|
||||
{ unsigned w, h;
|
||||
unsigned error = lodepng::decode(out, w, h, filename);
|
||||
if (error) {
|
||||
ostringstream msg;
|
||||
msg << "Error while loading '" << lodepng_error_text(error) << "'";
|
||||
throw zxing::IllegalArgumentException(msg.str().c_str());
|
||||
}
|
||||
width = w;
|
||||
height = h;
|
||||
}
|
||||
|
||||
comps = 4;
|
||||
image = zxing::ArrayRef<char>(4 * width * height);
|
||||
memcpy(&image[0], &out[0], image->size());
|
||||
} else if (extension == "jpg" || extension == "jpeg") {
|
||||
char *buffer = reinterpret_cast<char*>(jpgd::decompress_jpeg_image_from_file(
|
||||
filename.c_str(), &width, &height, &comps, 4));
|
||||
image = zxing::ArrayRef<char>(buffer, 4 * width * height);
|
||||
}
|
||||
if (!image) {
|
||||
ostringstream msg;
|
||||
msg << "Loading \"" << filename << "\" failed.";
|
||||
throw zxing::IllegalArgumentException(msg.str().c_str());
|
||||
}
|
||||
|
||||
return Ref<LuminanceSource>(new ImageReaderSource(image, width, height, comps));
|
||||
}
|
||||
|
||||
zxing::ArrayRef<char> ImageReaderSource::getRow(int y, zxing::ArrayRef<char> row) const {
|
||||
const char* pixelRow = &image[0] + y * getWidth() * 4;
|
||||
if (!row) {
|
||||
row = zxing::ArrayRef<char>(getWidth());
|
||||
}
|
||||
for (int x = 0; x < getWidth(); x++) {
|
||||
row[x] = convertPixel(pixelRow + (x * 4));
|
||||
}
|
||||
return row;
|
||||
}
|
||||
|
||||
/** This is a more efficient implementation. */
|
||||
zxing::ArrayRef<char> ImageReaderSource::getMatrix() const {
|
||||
const char* p = &image[0];
|
||||
zxing::ArrayRef<char> matrix(getWidth() * getHeight());
|
||||
char* m = &matrix[0];
|
||||
for (int y = 0; y < getHeight(); y++) {
|
||||
for (int x = 0; x < getWidth(); x++) {
|
||||
*m = convertPixel(p);
|
||||
m++;
|
||||
p += 4;
|
||||
}
|
||||
}
|
||||
return matrix;
|
||||
}
|
|
@ -1,40 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
#ifndef __IMAGE_READER_SOURCE_H_
|
||||
#define __IMAGE_READER_SOURCE_H_
|
||||
/*
|
||||
* Copyright 2010-2011 ZXing authors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/LuminanceSource.h>
|
||||
|
||||
class ImageReaderSource : public zxing::LuminanceSource {
|
||||
private:
|
||||
typedef LuminanceSource Super;
|
||||
|
||||
const zxing::ArrayRef<char> image;
|
||||
const int comps;
|
||||
|
||||
char convertPixel(const char* pixel) const;
|
||||
|
||||
public:
|
||||
static zxing::Ref<LuminanceSource> create(std::string const& filename);
|
||||
|
||||
ImageReaderSource(zxing::ArrayRef<char> image, int width, int height, int comps);
|
||||
|
||||
zxing::ArrayRef<char> getRow(int y, zxing::ArrayRef<char> row) const;
|
||||
zxing::ArrayRef<char> getMatrix() const;
|
||||
};
|
||||
|
||||
#endif /* __IMAGE_READER_SOURCE_H_ */
|
3174
cpp/cli/src/jpgd.cpp
3174
cpp/cli/src/jpgd.cpp
File diff suppressed because it is too large
Load diff
|
@ -1,319 +0,0 @@
|
|||
// jpgd.h - C++ class for JPEG decompression.
|
||||
// Public domain, Rich Geldreich <richgel99@gmail.com>
|
||||
#ifndef JPEG_DECODER_H
|
||||
#define JPEG_DECODER_H
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include <setjmp.h>
|
||||
|
||||
#ifdef _MSC_VER
|
||||
#define JPGD_NORETURN __declspec(noreturn)
|
||||
#elif defined(__GNUC__)
|
||||
#define JPGD_NORETURN __attribute__ ((noreturn))
|
||||
#else
|
||||
#define JPGD_NORETURN
|
||||
#endif
|
||||
|
||||
namespace jpgd
|
||||
{
|
||||
typedef unsigned char uint8;
|
||||
typedef signed short int16;
|
||||
typedef unsigned short uint16;
|
||||
typedef unsigned int uint;
|
||||
typedef signed int int32;
|
||||
|
||||
// Loads a JPEG image from a memory buffer or a file.
|
||||
// req_comps can be 1 (grayscale), 3 (RGB), or 4 (RGBA).
|
||||
// On return, width/height will be set to the image's dimensions, and actual_comps will be set to the either 1 (grayscale) or 3 (RGB).
|
||||
// Notes: For more control over where and how the source data is read, see the decompress_jpeg_image_from_stream() function below, or call the jpeg_decoder class directly.
|
||||
// Requesting a 8 or 32bpp image is currently a little faster than 24bpp because the jpeg_decoder class itself currently always unpacks to either 8 or 32bpp.
|
||||
unsigned char *decompress_jpeg_image_from_memory(const unsigned char *pSrc_data, int src_data_size, int *width, int *height, int *actual_comps, int req_comps);
|
||||
unsigned char *decompress_jpeg_image_from_file(const char *pSrc_filename, int *width, int *height, int *actual_comps, int req_comps);
|
||||
|
||||
// Success/failure error codes.
|
||||
enum jpgd_status
|
||||
{
|
||||
JPGD_SUCCESS = 0, JPGD_FAILED = -1, JPGD_DONE = 1,
|
||||
JPGD_BAD_DHT_COUNTS = -256, JPGD_BAD_DHT_INDEX, JPGD_BAD_DHT_MARKER, JPGD_BAD_DQT_MARKER, JPGD_BAD_DQT_TABLE,
|
||||
JPGD_BAD_PRECISION, JPGD_BAD_HEIGHT, JPGD_BAD_WIDTH, JPGD_TOO_MANY_COMPONENTS,
|
||||
JPGD_BAD_SOF_LENGTH, JPGD_BAD_VARIABLE_MARKER, JPGD_BAD_DRI_LENGTH, JPGD_BAD_SOS_LENGTH,
|
||||
JPGD_BAD_SOS_COMP_ID, JPGD_W_EXTRA_BYTES_BEFORE_MARKER, JPGD_NO_ARITHMITIC_SUPPORT, JPGD_UNEXPECTED_MARKER,
|
||||
JPGD_NOT_JPEG, JPGD_UNSUPPORTED_MARKER, JPGD_BAD_DQT_LENGTH, JPGD_TOO_MANY_BLOCKS,
|
||||
JPGD_UNDEFINED_QUANT_TABLE, JPGD_UNDEFINED_HUFF_TABLE, JPGD_NOT_SINGLE_SCAN, JPGD_UNSUPPORTED_COLORSPACE,
|
||||
JPGD_UNSUPPORTED_SAMP_FACTORS, JPGD_DECODE_ERROR, JPGD_BAD_RESTART_MARKER, JPGD_ASSERTION_ERROR,
|
||||
JPGD_BAD_SOS_SPECTRAL, JPGD_BAD_SOS_SUCCESSIVE, JPGD_STREAM_READ, JPGD_NOTENOUGHMEM
|
||||
};
|
||||
|
||||
// Input stream interface.
|
||||
// Derive from this class to read input data from sources other than files or memory. Set m_eof_flag to true when no more data is available.
|
||||
// The decoder is rather greedy: it will keep on calling this method until its internal input buffer is full, or until the EOF flag is set.
|
||||
// It the input stream contains data after the JPEG stream's EOI (end of image) marker it will probably be pulled into the internal buffer.
|
||||
// Call the get_total_bytes_read() method to determine the actual size of the JPEG stream after successful decoding.
|
||||
class jpeg_decoder_stream
|
||||
{
|
||||
public:
|
||||
jpeg_decoder_stream() { }
|
||||
virtual ~jpeg_decoder_stream() { }
|
||||
|
||||
// The read() method is called when the internal input buffer is empty.
|
||||
// Parameters:
|
||||
// pBuf - input buffer
|
||||
// max_bytes_to_read - maximum bytes that can be written to pBuf
|
||||
// pEOF_flag - set this to true if at end of stream (no more bytes remaining)
|
||||
// Returns -1 on error, otherwise return the number of bytes actually written to the buffer (which may be 0).
|
||||
// Notes: This method will be called in a loop until you set *pEOF_flag to true or the internal buffer is full.
|
||||
virtual int read(uint8 *pBuf, int max_bytes_to_read, bool *pEOF_flag) = 0;
|
||||
};
|
||||
|
||||
// stdio FILE stream class.
|
||||
class jpeg_decoder_file_stream : public jpeg_decoder_stream
|
||||
{
|
||||
jpeg_decoder_file_stream(const jpeg_decoder_file_stream &);
|
||||
jpeg_decoder_file_stream &operator =(const jpeg_decoder_file_stream &);
|
||||
|
||||
FILE *m_pFile;
|
||||
bool m_eof_flag, m_error_flag;
|
||||
|
||||
public:
|
||||
jpeg_decoder_file_stream();
|
||||
virtual ~jpeg_decoder_file_stream();
|
||||
|
||||
bool open(const char *Pfilename);
|
||||
void close();
|
||||
|
||||
virtual int read(uint8 *pBuf, int max_bytes_to_read, bool *pEOF_flag);
|
||||
};
|
||||
|
||||
// Memory stream class.
|
||||
class jpeg_decoder_mem_stream : public jpeg_decoder_stream
|
||||
{
|
||||
const uint8 *m_pSrc_data;
|
||||
uint m_ofs, m_size;
|
||||
|
||||
public:
|
||||
jpeg_decoder_mem_stream() : m_pSrc_data(NULL), m_ofs(0), m_size(0) { }
|
||||
jpeg_decoder_mem_stream(const uint8 *pSrc_data, uint size) : m_pSrc_data(pSrc_data), m_ofs(0), m_size(size) { }
|
||||
|
||||
virtual ~jpeg_decoder_mem_stream() { }
|
||||
|
||||
bool open(const uint8 *pSrc_data, uint size);
|
||||
void close() { m_pSrc_data = NULL; m_ofs = 0; m_size = 0; }
|
||||
|
||||
virtual int read(uint8 *pBuf, int max_bytes_to_read, bool *pEOF_flag);
|
||||
};
|
||||
|
||||
// Loads JPEG file from a jpeg_decoder_stream.
|
||||
unsigned char *decompress_jpeg_image_from_stream(jpeg_decoder_stream *pStream, int *width, int *height, int *actual_comps, int req_comps);
|
||||
|
||||
enum
|
||||
{
|
||||
JPGD_IN_BUF_SIZE = 8192, JPGD_MAX_BLOCKS_PER_MCU = 10, JPGD_MAX_HUFF_TABLES = 8, JPGD_MAX_QUANT_TABLES = 4,
|
||||
JPGD_MAX_COMPONENTS = 4, JPGD_MAX_COMPS_IN_SCAN = 4, JPGD_MAX_BLOCKS_PER_ROW = 8192, JPGD_MAX_HEIGHT = 16384, JPGD_MAX_WIDTH = 16384
|
||||
};
|
||||
|
||||
typedef int16 jpgd_quant_t;
|
||||
typedef int16 jpgd_block_t;
|
||||
|
||||
class jpeg_decoder
|
||||
{
|
||||
public:
|
||||
// Call get_error_code() after constructing to determine if the stream is valid or not. You may call the get_width(), get_height(), etc.
|
||||
// methods after the constructor is called. You may then either destruct the object, or begin decoding the image by calling begin_decoding(), then decode() on each scanline.
|
||||
jpeg_decoder(jpeg_decoder_stream *pStream);
|
||||
|
||||
~jpeg_decoder();
|
||||
|
||||
// Call this method after constructing the object to begin decompression.
|
||||
// If JPGD_SUCCESS is returned you may then call decode() on each scanline.
|
||||
int begin_decoding();
|
||||
|
||||
// Returns the next scan line.
|
||||
// For grayscale images, pScan_line will point to a buffer containing 8-bit pixels (get_bytes_per_pixel() will return 1).
|
||||
// Otherwise, it will always point to a buffer containing 32-bit RGBA pixels (A will always be 255, and get_bytes_per_pixel() will return 4).
|
||||
// Returns JPGD_SUCCESS if a scan line has been returned.
|
||||
// Returns JPGD_DONE if all scan lines have been returned.
|
||||
// Returns JPGD_FAILED if an error occurred. Call get_error_code() for a more info.
|
||||
int decode(const void** pScan_line, uint* pScan_line_len);
|
||||
|
||||
inline jpgd_status get_error_code() const { return m_error_code; }
|
||||
|
||||
inline int get_width() const { return m_image_x_size; }
|
||||
inline int get_height() const { return m_image_y_size; }
|
||||
|
||||
inline int get_num_components() const { return m_comps_in_frame; }
|
||||
|
||||
inline int get_bytes_per_pixel() const { return m_dest_bytes_per_pixel; }
|
||||
inline int get_bytes_per_scan_line() const { return m_image_x_size * get_bytes_per_pixel(); }
|
||||
|
||||
// Returns the total number of bytes actually consumed by the decoder (which should equal the actual size of the JPEG file).
|
||||
inline int get_total_bytes_read() const { return m_total_bytes_read; }
|
||||
|
||||
private:
|
||||
jpeg_decoder(const jpeg_decoder &);
|
||||
jpeg_decoder &operator =(const jpeg_decoder &);
|
||||
|
||||
typedef void (*pDecode_block_func)(jpeg_decoder *, int, int, int);
|
||||
|
||||
struct huff_tables
|
||||
{
|
||||
bool ac_table;
|
||||
uint look_up[256];
|
||||
uint look_up2[256];
|
||||
uint8 code_size[256];
|
||||
uint tree[512];
|
||||
};
|
||||
|
||||
struct coeff_buf
|
||||
{
|
||||
uint8 *pData;
|
||||
int block_num_x, block_num_y;
|
||||
int block_len_x, block_len_y;
|
||||
int block_size;
|
||||
};
|
||||
|
||||
struct mem_block
|
||||
{
|
||||
mem_block *m_pNext;
|
||||
size_t m_used_count;
|
||||
size_t m_size;
|
||||
char m_data[1];
|
||||
};
|
||||
|
||||
jmp_buf m_jmp_state;
|
||||
mem_block *m_pMem_blocks;
|
||||
int m_image_x_size;
|
||||
int m_image_y_size;
|
||||
jpeg_decoder_stream *m_pStream;
|
||||
int m_progressive_flag;
|
||||
uint8 m_huff_ac[JPGD_MAX_HUFF_TABLES];
|
||||
uint8* m_huff_num[JPGD_MAX_HUFF_TABLES]; // pointer to number of Huffman codes per bit size
|
||||
uint8* m_huff_val[JPGD_MAX_HUFF_TABLES]; // pointer to Huffman codes per bit size
|
||||
jpgd_quant_t* m_quant[JPGD_MAX_QUANT_TABLES]; // pointer to quantization tables
|
||||
int m_scan_type; // Gray, Yh1v1, Yh1v2, Yh2v1, Yh2v2 (CMYK111, CMYK4114 no longer supported)
|
||||
int m_comps_in_frame; // # of components in frame
|
||||
int m_comp_h_samp[JPGD_MAX_COMPONENTS]; // component's horizontal sampling factor
|
||||
int m_comp_v_samp[JPGD_MAX_COMPONENTS]; // component's vertical sampling factor
|
||||
int m_comp_quant[JPGD_MAX_COMPONENTS]; // component's quantization table selector
|
||||
int m_comp_ident[JPGD_MAX_COMPONENTS]; // component's ID
|
||||
int m_comp_h_blocks[JPGD_MAX_COMPONENTS];
|
||||
int m_comp_v_blocks[JPGD_MAX_COMPONENTS];
|
||||
int m_comps_in_scan; // # of components in scan
|
||||
int m_comp_list[JPGD_MAX_COMPS_IN_SCAN]; // components in this scan
|
||||
int m_comp_dc_tab[JPGD_MAX_COMPONENTS]; // component's DC Huffman coding table selector
|
||||
int m_comp_ac_tab[JPGD_MAX_COMPONENTS]; // component's AC Huffman coding table selector
|
||||
int m_spectral_start; // spectral selection start
|
||||
int m_spectral_end; // spectral selection end
|
||||
int m_successive_low; // successive approximation low
|
||||
int m_successive_high; // successive approximation high
|
||||
int m_max_mcu_x_size; // MCU's max. X size in pixels
|
||||
int m_max_mcu_y_size; // MCU's max. Y size in pixels
|
||||
int m_blocks_per_mcu;
|
||||
int m_max_blocks_per_row;
|
||||
int m_mcus_per_row, m_mcus_per_col;
|
||||
int m_mcu_org[JPGD_MAX_BLOCKS_PER_MCU];
|
||||
int m_total_lines_left; // total # lines left in image
|
||||
int m_mcu_lines_left; // total # lines left in this MCU
|
||||
int m_real_dest_bytes_per_scan_line;
|
||||
int m_dest_bytes_per_scan_line; // rounded up
|
||||
int m_dest_bytes_per_pixel; // 4 (RGB) or 1 (Y)
|
||||
huff_tables* m_pHuff_tabs[JPGD_MAX_HUFF_TABLES];
|
||||
coeff_buf* m_dc_coeffs[JPGD_MAX_COMPONENTS];
|
||||
coeff_buf* m_ac_coeffs[JPGD_MAX_COMPONENTS];
|
||||
int m_eob_run;
|
||||
int m_block_y_mcu[JPGD_MAX_COMPONENTS];
|
||||
uint8* m_pIn_buf_ofs;
|
||||
int m_in_buf_left;
|
||||
int m_tem_flag;
|
||||
bool m_eof_flag;
|
||||
uint8 m_in_buf_pad_start[128];
|
||||
uint8 m_in_buf[JPGD_IN_BUF_SIZE + 128];
|
||||
uint8 m_in_buf_pad_end[128];
|
||||
int m_bits_left;
|
||||
uint m_bit_buf;
|
||||
int m_restart_interval;
|
||||
int m_restarts_left;
|
||||
int m_next_restart_num;
|
||||
int m_max_mcus_per_row;
|
||||
int m_max_blocks_per_mcu;
|
||||
int m_expanded_blocks_per_mcu;
|
||||
int m_expanded_blocks_per_row;
|
||||
int m_expanded_blocks_per_component;
|
||||
bool m_freq_domain_chroma_upsample;
|
||||
int m_max_mcus_per_col;
|
||||
uint m_last_dc_val[JPGD_MAX_COMPONENTS];
|
||||
jpgd_block_t* m_pMCU_coefficients;
|
||||
int m_mcu_block_max_zag[JPGD_MAX_BLOCKS_PER_MCU];
|
||||
uint8* m_pSample_buf;
|
||||
int m_crr[256];
|
||||
int m_cbb[256];
|
||||
int m_crg[256];
|
||||
int m_cbg[256];
|
||||
uint8* m_pScan_line_0;
|
||||
uint8* m_pScan_line_1;
|
||||
jpgd_status m_error_code;
|
||||
bool m_ready_flag;
|
||||
int m_total_bytes_read;
|
||||
|
||||
void free_all_blocks();
|
||||
JPGD_NORETURN void stop_decoding(jpgd_status status);
|
||||
void *alloc(size_t n, bool zero = false);
|
||||
void word_clear(void *p, uint16 c, uint n);
|
||||
void prep_in_buffer();
|
||||
void read_dht_marker();
|
||||
void read_dqt_marker();
|
||||
void read_sof_marker();
|
||||
void skip_variable_marker();
|
||||
void read_dri_marker();
|
||||
void read_sos_marker();
|
||||
int next_marker();
|
||||
int process_markers();
|
||||
void locate_soi_marker();
|
||||
void locate_sof_marker();
|
||||
int locate_sos_marker();
|
||||
void init(jpeg_decoder_stream * pStream);
|
||||
void create_look_ups();
|
||||
void fix_in_buffer();
|
||||
void transform_mcu(int mcu_row);
|
||||
void transform_mcu_expand(int mcu_row);
|
||||
coeff_buf* coeff_buf_open(int block_num_x, int block_num_y, int block_len_x, int block_len_y);
|
||||
inline jpgd_block_t *coeff_buf_getp(coeff_buf *cb, int block_x, int block_y);
|
||||
void load_next_row();
|
||||
void decode_next_row();
|
||||
void make_huff_table(int index, huff_tables *pH);
|
||||
void check_quant_tables();
|
||||
void check_huff_tables();
|
||||
void calc_mcu_block_order();
|
||||
int init_scan();
|
||||
void init_frame();
|
||||
void process_restart();
|
||||
void decode_scan(pDecode_block_func decode_block_func);
|
||||
void init_progressive();
|
||||
void init_sequential();
|
||||
void decode_start();
|
||||
void decode_init(jpeg_decoder_stream * pStream);
|
||||
void H2V2Convert();
|
||||
void H2V1Convert();
|
||||
void H1V2Convert();
|
||||
void H1V1Convert();
|
||||
void gray_convert();
|
||||
void expanded_convert();
|
||||
void find_eoi();
|
||||
inline uint get_char();
|
||||
inline uint get_char(bool *pPadding_flag);
|
||||
inline void stuff_char(uint8 q);
|
||||
inline uint8 get_octet();
|
||||
inline uint get_bits(int num_bits);
|
||||
inline uint get_bits_no_markers(int numbits);
|
||||
inline int huff_decode(huff_tables *pH);
|
||||
inline int huff_decode(huff_tables *pH, int& extrabits);
|
||||
static inline uint8 clamp(int i);
|
||||
static void decode_block_dc_first(jpeg_decoder *pD, int component_id, int block_x, int block_y);
|
||||
static void decode_block_dc_refine(jpeg_decoder *pD, int component_id, int block_x, int block_y);
|
||||
static void decode_block_ac_first(jpeg_decoder *pD, int component_id, int block_x, int block_y);
|
||||
static void decode_block_ac_refine(jpeg_decoder *pD, int component_id, int block_x, int block_y);
|
||||
};
|
||||
|
||||
} // namespace jpgd
|
||||
|
||||
#endif // JPEG_DECODER_H
|
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
@ -1,297 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
/*
|
||||
* Copyright 2010-2011 ZXing authors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <iostream>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
#include "ImageReaderSource.h"
|
||||
#include <zxing/common/Counted.h>
|
||||
#include <zxing/Binarizer.h>
|
||||
#include <zxing/MultiFormatReader.h>
|
||||
#include <zxing/Result.h>
|
||||
#include <zxing/ReaderException.h>
|
||||
#include <zxing/common/GlobalHistogramBinarizer.h>
|
||||
#include <zxing/common/HybridBinarizer.h>
|
||||
#include <exception>
|
||||
#include <zxing/Exception.h>
|
||||
#include <zxing/common/IllegalArgumentException.h>
|
||||
#include <zxing/BinaryBitmap.h>
|
||||
#include <zxing/DecodeHints.h>
|
||||
|
||||
#include <zxing/qrcode/QRCodeReader.h>
|
||||
#include <zxing/multi/qrcode/QRCodeMultiReader.h>
|
||||
#include <zxing/multi/ByQuadrantReader.h>
|
||||
#include <zxing/multi/MultipleBarcodeReader.h>
|
||||
#include <zxing/multi/GenericMultipleBarcodeReader.h>
|
||||
|
||||
using namespace std;
|
||||
using namespace zxing;
|
||||
using namespace zxing::multi;
|
||||
using namespace zxing::qrcode;
|
||||
|
||||
namespace {
|
||||
|
||||
bool more = false;
|
||||
bool test_mode = false;
|
||||
bool try_harder = false;
|
||||
bool search_multi = false;
|
||||
bool use_hybrid = false;
|
||||
bool use_global = false;
|
||||
bool verbose = false;
|
||||
|
||||
}
|
||||
|
||||
vector<Ref<Result> > decode(Ref<BinaryBitmap> image, DecodeHints hints) {
|
||||
Ref<Reader> reader(new MultiFormatReader);
|
||||
return vector<Ref<Result> >(1, reader->decode(image, hints));
|
||||
}
|
||||
|
||||
vector<Ref<Result> > decode_multi(Ref<BinaryBitmap> image, DecodeHints hints) {
|
||||
MultiFormatReader delegate;
|
||||
GenericMultipleBarcodeReader reader(delegate);
|
||||
return reader.decodeMultiple(image, hints);
|
||||
}
|
||||
|
||||
int read_image(Ref<LuminanceSource> source, bool hybrid, string expected) {
|
||||
vector<Ref<Result> > results;
|
||||
string cell_result;
|
||||
int res = -1;
|
||||
|
||||
try {
|
||||
Ref<Binarizer> binarizer;
|
||||
if (hybrid) {
|
||||
binarizer = new HybridBinarizer(source);
|
||||
} else {
|
||||
binarizer = new GlobalHistogramBinarizer(source);
|
||||
}
|
||||
DecodeHints hints(DecodeHints::DEFAULT_HINT);
|
||||
hints.setTryHarder(try_harder);
|
||||
Ref<BinaryBitmap> binary(new BinaryBitmap(binarizer));
|
||||
if (search_multi) {
|
||||
results = decode_multi(binary, hints);
|
||||
} else {
|
||||
results = decode(binary, hints);
|
||||
}
|
||||
res = 0;
|
||||
} catch (const ReaderException& e) {
|
||||
cell_result = "zxing::ReaderException: " + string(e.what());
|
||||
res = -2;
|
||||
} catch (const zxing::IllegalArgumentException& e) {
|
||||
cell_result = "zxing::IllegalArgumentException: " + string(e.what());
|
||||
res = -3;
|
||||
} catch (const zxing::Exception& e) {
|
||||
cell_result = "zxing::Exception: " + string(e.what());
|
||||
res = -4;
|
||||
} catch (const std::exception& e) {
|
||||
cell_result = "std::exception: " + string(e.what());
|
||||
res = -5;
|
||||
}
|
||||
|
||||
if (test_mode && results.size() == 1) {
|
||||
std::string result = results[0]->getText()->getText();
|
||||
if (expected.empty()) {
|
||||
cout << " Expected text or binary data for image missing." << endl
|
||||
<< " Detected: " << result << endl;
|
||||
res = -6;
|
||||
} else {
|
||||
if (expected.compare(result) != 0) {
|
||||
cout << " Expected: " << expected << endl
|
||||
<< " Detected: " << result << endl;
|
||||
cell_result = "data did not match";
|
||||
res = -6;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (res != 0 && (verbose || (use_global ^ use_hybrid))) {
|
||||
cout << (hybrid ? "Hybrid" : "Global")
|
||||
<< " binarizer failed: " << cell_result << endl;
|
||||
} else if (!test_mode) {
|
||||
if (verbose) {
|
||||
cout << (hybrid ? "Hybrid" : "Global")
|
||||
<< " binarizer succeeded: " << endl;
|
||||
}
|
||||
for (size_t i = 0; i < results.size(); i++) {
|
||||
if (more) {
|
||||
cout << " Format: "
|
||||
<< BarcodeFormat::barcodeFormatNames[results[i]->getBarcodeFormat()]
|
||||
<< endl;
|
||||
for (int j = 0; j < results[i]->getResultPoints()->size(); j++) {
|
||||
cout << " Point[" << j << "]: "
|
||||
<< results[i]->getResultPoints()[j]->getX() << " "
|
||||
<< results[i]->getResultPoints()[j]->getY() << endl;
|
||||
}
|
||||
}
|
||||
if (verbose) {
|
||||
cout << " ";
|
||||
}
|
||||
cout << results[i]->getText()->getText() << endl;
|
||||
}
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
string read_expected(string imagefilename) {
|
||||
string textfilename = imagefilename;
|
||||
string::size_type dotpos = textfilename.rfind(".");
|
||||
|
||||
textfilename.replace(dotpos + 1, textfilename.length() - dotpos - 1, "txt");
|
||||
ifstream textfile(textfilename.c_str(), ios::binary);
|
||||
textfilename.replace(dotpos + 1, textfilename.length() - dotpos - 1, "bin");
|
||||
ifstream binfile(textfilename.c_str(), ios::binary);
|
||||
ifstream *file = 0;
|
||||
if (textfile.is_open()) {
|
||||
file = &textfile;
|
||||
} else if (binfile.is_open()) {
|
||||
file = &binfile;
|
||||
} else {
|
||||
return std::string();
|
||||
}
|
||||
file->seekg(0, ios_base::end);
|
||||
size_t size = size_t(file->tellg());
|
||||
file->seekg(0, ios_base::beg);
|
||||
|
||||
if (size == 0) {
|
||||
return std::string();
|
||||
}
|
||||
|
||||
char* data = new char[size + 1];
|
||||
file->read(data, size);
|
||||
data[size] = '\0';
|
||||
string expected(data);
|
||||
delete[] data;
|
||||
|
||||
return expected;
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
if (argc <= 1) {
|
||||
cout << "Usage: " << argv[0] << " [OPTION]... <IMAGE>..." << endl
|
||||
<< "Read barcodes from each IMAGE file." << endl
|
||||
<< endl
|
||||
<< "Options:" << endl
|
||||
<< " (-h|--hybrid) use the hybrid binarizer (default)" << endl
|
||||
<< " (-g|--global) use the global binarizer" << endl
|
||||
<< " (-v|--verbose) chattier results printing" << endl
|
||||
<< " --more display more information about the barcode" << endl
|
||||
<< " --test-mode compare IMAGEs against text files" << endl
|
||||
<< " --try-harder spend more time to try to find a barcode" << endl
|
||||
<< " --search-multi search for more than one bar code" << endl
|
||||
<< endl
|
||||
<< "Example usage:" << endl
|
||||
<< " zxing --test-mode *.jpg" << endl
|
||||
<< endl;
|
||||
return 1;
|
||||
}
|
||||
|
||||
int total = 0;
|
||||
int gonly = 0;
|
||||
int honly = 0;
|
||||
int both = 0;
|
||||
int neither = 0;
|
||||
|
||||
for (int i = 1; i < argc; i++) {
|
||||
string filename = argv[i];
|
||||
if (filename.compare("--verbose") == 0 ||
|
||||
filename.compare("-v") == 0) {
|
||||
verbose = true;
|
||||
continue;
|
||||
}
|
||||
if (filename.compare("--hybrid") == 0 ||
|
||||
filename.compare("-h") == 0) {
|
||||
use_hybrid = true;
|
||||
continue;
|
||||
}
|
||||
if (filename.compare("--global") == 0 ||
|
||||
filename.compare("-g") == 0) {
|
||||
use_global = true;
|
||||
continue;
|
||||
}
|
||||
if (filename.compare("--more") == 0) {
|
||||
more = true;
|
||||
continue;
|
||||
}
|
||||
if (filename.compare("--test-mode") == 0) {
|
||||
test_mode = true;
|
||||
continue;
|
||||
}
|
||||
if (filename.compare("--try-harder") == 0) {
|
||||
try_harder = true;
|
||||
continue;
|
||||
}
|
||||
if (filename.compare("--search-multi") == 0){
|
||||
search_multi = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (filename.length() > 3 &&
|
||||
(filename.substr(filename.length() - 3, 3).compare("txt") == 0 ||
|
||||
filename.substr(filename.length() - 3, 3).compare("bin") == 0)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!use_global && !use_hybrid) {
|
||||
use_global = use_hybrid = true;
|
||||
}
|
||||
|
||||
if (test_mode) {
|
||||
cerr << "Testing: " << filename << endl;
|
||||
}
|
||||
|
||||
Ref<LuminanceSource> source;
|
||||
try {
|
||||
source = ImageReaderSource::create(filename);
|
||||
} catch (const zxing::IllegalArgumentException &e) {
|
||||
cerr << e.what() << " (ignoring)" << endl;
|
||||
continue;
|
||||
}
|
||||
|
||||
string expected = read_expected(filename);
|
||||
|
||||
int gresult = 1;
|
||||
int hresult = 1;
|
||||
if (use_hybrid) {
|
||||
hresult = read_image(source, true, expected);
|
||||
}
|
||||
if (use_global && (verbose || hresult != 0)) {
|
||||
gresult = read_image(source, false, expected);
|
||||
if (!verbose && gresult != 0) {
|
||||
cout << "decoding failed" << endl;
|
||||
}
|
||||
}
|
||||
gresult = gresult == 0;
|
||||
hresult = hresult == 0;
|
||||
gonly += gresult && !hresult;
|
||||
honly += hresult && !gresult;
|
||||
both += gresult && hresult;
|
||||
neither += !gresult && !hresult;
|
||||
total = total + 1;
|
||||
}
|
||||
|
||||
if (test_mode) {
|
||||
cout << endl
|
||||
<< "Summary:" << endl
|
||||
<< " " << total << " images tested total," << endl
|
||||
<< " " << (honly + both) << " passed hybrid, " << (gonly + both)
|
||||
<< " passed global, " << both << " pass both, " << endl
|
||||
<< " " << honly << " passed only hybrid, " << gonly
|
||||
<< " passed only global, " << neither << " pass neither." << endl;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
|
@ -1,54 +0,0 @@
|
|||
#
|
||||
# Find the CppUnit includes and library
|
||||
#
|
||||
# This module defines
|
||||
# CPPUNIT_INCLUDE_DIR, where to find tiff.h, etc.
|
||||
# CPPUNIT_LIBRARIES, the libraries to link against to use CppUnit.
|
||||
# CPPUNIT_FOUND, If false, do not try to use CppUnit.
|
||||
|
||||
# also defined, but not for general use are
|
||||
# CPPUNIT_LIBRARY, where to find the CppUnit library.
|
||||
# CPPUNIT_DEBUG_LIBRARY, where to find the CppUnit library in debug
|
||||
# mode.
|
||||
|
||||
SET(CPPUNIT_FOUND "NO")
|
||||
|
||||
FIND_PATH(CPPUNIT_INCLUDE_DIR cppunit/TestCase.h /usr/local/include /usr/include)
|
||||
|
||||
# With Win32, important to have both
|
||||
IF(WIN32)
|
||||
FIND_LIBRARY(CPPUNIT_LIBRARY cppunit
|
||||
${CPPUNIT_INCLUDE_DIR}/../lib
|
||||
/usr/local/lib
|
||||
/usr/lib)
|
||||
FIND_LIBRARY(CPPUNIT_DEBUG_LIBRARY cppunitd
|
||||
${CPPUNIT_INCLUDE_DIR}/../lib
|
||||
/usr/local/lib
|
||||
/usr/lib)
|
||||
ELSE(WIN32)
|
||||
# On unix system, debug and release have the same name
|
||||
FIND_LIBRARY(CPPUNIT_LIBRARY cppunit
|
||||
${CPPUNIT_INCLUDE_DIR}/../lib
|
||||
/usr/local/lib
|
||||
/usr/lib)
|
||||
FIND_LIBRARY(CPPUNIT_DEBUG_LIBRARY cppunit
|
||||
${CPPUNIT_INCLUDE_DIR}/../lib
|
||||
/usr/local/lib
|
||||
/usr/lib)
|
||||
ENDIF(WIN32)
|
||||
|
||||
IF(CPPUNIT_INCLUDE_DIR)
|
||||
IF(CPPUNIT_LIBRARY)
|
||||
SET(CPPUNIT_FOUND "YES")
|
||||
SET(CPPUNIT_LIBRARIES ${CPPUNIT_LIBRARY} ${CMAKE_DL_LIBS})
|
||||
SET(CPPUNIT_DEBUG_LIBRARIES ${CPPUNIT_DEBUG_LIBRARY} ${CMAKE_DL_LIBS})
|
||||
ELSE (CPPUNIT_LIBRARY)
|
||||
IF (CPPUNIT_FIND_REQUIRED)
|
||||
MESSAGE(SEND_ERROR "Could not find library CppUnit.")
|
||||
ENDIF (CPPUNIT_FIND_REQUIRED)
|
||||
ENDIF(CPPUNIT_LIBRARY)
|
||||
ELSE(CPPUNIT_INCLUDE_DIR)
|
||||
IF (CPPUNIT_FIND_REQUIRED)
|
||||
MESSAGE(SEND_ERROR "Could not find library CppUnit.")
|
||||
ENDIF(CPPUNIT_FIND_REQUIRED)
|
||||
ENDIF(CPPUNIT_INCLUDE_DIR)
|
|
@ -1,57 +0,0 @@
|
|||
# - Try to find Iconv
|
||||
# Once done this will define
|
||||
#
|
||||
# ICONV_FOUND - system has Iconv
|
||||
# ICONV_INCLUDE_DIR - the Iconv include directory
|
||||
# ICONV_LIBRARIES - Link these to use Iconv
|
||||
# ICONV_SECOND_ARGUMENT_IS_CONST - the second argument for iconv() is const
|
||||
#
|
||||
include(CheckCXXSourceCompiles)
|
||||
|
||||
IF (ICONV_INCLUDE_DIR)
|
||||
# Already in cache, be silent
|
||||
SET(ICONV_FIND_QUIETLY TRUE)
|
||||
ENDIF (ICONV_INCLUDE_DIR)
|
||||
|
||||
FIND_PATH(ICONV_INCLUDE_DIR iconv.h)
|
||||
|
||||
FIND_LIBRARY(ICONV_LIBRARIES NAMES iconv libiconv libiconv-2 c)
|
||||
|
||||
IF(ICONV_INCLUDE_DIR)
|
||||
SET(ICONV_FOUND TRUE)
|
||||
ENDIF(ICONV_INCLUDE_DIR)
|
||||
|
||||
set(CMAKE_REQUIRED_INCLUDES ${ICONV_INCLUDE_DIR})
|
||||
set(CMAKE_REQUIRED_LIBRARIES ${ICONV_LIBRARIES})
|
||||
IF(ICONV_FOUND)
|
||||
check_cxx_source_compiles("
|
||||
#include <iconv.h>
|
||||
int main(){
|
||||
iconv_t conv = 0;
|
||||
char* in = 0;
|
||||
size_t ilen = 0;
|
||||
char* out = 0;
|
||||
size_t olen = 0;
|
||||
iconv(conv, &in, &ilen, &out, &olen);
|
||||
return 0;
|
||||
}
|
||||
" ICONV_SECOND_ARGUMENT_IS_CONST )
|
||||
ENDIF(ICONV_FOUND)
|
||||
set(CMAKE_REQUIRED_INCLUDES)
|
||||
set(CMAKE_REQUIRED_LIBRARIES)
|
||||
|
||||
IF(ICONV_FOUND)
|
||||
IF(NOT ICONV_FIND_QUIETLY)
|
||||
MESSAGE(STATUS "Found Iconv: ${ICONV_LIBRARIES}")
|
||||
ENDIF(NOT ICONV_FIND_QUIETLY)
|
||||
ELSE(ICONV_FOUND)
|
||||
IF(Iconv_FIND_REQUIRED)
|
||||
MESSAGE(FATAL_ERROR "Could not find Iconv")
|
||||
ENDIF(Iconv_FIND_REQUIRED)
|
||||
ENDIF(ICONV_FOUND)
|
||||
|
||||
MARK_AS_ADVANCED(
|
||||
ICONV_INCLUDE_DIR
|
||||
ICONV_LIBRARIES
|
||||
ICONV_SECOND_ARGUMENT_IS_CONST
|
||||
)
|
6
cpp/core/src/bigint/.gitignore
vendored
6
cpp/core/src/bigint/.gitignore
vendored
|
@ -1,6 +0,0 @@
|
|||
*.o
|
||||
sample
|
||||
testsuite
|
||||
testsuite.expected
|
||||
testsuite.out
|
||||
testsuite.err
|
|
@ -1,405 +0,0 @@
|
|||
#include "BigInteger.hh"
|
||||
|
||||
void BigInteger::operator =(const BigInteger &x) {
|
||||
// Calls like a = a have no effect
|
||||
if (this == &x)
|
||||
return;
|
||||
// Copy sign
|
||||
sign = x.sign;
|
||||
// Copy the rest
|
||||
mag = x.mag;
|
||||
}
|
||||
|
||||
BigInteger::BigInteger(const Blk *b, Index blen, Sign s) : mag(b, blen) {
|
||||
switch (s) {
|
||||
case zero:
|
||||
if (!mag.isZero())
|
||||
throw "BigInteger::BigInteger(const Blk *, Index, Sign): Cannot use a sign of zero with a nonzero magnitude";
|
||||
sign = zero;
|
||||
break;
|
||||
case positive:
|
||||
case negative:
|
||||
// If the magnitude is zero, force the sign to zero.
|
||||
sign = mag.isZero() ? zero : s;
|
||||
break;
|
||||
default:
|
||||
/* g++ seems to be optimizing out this case on the assumption
|
||||
* that the sign is a valid member of the enumeration. Oh well. */
|
||||
throw "BigInteger::BigInteger(const Blk *, Index, Sign): Invalid sign";
|
||||
}
|
||||
}
|
||||
|
||||
BigInteger::BigInteger(const BigUnsigned &x, Sign s) : mag(x) {
|
||||
switch (s) {
|
||||
case zero:
|
||||
if (!mag.isZero())
|
||||
throw "BigInteger::BigInteger(const BigUnsigned &, Sign): Cannot use a sign of zero with a nonzero magnitude";
|
||||
sign = zero;
|
||||
break;
|
||||
case positive:
|
||||
case negative:
|
||||
// If the magnitude is zero, force the sign to zero.
|
||||
sign = mag.isZero() ? zero : s;
|
||||
break;
|
||||
default:
|
||||
/* g++ seems to be optimizing out this case on the assumption
|
||||
* that the sign is a valid member of the enumeration. Oh well. */
|
||||
throw "BigInteger::BigInteger(const BigUnsigned &, Sign): Invalid sign";
|
||||
}
|
||||
}
|
||||
|
||||
/* CONSTRUCTION FROM PRIMITIVE INTEGERS
|
||||
* Same idea as in BigUnsigned.cc, except that negative input results in a
|
||||
* negative BigInteger instead of an exception. */
|
||||
|
||||
// Done longhand to let us use initialization.
|
||||
BigInteger::BigInteger(unsigned long x) : mag(x) { sign = mag.isZero() ? zero : positive; }
|
||||
BigInteger::BigInteger(unsigned int x) : mag(x) { sign = mag.isZero() ? zero : positive; }
|
||||
BigInteger::BigInteger(unsigned short x) : mag(x) { sign = mag.isZero() ? zero : positive; }
|
||||
|
||||
// For signed input, determine the desired magnitude and sign separately.
|
||||
|
||||
namespace {
|
||||
template <class X, class UX>
|
||||
BigInteger::Blk magOf(X x) {
|
||||
/* UX(...) cast needed to stop short(-2^15), which negates to
|
||||
* itself, from sign-extending in the conversion to Blk. */
|
||||
return BigInteger::Blk(x < 0 ? UX(-x) : x);
|
||||
}
|
||||
template <class X>
|
||||
BigInteger::Sign signOf(X x) {
|
||||
return (x == 0) ? BigInteger::zero
|
||||
: (x > 0) ? BigInteger::positive
|
||||
: BigInteger::negative;
|
||||
}
|
||||
}
|
||||
|
||||
BigInteger::BigInteger(long x) : sign(signOf(x)), mag(magOf<long , unsigned long >(x)) {}
|
||||
BigInteger::BigInteger(int x) : sign(signOf(x)), mag(magOf<int , unsigned int >(x)) {}
|
||||
BigInteger::BigInteger(short x) : sign(signOf(x)), mag(magOf<short, unsigned short>(x)) {}
|
||||
|
||||
// CONVERSION TO PRIMITIVE INTEGERS
|
||||
|
||||
/* Reuse BigUnsigned's conversion to an unsigned primitive integer.
|
||||
* The friend is a separate function rather than
|
||||
* BigInteger::convertToUnsignedPrimitive to avoid requiring BigUnsigned to
|
||||
* declare BigInteger. */
|
||||
template <class X>
|
||||
inline X convertBigUnsignedToPrimitiveAccess(const BigUnsigned &a) {
|
||||
return a.convertToPrimitive<X>();
|
||||
}
|
||||
|
||||
template <class X>
|
||||
X BigInteger::convertToUnsignedPrimitive() const {
|
||||
if (sign == negative)
|
||||
throw "BigInteger::to<Primitive>: "
|
||||
"Cannot convert a negative integer to an unsigned type";
|
||||
else
|
||||
return convertBigUnsignedToPrimitiveAccess<X>(mag);
|
||||
}
|
||||
|
||||
/* Similar to BigUnsigned::convertToPrimitive, but split into two cases for
|
||||
* nonnegative and negative numbers. */
|
||||
template <class X, class UX>
|
||||
X BigInteger::convertToSignedPrimitive() const {
|
||||
if (sign == zero)
|
||||
return 0;
|
||||
else if (mag.getLength() == 1) {
|
||||
// The single block might fit in an X. Try the conversion.
|
||||
Blk b = mag.getBlock(0);
|
||||
if (sign == positive) {
|
||||
X x = X(b);
|
||||
if (x >= 0 && Blk(x) == b)
|
||||
return x;
|
||||
} else {
|
||||
X x = -X(b);
|
||||
/* UX(...) needed to avoid rejecting conversion of
|
||||
* -2^15 to a short. */
|
||||
if (x < 0 && Blk(UX(-x)) == b)
|
||||
return x;
|
||||
}
|
||||
// Otherwise fall through.
|
||||
}
|
||||
throw "BigInteger::to<Primitive>: "
|
||||
"Value is too big to fit in the requested type";
|
||||
}
|
||||
|
||||
unsigned long BigInteger::toUnsignedLong () const { return convertToUnsignedPrimitive<unsigned long > (); }
|
||||
unsigned int BigInteger::toUnsignedInt () const { return convertToUnsignedPrimitive<unsigned int > (); }
|
||||
unsigned short BigInteger::toUnsignedShort() const { return convertToUnsignedPrimitive<unsigned short> (); }
|
||||
long BigInteger::toLong () const { return convertToSignedPrimitive <long , unsigned long> (); }
|
||||
int BigInteger::toInt () const { return convertToSignedPrimitive <int , unsigned int> (); }
|
||||
short BigInteger::toShort () const { return convertToSignedPrimitive <short, unsigned short>(); }
|
||||
|
||||
// COMPARISON
|
||||
BigInteger::CmpRes BigInteger::compareTo(const BigInteger &x) const {
|
||||
// A greater sign implies a greater number
|
||||
if (sign < x.sign)
|
||||
return less;
|
||||
else if (sign > x.sign)
|
||||
return greater;
|
||||
else switch (sign) {
|
||||
// If the signs are the same...
|
||||
case zero:
|
||||
return equal; // Two zeros are equal
|
||||
case positive:
|
||||
// Compare the magnitudes
|
||||
return mag.compareTo(x.mag);
|
||||
case negative:
|
||||
// Compare the magnitudes, but return the opposite result
|
||||
return CmpRes(-mag.compareTo(x.mag));
|
||||
default:
|
||||
throw "BigInteger internal error";
|
||||
}
|
||||
}
|
||||
|
||||
/* COPY-LESS OPERATIONS
|
||||
* These do some messing around to determine the sign of the result,
|
||||
* then call one of BigUnsigned's copy-less operations. */
|
||||
|
||||
// See remarks about aliased calls in BigUnsigned.cc .
|
||||
#define DTRT_ALIASED(cond, op) \
|
||||
if (cond) { \
|
||||
BigInteger tmpThis; \
|
||||
tmpThis.op; \
|
||||
*this = tmpThis; \
|
||||
return; \
|
||||
}
|
||||
|
||||
void BigInteger::add(const BigInteger &a, const BigInteger &b) {
|
||||
DTRT_ALIASED(this == &a || this == &b, add(a, b));
|
||||
// If one argument is zero, copy the other.
|
||||
if (a.sign == zero)
|
||||
operator =(b);
|
||||
else if (b.sign == zero)
|
||||
operator =(a);
|
||||
// If the arguments have the same sign, take the
|
||||
// common sign and add their magnitudes.
|
||||
else if (a.sign == b.sign) {
|
||||
sign = a.sign;
|
||||
mag.add(a.mag, b.mag);
|
||||
} else {
|
||||
// Otherwise, their magnitudes must be compared.
|
||||
switch (a.mag.compareTo(b.mag)) {
|
||||
case equal:
|
||||
// If their magnitudes are the same, copy zero.
|
||||
mag = 0;
|
||||
sign = zero;
|
||||
break;
|
||||
// Otherwise, take the sign of the greater, and subtract
|
||||
// the lesser magnitude from the greater magnitude.
|
||||
case greater:
|
||||
sign = a.sign;
|
||||
mag.subtract(a.mag, b.mag);
|
||||
break;
|
||||
case less:
|
||||
sign = b.sign;
|
||||
mag.subtract(b.mag, a.mag);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void BigInteger::subtract(const BigInteger &a, const BigInteger &b) {
|
||||
// Notice that this routine is identical to BigInteger::add,
|
||||
// if one replaces b.sign by its opposite.
|
||||
DTRT_ALIASED(this == &a || this == &b, subtract(a, b));
|
||||
// If a is zero, copy b and flip its sign. If b is zero, copy a.
|
||||
if (a.sign == zero) {
|
||||
mag = b.mag;
|
||||
// Take the negative of _b_'s, sign, not ours.
|
||||
// Bug pointed out by Sam Larkin on 2005.03.30.
|
||||
sign = Sign(-b.sign);
|
||||
} else if (b.sign == zero)
|
||||
operator =(a);
|
||||
// If their signs differ, take a.sign and add the magnitudes.
|
||||
else if (a.sign != b.sign) {
|
||||
sign = a.sign;
|
||||
mag.add(a.mag, b.mag);
|
||||
} else {
|
||||
// Otherwise, their magnitudes must be compared.
|
||||
switch (a.mag.compareTo(b.mag)) {
|
||||
// If their magnitudes are the same, copy zero.
|
||||
case equal:
|
||||
mag = 0;
|
||||
sign = zero;
|
||||
break;
|
||||
// If a's magnitude is greater, take a.sign and
|
||||
// subtract a from b.
|
||||
case greater:
|
||||
sign = a.sign;
|
||||
mag.subtract(a.mag, b.mag);
|
||||
break;
|
||||
// If b's magnitude is greater, take the opposite
|
||||
// of b.sign and subtract b from a.
|
||||
case less:
|
||||
sign = Sign(-b.sign);
|
||||
mag.subtract(b.mag, a.mag);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void BigInteger::multiply(const BigInteger &a, const BigInteger &b) {
|
||||
DTRT_ALIASED(this == &a || this == &b, multiply(a, b));
|
||||
// If one object is zero, copy zero and return.
|
||||
if (a.sign == zero || b.sign == zero) {
|
||||
sign = zero;
|
||||
mag = 0;
|
||||
return;
|
||||
}
|
||||
// If the signs of the arguments are the same, the result
|
||||
// is positive, otherwise it is negative.
|
||||
sign = (a.sign == b.sign) ? positive : negative;
|
||||
// Multiply the magnitudes.
|
||||
mag.multiply(a.mag, b.mag);
|
||||
}
|
||||
|
||||
/*
|
||||
* DIVISION WITH REMAINDER
|
||||
* Please read the comments before the definition of
|
||||
* `BigUnsigned::divideWithRemainder' in `BigUnsigned.cc' for lots of
|
||||
* information you should know before reading this function.
|
||||
*
|
||||
* Following Knuth, I decree that x / y is to be
|
||||
* 0 if y==0 and floor(real-number x / y) if y!=0.
|
||||
* Then x % y shall be x - y*(integer x / y).
|
||||
*
|
||||
* Note that x = y * (x / y) + (x % y) always holds.
|
||||
* In addition, (x % y) is from 0 to y - 1 if y > 0,
|
||||
* and from -(|y| - 1) to 0 if y < 0. (x % y) = x if y = 0.
|
||||
*
|
||||
* Examples: (q = a / b, r = a % b)
|
||||
* a b q r
|
||||
* === === === ===
|
||||
* 4 3 1 1
|
||||
* -4 3 -2 2
|
||||
* 4 -3 -2 -2
|
||||
* -4 -3 1 -1
|
||||
*/
|
||||
void BigInteger::divideWithRemainder(const BigInteger &b, BigInteger &q) {
|
||||
// Defend against aliased calls;
|
||||
// same idea as in BigUnsigned::divideWithRemainder .
|
||||
if (this == &q)
|
||||
throw "BigInteger::divideWithRemainder: Cannot write quotient and remainder into the same variable";
|
||||
if (this == &b || &q == &b) {
|
||||
BigInteger tmpB(b);
|
||||
divideWithRemainder(tmpB, q);
|
||||
return;
|
||||
}
|
||||
|
||||
// Division by zero gives quotient 0 and remainder *this
|
||||
if (b.sign == zero) {
|
||||
q.mag = 0;
|
||||
q.sign = zero;
|
||||
return;
|
||||
}
|
||||
// 0 / b gives quotient 0 and remainder 0
|
||||
if (sign == zero) {
|
||||
q.mag = 0;
|
||||
q.sign = zero;
|
||||
return;
|
||||
}
|
||||
|
||||
// Here *this != 0, b != 0.
|
||||
|
||||
// Do the operands have the same sign?
|
||||
if (sign == b.sign) {
|
||||
// Yes: easy case. Quotient is zero or positive.
|
||||
q.sign = positive;
|
||||
} else {
|
||||
// No: harder case. Quotient is negative.
|
||||
q.sign = negative;
|
||||
// Decrease the magnitude of the dividend by one.
|
||||
mag--;
|
||||
/*
|
||||
* We tinker with the dividend before and with the
|
||||
* quotient and remainder after so that the result
|
||||
* comes out right. To see why it works, consider the following
|
||||
* list of examples, where A is the magnitude-decreased
|
||||
* a, Q and R are the results of BigUnsigned division
|
||||
* with remainder on A and |b|, and q and r are the
|
||||
* final results we want:
|
||||
*
|
||||
* a A b Q R q r
|
||||
* -3 -2 3 0 2 -1 0
|
||||
* -4 -3 3 1 0 -2 2
|
||||
* -5 -4 3 1 1 -2 1
|
||||
* -6 -5 3 1 2 -2 0
|
||||
*
|
||||
* It appears that we need a total of 3 corrections:
|
||||
* Decrease the magnitude of a to get A. Increase the
|
||||
* magnitude of Q to get q (and make it negative).
|
||||
* Find r = (b - 1) - R and give it the desired sign.
|
||||
*/
|
||||
}
|
||||
|
||||
// Divide the magnitudes.
|
||||
mag.divideWithRemainder(b.mag, q.mag);
|
||||
|
||||
if (sign != b.sign) {
|
||||
// More for the harder case (as described):
|
||||
// Increase the magnitude of the quotient by one.
|
||||
q.mag++;
|
||||
// Modify the remainder.
|
||||
mag.subtract(b.mag, mag);
|
||||
mag--;
|
||||
}
|
||||
|
||||
// Sign of the remainder is always the sign of the divisor b.
|
||||
sign = b.sign;
|
||||
|
||||
// Set signs to zero as necessary. (Thanks David Allen!)
|
||||
if (mag.isZero())
|
||||
sign = zero;
|
||||
if (q.mag.isZero())
|
||||
q.sign = zero;
|
||||
|
||||
// WHEW!!!
|
||||
}
|
||||
|
||||
// Negation
|
||||
void BigInteger::negate(const BigInteger &a) {
|
||||
DTRT_ALIASED(this == &a, negate(a));
|
||||
// Copy a's magnitude
|
||||
mag = a.mag;
|
||||
// Copy the opposite of a.sign
|
||||
sign = Sign(-a.sign);
|
||||
}
|
||||
|
||||
// INCREMENT/DECREMENT OPERATORS
|
||||
|
||||
// Prefix increment
|
||||
void BigInteger::operator ++() {
|
||||
if (sign == negative) {
|
||||
mag--;
|
||||
if (mag == 0)
|
||||
sign = zero;
|
||||
} else {
|
||||
mag++;
|
||||
sign = positive; // if not already
|
||||
}
|
||||
}
|
||||
|
||||
// Postfix increment: same as prefix
|
||||
void BigInteger::operator ++(int) {
|
||||
operator ++();
|
||||
}
|
||||
|
||||
// Prefix decrement
|
||||
void BigInteger::operator --() {
|
||||
if (sign == positive) {
|
||||
mag--;
|
||||
if (mag == 0)
|
||||
sign = zero;
|
||||
} else {
|
||||
mag++;
|
||||
sign = negative;
|
||||
}
|
||||
}
|
||||
|
||||
// Postfix decrement: same as prefix
|
||||
void BigInteger::operator --(int) {
|
||||
operator --();
|
||||
}
|
||||
|
|
@ -1,215 +0,0 @@
|
|||
#ifndef BIGINTEGER_H
|
||||
#define BIGINTEGER_H
|
||||
|
||||
#include "BigUnsigned.hh"
|
||||
|
||||
/* A BigInteger object represents a signed integer of size limited only by
|
||||
* available memory. BigUnsigneds support most mathematical operators and can
|
||||
* be converted to and from most primitive integer types.
|
||||
*
|
||||
* A BigInteger is just an aggregate of a BigUnsigned and a sign. (It is no
|
||||
* longer derived from BigUnsigned because that led to harmful implicit
|
||||
* conversions.) */
|
||||
class BigInteger {
|
||||
|
||||
public:
|
||||
typedef BigUnsigned::Blk Blk;
|
||||
typedef BigUnsigned::Index Index;
|
||||
typedef BigUnsigned::CmpRes CmpRes;
|
||||
static const CmpRes
|
||||
less = BigUnsigned::less ,
|
||||
equal = BigUnsigned::equal ,
|
||||
greater = BigUnsigned::greater;
|
||||
// Enumeration for the sign of a BigInteger.
|
||||
enum Sign { negative = -1, zero = 0, positive = 1 };
|
||||
|
||||
protected:
|
||||
Sign sign;
|
||||
BigUnsigned mag;
|
||||
|
||||
public:
|
||||
// Constructs zero.
|
||||
BigInteger() : sign(zero), mag() {}
|
||||
|
||||
// Copy constructor
|
||||
BigInteger(const BigInteger &x) : sign(x.sign), mag(x.mag) {};
|
||||
|
||||
// Assignment operator
|
||||
void operator=(const BigInteger &x);
|
||||
|
||||
// Constructor that copies from a given array of blocks with a sign.
|
||||
BigInteger(const Blk *b, Index blen, Sign s);
|
||||
|
||||
// Nonnegative constructor that copies from a given array of blocks.
|
||||
BigInteger(const Blk *b, Index blen) : mag(b, blen) {
|
||||
sign = mag.isZero() ? zero : positive;
|
||||
}
|
||||
|
||||
// Constructor from a BigUnsigned and a sign
|
||||
BigInteger(const BigUnsigned &x, Sign s);
|
||||
|
||||
// Nonnegative constructor from a BigUnsigned
|
||||
BigInteger(const BigUnsigned &x) : mag(x) {
|
||||
sign = mag.isZero() ? zero : positive;
|
||||
}
|
||||
|
||||
// Constructors from primitive integer types
|
||||
BigInteger(unsigned long x);
|
||||
BigInteger( long x);
|
||||
BigInteger(unsigned int x);
|
||||
BigInteger( int x);
|
||||
BigInteger(unsigned short x);
|
||||
BigInteger( short x);
|
||||
|
||||
/* Converters to primitive integer types
|
||||
* The implicit conversion operators caused trouble, so these are now
|
||||
* named. */
|
||||
unsigned long toUnsignedLong () const;
|
||||
long toLong () const;
|
||||
unsigned int toUnsignedInt () const;
|
||||
int toInt () const;
|
||||
unsigned short toUnsignedShort() const;
|
||||
short toShort () const;
|
||||
protected:
|
||||
// Helper
|
||||
template <class X> X convertToUnsignedPrimitive() const;
|
||||
template <class X, class UX> X convertToSignedPrimitive() const;
|
||||
public:
|
||||
|
||||
// ACCESSORS
|
||||
Sign getSign() const { return sign; }
|
||||
/* The client can't do any harm by holding a read-only reference to the
|
||||
* magnitude. */
|
||||
const BigUnsigned &getMagnitude() const { return mag; }
|
||||
|
||||
// Some accessors that go through to the magnitude
|
||||
Index getLength() const { return mag.getLength(); }
|
||||
Index getCapacity() const { return mag.getCapacity(); }
|
||||
Blk getBlock(Index i) const { return mag.getBlock(i); }
|
||||
bool isZero() const { return sign == zero; } // A bit special
|
||||
|
||||
// COMPARISONS
|
||||
|
||||
// Compares this to x like Perl's <=>
|
||||
CmpRes compareTo(const BigInteger &x) const;
|
||||
|
||||
// Ordinary comparison operators
|
||||
bool operator ==(const BigInteger &x) const {
|
||||
return sign == x.sign && mag == x.mag;
|
||||
}
|
||||
bool operator !=(const BigInteger &x) const { return !operator ==(x); };
|
||||
bool operator < (const BigInteger &x) const { return compareTo(x) == less ; }
|
||||
bool operator <=(const BigInteger &x) const { return compareTo(x) != greater; }
|
||||
bool operator >=(const BigInteger &x) const { return compareTo(x) != less ; }
|
||||
bool operator > (const BigInteger &x) const { return compareTo(x) == greater; }
|
||||
|
||||
// OPERATORS -- See the discussion in BigUnsigned.hh.
|
||||
void add (const BigInteger &a, const BigInteger &b);
|
||||
void subtract(const BigInteger &a, const BigInteger &b);
|
||||
void multiply(const BigInteger &a, const BigInteger &b);
|
||||
/* See the comment on BigUnsigned::divideWithRemainder. Semantics
|
||||
* differ from those of primitive integers when negatives and/or zeros
|
||||
* are involved. */
|
||||
void divideWithRemainder(const BigInteger &b, BigInteger &q);
|
||||
void negate(const BigInteger &a);
|
||||
|
||||
/* Bitwise operators are not provided for BigIntegers. Use
|
||||
* getMagnitude to get the magnitude and operate on that instead. */
|
||||
|
||||
BigInteger operator +(const BigInteger &x) const;
|
||||
BigInteger operator -(const BigInteger &x) const;
|
||||
BigInteger operator *(const BigInteger &x) const;
|
||||
BigInteger operator /(const BigInteger &x) const;
|
||||
BigInteger operator %(const BigInteger &x) const;
|
||||
BigInteger operator -() const;
|
||||
|
||||
void operator +=(const BigInteger &x);
|
||||
void operator -=(const BigInteger &x);
|
||||
void operator *=(const BigInteger &x);
|
||||
void operator /=(const BigInteger &x);
|
||||
void operator %=(const BigInteger &x);
|
||||
void flipSign();
|
||||
|
||||
// INCREMENT/DECREMENT OPERATORS
|
||||
void operator ++( );
|
||||
void operator ++(int);
|
||||
void operator --( );
|
||||
void operator --(int);
|
||||
};
|
||||
|
||||
// NORMAL OPERATORS
|
||||
/* These create an object to hold the result and invoke
|
||||
* the appropriate put-here operation on it, passing
|
||||
* this and x. The new object is then returned. */
|
||||
inline BigInteger BigInteger::operator +(const BigInteger &x) const {
|
||||
BigInteger ans;
|
||||
ans.add(*this, x);
|
||||
return ans;
|
||||
}
|
||||
inline BigInteger BigInteger::operator -(const BigInteger &x) const {
|
||||
BigInteger ans;
|
||||
ans.subtract(*this, x);
|
||||
return ans;
|
||||
}
|
||||
inline BigInteger BigInteger::operator *(const BigInteger &x) const {
|
||||
BigInteger ans;
|
||||
ans.multiply(*this, x);
|
||||
return ans;
|
||||
}
|
||||
inline BigInteger BigInteger::operator /(const BigInteger &x) const {
|
||||
if (x.isZero()) throw "BigInteger::operator /: division by zero";
|
||||
BigInteger q, r;
|
||||
r = *this;
|
||||
r.divideWithRemainder(x, q);
|
||||
return q;
|
||||
}
|
||||
inline BigInteger BigInteger::operator %(const BigInteger &x) const {
|
||||
if (x.isZero()) throw "BigInteger::operator %: division by zero";
|
||||
BigInteger q, r;
|
||||
r = *this;
|
||||
r.divideWithRemainder(x, q);
|
||||
return r;
|
||||
}
|
||||
inline BigInteger BigInteger::operator -() const {
|
||||
BigInteger ans;
|
||||
ans.negate(*this);
|
||||
return ans;
|
||||
}
|
||||
|
||||
/*
|
||||
* ASSIGNMENT OPERATORS
|
||||
*
|
||||
* Now the responsibility for making a temporary copy if necessary
|
||||
* belongs to the put-here operations. See Assignment Operators in
|
||||
* BigUnsigned.hh.
|
||||
*/
|
||||
inline void BigInteger::operator +=(const BigInteger &x) {
|
||||
add(*this, x);
|
||||
}
|
||||
inline void BigInteger::operator -=(const BigInteger &x) {
|
||||
subtract(*this, x);
|
||||
}
|
||||
inline void BigInteger::operator *=(const BigInteger &x) {
|
||||
multiply(*this, x);
|
||||
}
|
||||
inline void BigInteger::operator /=(const BigInteger &x) {
|
||||
if (x.isZero()) throw "BigInteger::operator /=: division by zero";
|
||||
/* The following technique is slightly faster than copying *this first
|
||||
* when x is large. */
|
||||
BigInteger q;
|
||||
divideWithRemainder(x, q);
|
||||
// *this contains the remainder, but we overwrite it with the quotient.
|
||||
*this = q;
|
||||
}
|
||||
inline void BigInteger::operator %=(const BigInteger &x) {
|
||||
if (x.isZero()) throw "BigInteger::operator %=: division by zero";
|
||||
BigInteger q;
|
||||
// Mods *this by x. Don't care about quotient left in q.
|
||||
divideWithRemainder(x, q);
|
||||
}
|
||||
// This one is trivial
|
||||
inline void BigInteger::flipSign() {
|
||||
sign = Sign(-sign);
|
||||
}
|
||||
|
||||
#endif
|
|
@ -1,70 +0,0 @@
|
|||
#include "BigIntegerAlgorithms.hh"
|
||||
|
||||
BigUnsigned gcd(BigUnsigned a, BigUnsigned b) {
|
||||
BigUnsigned trash;
|
||||
// Neat in-place alternating technique.
|
||||
for (;;) {
|
||||
if (b.isZero())
|
||||
return a;
|
||||
a.divideWithRemainder(b, trash);
|
||||
if (a.isZero())
|
||||
return b;
|
||||
b.divideWithRemainder(a, trash);
|
||||
}
|
||||
}
|
||||
|
||||
void extendedEuclidean(BigInteger m, BigInteger n,
|
||||
BigInteger &g, BigInteger &r, BigInteger &s) {
|
||||
if (&g == &r || &g == &s || &r == &s)
|
||||
throw "BigInteger extendedEuclidean: Outputs are aliased";
|
||||
BigInteger r1(1), s1(0), r2(0), s2(1), q;
|
||||
/* Invariants:
|
||||
* r1*m(orig) + s1*n(orig) == m(current)
|
||||
* r2*m(orig) + s2*n(orig) == n(current) */
|
||||
for (;;) {
|
||||
if (n.isZero()) {
|
||||
r = r1; s = s1; g = m;
|
||||
return;
|
||||
}
|
||||
// Subtract q times the second invariant from the first invariant.
|
||||
m.divideWithRemainder(n, q);
|
||||
r1 -= q*r2; s1 -= q*s2;
|
||||
|
||||
if (m.isZero()) {
|
||||
r = r2; s = s2; g = n;
|
||||
return;
|
||||
}
|
||||
// Subtract q times the first invariant from the second invariant.
|
||||
n.divideWithRemainder(m, q);
|
||||
r2 -= q*r1; s2 -= q*s1;
|
||||
}
|
||||
}
|
||||
|
||||
BigUnsigned modinv(const BigInteger &x, const BigUnsigned &n) {
|
||||
BigInteger g, r, s;
|
||||
extendedEuclidean(x, n, g, r, s);
|
||||
if (g == 1)
|
||||
// r*x + s*n == 1, so r*x === 1 (mod n), so r is the answer.
|
||||
return (r % n).getMagnitude(); // (r % n) will be nonnegative
|
||||
else
|
||||
throw "BigInteger modinv: x and n have a common factor";
|
||||
}
|
||||
|
||||
BigUnsigned modexp(const BigInteger &base, const BigUnsigned &exponent,
|
||||
const BigUnsigned &modulus) {
|
||||
BigUnsigned ans = 1, base2 = (base % modulus).getMagnitude();
|
||||
BigUnsigned::Index i = exponent.bitLength();
|
||||
// For each bit of the exponent, most to least significant...
|
||||
while (i > 0) {
|
||||
i--;
|
||||
// Square.
|
||||
ans *= ans;
|
||||
ans %= modulus;
|
||||
// And multiply if the bit is a 1.
|
||||
if (exponent.getBit(i)) {
|
||||
ans *= base2;
|
||||
ans %= modulus;
|
||||
}
|
||||
}
|
||||
return ans;
|
||||
}
|
|
@ -1,25 +0,0 @@
|
|||
#ifndef BIGINTEGERALGORITHMS_H
|
||||
#define BIGINTEGERALGORITHMS_H
|
||||
|
||||
#include "BigInteger.hh"
|
||||
|
||||
/* Some mathematical algorithms for big integers.
|
||||
* This code is new and, as such, experimental. */
|
||||
|
||||
// Returns the greatest common divisor of a and b.
|
||||
BigUnsigned gcd(BigUnsigned a, BigUnsigned b);
|
||||
|
||||
/* Extended Euclidean algorithm.
|
||||
* Given m and n, finds gcd g and numbers r, s such that r*m + s*n == g. */
|
||||
void extendedEuclidean(BigInteger m, BigInteger n,
|
||||
BigInteger &g, BigInteger &r, BigInteger &s);
|
||||
|
||||
/* Returns the multiplicative inverse of x modulo n, or throws an exception if
|
||||
* they have a common factor. */
|
||||
BigUnsigned modinv(const BigInteger &x, const BigUnsigned &n);
|
||||
|
||||
// Returns (base ^ exponent) % modulus.
|
||||
BigUnsigned modexp(const BigInteger &base, const BigUnsigned &exponent,
|
||||
const BigUnsigned &modulus);
|
||||
|
||||
#endif
|
|
@ -1,8 +0,0 @@
|
|||
// This header file includes all of the library header files.
|
||||
|
||||
#include "NumberlikeArray.hh"
|
||||
#include "BigUnsigned.hh"
|
||||
#include "BigInteger.hh"
|
||||
#include "BigIntegerAlgorithms.hh"
|
||||
#include "BigUnsignedInABase.hh"
|
||||
#include "BigIntegerUtils.hh"
|
|
@ -1,50 +0,0 @@
|
|||
#include "BigIntegerUtils.hh"
|
||||
#include "BigUnsignedInABase.hh"
|
||||
|
||||
std::string bigUnsignedToString(const BigUnsigned &x) {
|
||||
return std::string(BigUnsignedInABase(x, 10));
|
||||
}
|
||||
|
||||
std::string bigIntegerToString(const BigInteger &x) {
|
||||
return (x.getSign() == BigInteger::negative)
|
||||
? (std::string("-") + bigUnsignedToString(x.getMagnitude()))
|
||||
: (bigUnsignedToString(x.getMagnitude()));
|
||||
}
|
||||
|
||||
BigUnsigned stringToBigUnsigned(const std::string &s) {
|
||||
return BigUnsigned(BigUnsignedInABase(s, 10));
|
||||
}
|
||||
|
||||
BigInteger stringToBigInteger(const std::string &s) {
|
||||
// Recognize a sign followed by a BigUnsigned.
|
||||
return (s[0] == '-') ? BigInteger(stringToBigUnsigned(s.substr(1, s.length() - 1)), BigInteger::negative)
|
||||
: (s[0] == '+') ? BigInteger(stringToBigUnsigned(s.substr(1, s.length() - 1)))
|
||||
: BigInteger(stringToBigUnsigned(s));
|
||||
}
|
||||
|
||||
std::ostream &operator <<(std::ostream &os, const BigUnsigned &x) {
|
||||
BigUnsignedInABase::Base base;
|
||||
long osFlags = os.flags();
|
||||
if (osFlags & os.dec)
|
||||
base = 10;
|
||||
else if (osFlags & os.hex) {
|
||||
base = 16;
|
||||
if (osFlags & os.showbase)
|
||||
os << "0x";
|
||||
} else if (osFlags & os.oct) {
|
||||
base = 8;
|
||||
if (osFlags & os.showbase)
|
||||
os << '0';
|
||||
} else
|
||||
throw "std::ostream << BigUnsigned: Could not determine the desired base from output-stream flags";
|
||||
std::string s = std::string(BigUnsignedInABase(x, base));
|
||||
os << s;
|
||||
return os;
|
||||
}
|
||||
|
||||
std::ostream &operator <<(std::ostream &os, const BigInteger &x) {
|
||||
if (x.getSign() == BigInteger::negative)
|
||||
os << '-';
|
||||
os << x.getMagnitude();
|
||||
return os;
|
||||
}
|
|
@ -1,72 +0,0 @@
|
|||
#ifndef BIGINTEGERUTILS_H
|
||||
#define BIGINTEGERUTILS_H
|
||||
|
||||
#include "BigInteger.hh"
|
||||
#include <string>
|
||||
#include <iostream>
|
||||
|
||||
/* This file provides:
|
||||
* - Convenient std::string <-> BigUnsigned/BigInteger conversion routines
|
||||
* - std::ostream << operators for BigUnsigned/BigInteger */
|
||||
|
||||
// std::string conversion routines. Base 10 only.
|
||||
std::string bigUnsignedToString(const BigUnsigned &x);
|
||||
std::string bigIntegerToString(const BigInteger &x);
|
||||
BigUnsigned stringToBigUnsigned(const std::string &s);
|
||||
BigInteger stringToBigInteger(const std::string &s);
|
||||
|
||||
// Creates a BigInteger from data such as `char's; read below for details.
|
||||
template <class T>
|
||||
BigInteger dataToBigInteger(const T* data, BigInteger::Index length, BigInteger::Sign sign);
|
||||
|
||||
// Outputs x to os, obeying the flags `dec', `hex', `bin', and `showbase'.
|
||||
std::ostream &operator <<(std::ostream &os, const BigUnsigned &x);
|
||||
|
||||
// Outputs x to os, obeying the flags `dec', `hex', `bin', and `showbase'.
|
||||
// My somewhat arbitrary policy: a negative sign comes before a base indicator (like -0xFF).
|
||||
std::ostream &operator <<(std::ostream &os, const BigInteger &x);
|
||||
|
||||
// BEGIN TEMPLATE DEFINITIONS.
|
||||
|
||||
/*
|
||||
* Converts binary data to a BigInteger.
|
||||
* Pass an array `data', its length, and the desired sign.
|
||||
*
|
||||
* Elements of `data' may be of any type `T' that has the following
|
||||
* two properties (this includes almost all integral types):
|
||||
*
|
||||
* (1) `sizeof(T)' correctly gives the amount of binary data in one
|
||||
* value of `T' and is a factor of `sizeof(Blk)'.
|
||||
*
|
||||
* (2) When a value of `T' is casted to a `Blk', the low bytes of
|
||||
* the result contain the desired binary data.
|
||||
*/
|
||||
template <class T>
|
||||
BigInteger dataToBigInteger(const T* data, BigInteger::Index length, BigInteger::Sign sign) {
|
||||
// really ceiling(numBytes / sizeof(BigInteger::Blk))
|
||||
unsigned int pieceSizeInBits = 8 * sizeof(T);
|
||||
unsigned int piecesPerBlock = sizeof(BigInteger::Blk) / sizeof(T);
|
||||
unsigned int numBlocks = (length + piecesPerBlock - 1) / piecesPerBlock;
|
||||
|
||||
// Allocate our block array
|
||||
BigInteger::Blk *blocks = new BigInteger::Blk[numBlocks];
|
||||
|
||||
BigInteger::Index blockNum, pieceNum, pieceNumHere;
|
||||
|
||||
// Convert
|
||||
for (blockNum = 0, pieceNum = 0; blockNum < numBlocks; blockNum++) {
|
||||
BigInteger::Blk curBlock = 0;
|
||||
for (pieceNumHere = 0; pieceNumHere < piecesPerBlock && pieceNum < length;
|
||||
pieceNumHere++, pieceNum++)
|
||||
curBlock |= (BigInteger::Blk(data[pieceNum]) << (pieceSizeInBits * pieceNumHere));
|
||||
blocks[blockNum] = curBlock;
|
||||
}
|
||||
|
||||
// Create the BigInteger.
|
||||
BigInteger x(blocks, numBlocks, sign);
|
||||
|
||||
delete [] blocks;
|
||||
return x;
|
||||
}
|
||||
|
||||
#endif
|
|
@ -1,697 +0,0 @@
|
|||
#include "BigUnsigned.hh"
|
||||
|
||||
// Memory management definitions have moved to the bottom of NumberlikeArray.hh.
|
||||
|
||||
// The templates used by these constructors and converters are at the bottom of
|
||||
// BigUnsigned.hh.
|
||||
|
||||
BigUnsigned::BigUnsigned(unsigned long x) { initFromPrimitive (x); }
|
||||
BigUnsigned::BigUnsigned(unsigned int x) { initFromPrimitive (x); }
|
||||
BigUnsigned::BigUnsigned(unsigned short x) { initFromPrimitive (x); }
|
||||
BigUnsigned::BigUnsigned( long x) { initFromSignedPrimitive(x); }
|
||||
BigUnsigned::BigUnsigned( int x) { initFromSignedPrimitive(x); }
|
||||
BigUnsigned::BigUnsigned( short x) { initFromSignedPrimitive(x); }
|
||||
|
||||
unsigned long BigUnsigned::toUnsignedLong () const { return convertToPrimitive <unsigned long >(); }
|
||||
unsigned int BigUnsigned::toUnsignedInt () const { return convertToPrimitive <unsigned int >(); }
|
||||
unsigned short BigUnsigned::toUnsignedShort() const { return convertToPrimitive <unsigned short>(); }
|
||||
long BigUnsigned::toLong () const { return convertToSignedPrimitive< long >(); }
|
||||
int BigUnsigned::toInt () const { return convertToSignedPrimitive< int >(); }
|
||||
short BigUnsigned::toShort () const { return convertToSignedPrimitive< short>(); }
|
||||
|
||||
// BIT/BLOCK ACCESSORS
|
||||
|
||||
void BigUnsigned::setBlock(Index i, Blk newBlock) {
|
||||
if (newBlock == 0) {
|
||||
if (i < len) {
|
||||
blk[i] = 0;
|
||||
zapLeadingZeros();
|
||||
}
|
||||
// If i >= len, no effect.
|
||||
} else {
|
||||
if (i >= len) {
|
||||
// The nonzero block extends the number.
|
||||
allocateAndCopy(i+1);
|
||||
// Zero any added blocks that we aren't setting.
|
||||
for (Index j = len; j < i; j++)
|
||||
blk[j] = 0;
|
||||
len = i+1;
|
||||
}
|
||||
blk[i] = newBlock;
|
||||
}
|
||||
}
|
||||
|
||||
/* Evidently the compiler wants BigUnsigned:: on the return type because, at
|
||||
* that point, it hasn't yet parsed the BigUnsigned:: on the name to get the
|
||||
* proper scope. */
|
||||
BigUnsigned::Index BigUnsigned::bitLength() const {
|
||||
if (isZero())
|
||||
return 0;
|
||||
else {
|
||||
Blk leftmostBlock = getBlock(len - 1);
|
||||
Index leftmostBlockLen = 0;
|
||||
while (leftmostBlock != 0) {
|
||||
leftmostBlock >>= 1;
|
||||
leftmostBlockLen++;
|
||||
}
|
||||
return leftmostBlockLen + (len - 1) * N;
|
||||
}
|
||||
}
|
||||
|
||||
void BigUnsigned::setBit(Index bi, bool newBit) {
|
||||
Index blockI = bi / N;
|
||||
Blk block = getBlock(blockI), mask = Blk(1) << (bi % N);
|
||||
block = newBit ? (block | mask) : (block & ~mask);
|
||||
setBlock(blockI, block);
|
||||
}
|
||||
|
||||
// COMPARISON
|
||||
BigUnsigned::CmpRes BigUnsigned::compareTo(const BigUnsigned &x) const {
|
||||
// A bigger length implies a bigger number.
|
||||
if (len < x.len)
|
||||
return less;
|
||||
else if (len > x.len)
|
||||
return greater;
|
||||
else {
|
||||
// Compare blocks one by one from left to right.
|
||||
Index i = len;
|
||||
while (i > 0) {
|
||||
i--;
|
||||
if (blk[i] == x.blk[i])
|
||||
continue;
|
||||
else if (blk[i] > x.blk[i])
|
||||
return greater;
|
||||
else
|
||||
return less;
|
||||
}
|
||||
// If no blocks differed, the numbers are equal.
|
||||
return equal;
|
||||
}
|
||||
}
|
||||
|
||||
// COPY-LESS OPERATIONS
|
||||
|
||||
/*
|
||||
* On most calls to copy-less operations, it's safe to read the inputs little by
|
||||
* little and write the outputs little by little. However, if one of the
|
||||
* inputs is coming from the same variable into which the output is to be
|
||||
* stored (an "aliased" call), we risk overwriting the input before we read it.
|
||||
* In this case, we first compute the result into a temporary BigUnsigned
|
||||
* variable and then copy it into the requested output variable *this.
|
||||
* Each put-here operation uses the DTRT_ALIASED macro (Do The Right Thing on
|
||||
* aliased calls) to generate code for this check.
|
||||
*
|
||||
* I adopted this approach on 2007.02.13 (see Assignment Operators in
|
||||
* BigUnsigned.hh). Before then, put-here operations rejected aliased calls
|
||||
* with an exception. I think doing the right thing is better.
|
||||
*
|
||||
* Some of the put-here operations can probably handle aliased calls safely
|
||||
* without the extra copy because (for example) they process blocks strictly
|
||||
* right-to-left. At some point I might determine which ones don't need the
|
||||
* copy, but my reasoning would need to be verified very carefully. For now
|
||||
* I'll leave in the copy.
|
||||
*/
|
||||
#define DTRT_ALIASED(cond, op) \
|
||||
if (cond) { \
|
||||
BigUnsigned tmpThis; \
|
||||
tmpThis.op; \
|
||||
*this = tmpThis; \
|
||||
return; \
|
||||
}
|
||||
|
||||
|
||||
|
||||
void BigUnsigned::add(const BigUnsigned &a, const BigUnsigned &b) {
|
||||
DTRT_ALIASED(this == &a || this == &b, add(a, b));
|
||||
// If one argument is zero, copy the other.
|
||||
if (a.len == 0) {
|
||||
operator =(b);
|
||||
return;
|
||||
} else if (b.len == 0) {
|
||||
operator =(a);
|
||||
return;
|
||||
}
|
||||
// Some variables...
|
||||
// Carries in and out of an addition stage
|
||||
bool carryIn, carryOut;
|
||||
Blk temp;
|
||||
Index i;
|
||||
// a2 points to the longer input, b2 points to the shorter
|
||||
const BigUnsigned *a2, *b2;
|
||||
if (a.len >= b.len) {
|
||||
a2 = &a;
|
||||
b2 = &b;
|
||||
} else {
|
||||
a2 = &b;
|
||||
b2 = &a;
|
||||
}
|
||||
// Set prelimiary length and make room in this BigUnsigned
|
||||
len = a2->len + 1;
|
||||
allocate(len);
|
||||
// For each block index that is present in both inputs...
|
||||
for (i = 0, carryIn = false; i < b2->len; i++) {
|
||||
// Add input blocks
|
||||
temp = a2->blk[i] + b2->blk[i];
|
||||
// If a rollover occurred, the result is less than either input.
|
||||
// This test is used many times in the BigUnsigned code.
|
||||
carryOut = (temp < a2->blk[i]);
|
||||
// If a carry was input, handle it
|
||||
if (carryIn) {
|
||||
temp++;
|
||||
carryOut |= (temp == 0);
|
||||
}
|
||||
blk[i] = temp; // Save the addition result
|
||||
carryIn = carryOut; // Pass the carry along
|
||||
}
|
||||
// If there is a carry left over, increase blocks until
|
||||
// one does not roll over.
|
||||
for (; i < a2->len && carryIn; i++) {
|
||||
temp = a2->blk[i] + 1;
|
||||
carryIn = (temp == 0);
|
||||
blk[i] = temp;
|
||||
}
|
||||
// If the carry was resolved but the larger number
|
||||
// still has blocks, copy them over.
|
||||
for (; i < a2->len; i++)
|
||||
blk[i] = a2->blk[i];
|
||||
// Set the extra block if there's still a carry, decrease length otherwise
|
||||
if (carryIn)
|
||||
blk[i] = 1;
|
||||
else
|
||||
len--;
|
||||
}
|
||||
|
||||
void BigUnsigned::subtract(const BigUnsigned &a, const BigUnsigned &b) {
|
||||
DTRT_ALIASED(this == &a || this == &b, subtract(a, b));
|
||||
if (b.len == 0) {
|
||||
// If b is zero, copy a.
|
||||
operator =(a);
|
||||
return;
|
||||
} else if (a.len < b.len)
|
||||
// If a is shorter than b, the result is negative.
|
||||
throw "BigUnsigned::subtract: "
|
||||
"Negative result in unsigned calculation";
|
||||
// Some variables...
|
||||
bool borrowIn, borrowOut;
|
||||
Blk temp;
|
||||
Index i;
|
||||
// Set preliminary length and make room
|
||||
len = a.len;
|
||||
allocate(len);
|
||||
// For each block index that is present in both inputs...
|
||||
for (i = 0, borrowIn = false; i < b.len; i++) {
|
||||
temp = a.blk[i] - b.blk[i];
|
||||
// If a reverse rollover occurred,
|
||||
// the result is greater than the block from a.
|
||||
borrowOut = (temp > a.blk[i]);
|
||||
// Handle an incoming borrow
|
||||
if (borrowIn) {
|
||||
borrowOut |= (temp == 0);
|
||||
temp--;
|
||||
}
|
||||
blk[i] = temp; // Save the subtraction result
|
||||
borrowIn = borrowOut; // Pass the borrow along
|
||||
}
|
||||
// If there is a borrow left over, decrease blocks until
|
||||
// one does not reverse rollover.
|
||||
for (; i < a.len && borrowIn; i++) {
|
||||
borrowIn = (a.blk[i] == 0);
|
||||
blk[i] = a.blk[i] - 1;
|
||||
}
|
||||
/* If there's still a borrow, the result is negative.
|
||||
* Throw an exception, but zero out this object so as to leave it in a
|
||||
* predictable state. */
|
||||
if (borrowIn) {
|
||||
len = 0;
|
||||
throw "BigUnsigned::subtract: Negative result in unsigned calculation";
|
||||
} else
|
||||
// Copy over the rest of the blocks
|
||||
for (; i < a.len; i++)
|
||||
blk[i] = a.blk[i];
|
||||
// Zap leading zeros
|
||||
zapLeadingZeros();
|
||||
}
|
||||
|
||||
/*
|
||||
* About the multiplication and division algorithms:
|
||||
*
|
||||
* I searched unsucessfully for fast C++ built-in operations like the `b_0'
|
||||
* and `c_0' Knuth describes in Section 4.3.1 of ``The Art of Computer
|
||||
* Programming'' (replace `place' by `Blk'):
|
||||
*
|
||||
* ``b_0[:] multiplication of a one-place integer by another one-place
|
||||
* integer, giving a two-place answer;
|
||||
*
|
||||
* ``c_0[:] division of a two-place integer by a one-place integer,
|
||||
* provided that the quotient is a one-place integer, and yielding
|
||||
* also a one-place remainder.''
|
||||
*
|
||||
* I also missed his note that ``[b]y adjusting the word size, if
|
||||
* necessary, nearly all computers will have these three operations
|
||||
* available'', so I gave up on trying to use algorithms similar to his.
|
||||
* A future version of the library might include such algorithms; I
|
||||
* would welcome contributions from others for this.
|
||||
*
|
||||
* I eventually decided to use bit-shifting algorithms. To multiply `a'
|
||||
* and `b', we zero out the result. Then, for each `1' bit in `a', we
|
||||
* shift `b' left the appropriate amount and add it to the result.
|
||||
* Similarly, to divide `a' by `b', we shift `b' left varying amounts,
|
||||
* repeatedly trying to subtract it from `a'. When we succeed, we note
|
||||
* the fact by setting a bit in the quotient. While these algorithms
|
||||
* have the same O(n^2) time complexity as Knuth's, the ``constant factor''
|
||||
* is likely to be larger.
|
||||
*
|
||||
* Because I used these algorithms, which require single-block addition
|
||||
* and subtraction rather than single-block multiplication and division,
|
||||
* the innermost loops of all four routines are very similar. Study one
|
||||
* of them and all will become clear.
|
||||
*/
|
||||
|
||||
/*
|
||||
* This is a little inline function used by both the multiplication
|
||||
* routine and the division routine.
|
||||
*
|
||||
* `getShiftedBlock' returns the `x'th block of `num << y'.
|
||||
* `y' may be anything from 0 to N - 1, and `x' may be anything from
|
||||
* 0 to `num.len'.
|
||||
*
|
||||
* Two things contribute to this block:
|
||||
*
|
||||
* (1) The `N - y' low bits of `num.blk[x]', shifted `y' bits left.
|
||||
*
|
||||
* (2) The `y' high bits of `num.blk[x-1]', shifted `N - y' bits right.
|
||||
*
|
||||
* But we must be careful if `x == 0' or `x == num.len', in
|
||||
* which case we should use 0 instead of (2) or (1), respectively.
|
||||
*
|
||||
* If `y == 0', then (2) contributes 0, as it should. However,
|
||||
* in some computer environments, for a reason I cannot understand,
|
||||
* `a >> b' means `a >> (b % N)'. This means `num.blk[x-1] >> (N - y)'
|
||||
* will return `num.blk[x-1]' instead of the desired 0 when `y == 0';
|
||||
* the test `y == 0' handles this case specially.
|
||||
*/
|
||||
inline BigUnsigned::Blk getShiftedBlock(const BigUnsigned &num,
|
||||
BigUnsigned::Index x, unsigned int y) {
|
||||
BigUnsigned::Blk part1 = (x == 0 || y == 0) ? 0 : (num.blk[x - 1] >> (BigUnsigned::N - y));
|
||||
BigUnsigned::Blk part2 = (x == num.len) ? 0 : (num.blk[x] << y);
|
||||
return part1 | part2;
|
||||
}
|
||||
|
||||
void BigUnsigned::multiply(const BigUnsigned &a, const BigUnsigned &b) {
|
||||
DTRT_ALIASED(this == &a || this == &b, multiply(a, b));
|
||||
// If either a or b is zero, set to zero.
|
||||
if (a.len == 0 || b.len == 0) {
|
||||
len = 0;
|
||||
return;
|
||||
}
|
||||
/*
|
||||
* Overall method:
|
||||
*
|
||||
* Set this = 0.
|
||||
* For each 1-bit of `a' (say the `i2'th bit of block `i'):
|
||||
* Add `b << (i blocks and i2 bits)' to *this.
|
||||
*/
|
||||
// Variables for the calculation
|
||||
Index i, j, k;
|
||||
unsigned int i2;
|
||||
Blk temp;
|
||||
bool carryIn, carryOut;
|
||||
// Set preliminary length and make room
|
||||
len = a.len + b.len;
|
||||
allocate(len);
|
||||
// Zero out this object
|
||||
for (i = 0; i < len; i++)
|
||||
blk[i] = 0;
|
||||
// For each block of the first number...
|
||||
for (i = 0; i < a.len; i++) {
|
||||
// For each 1-bit of that block...
|
||||
for (i2 = 0; i2 < N; i2++) {
|
||||
if ((a.blk[i] & (Blk(1) << i2)) == 0)
|
||||
continue;
|
||||
/*
|
||||
* Add b to this, shifted left i blocks and i2 bits.
|
||||
* j is the index in b, and k = i + j is the index in this.
|
||||
*
|
||||
* `getShiftedBlock', a short inline function defined above,
|
||||
* is now used for the bit handling. It replaces the more
|
||||
* complex `bHigh' code, in which each run of the loop dealt
|
||||
* immediately with the low bits and saved the high bits to
|
||||
* be picked up next time. The last run of the loop used to
|
||||
* leave leftover high bits, which were handled separately.
|
||||
* Instead, this loop runs an additional time with j == b.len.
|
||||
* These changes were made on 2005.01.11.
|
||||
*/
|
||||
for (j = 0, k = i, carryIn = false; j <= b.len; j++, k++) {
|
||||
/*
|
||||
* The body of this loop is very similar to the body of the first loop
|
||||
* in `add', except that this loop does a `+=' instead of a `+'.
|
||||
*/
|
||||
temp = blk[k] + getShiftedBlock(b, j, i2);
|
||||
carryOut = (temp < blk[k]);
|
||||
if (carryIn) {
|
||||
temp++;
|
||||
carryOut |= (temp == 0);
|
||||
}
|
||||
blk[k] = temp;
|
||||
carryIn = carryOut;
|
||||
}
|
||||
// No more extra iteration to deal with `bHigh'.
|
||||
// Roll-over a carry as necessary.
|
||||
for (; carryIn; k++) {
|
||||
blk[k]++;
|
||||
carryIn = (blk[k] == 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Zap possible leading zero
|
||||
if (blk[len - 1] == 0)
|
||||
len--;
|
||||
}
|
||||
|
||||
/*
|
||||
* DIVISION WITH REMAINDER
|
||||
* This monstrous function mods *this by the given divisor b while storing the
|
||||
* quotient in the given object q; at the end, *this contains the remainder.
|
||||
* The seemingly bizarre pattern of inputs and outputs was chosen so that the
|
||||
* function copies as little as possible (since it is implemented by repeated
|
||||
* subtraction of multiples of b from *this).
|
||||
*
|
||||
* "modWithQuotient" might be a better name for this function, but I would
|
||||
* rather not change the name now.
|
||||
*/
|
||||
void BigUnsigned::divideWithRemainder(const BigUnsigned &b, BigUnsigned &q) {
|
||||
/* Defending against aliased calls is more complex than usual because we
|
||||
* are writing to both *this and q.
|
||||
*
|
||||
* It would be silly to try to write quotient and remainder to the
|
||||
* same variable. Rule that out right away. */
|
||||
if (this == &q)
|
||||
throw "BigUnsigned::divideWithRemainder: Cannot write quotient and remainder into the same variable";
|
||||
/* Now *this and q are separate, so the only concern is that b might be
|
||||
* aliased to one of them. If so, use a temporary copy of b. */
|
||||
if (this == &b || &q == &b) {
|
||||
BigUnsigned tmpB(b);
|
||||
divideWithRemainder(tmpB, q);
|
||||
return;
|
||||
}
|
||||
|
||||
/*
|
||||
* Knuth's definition of mod (which this function uses) is somewhat
|
||||
* different from the C++ definition of % in case of division by 0.
|
||||
*
|
||||
* We let a / 0 == 0 (it doesn't matter much) and a % 0 == a, no
|
||||
* exceptions thrown. This allows us to preserve both Knuth's demand
|
||||
* that a mod 0 == a and the useful property that
|
||||
* (a / b) * b + (a % b) == a.
|
||||
*/
|
||||
if (b.len == 0) {
|
||||
q.len = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
/*
|
||||
* If *this.len < b.len, then *this < b, and we can be sure that b doesn't go into
|
||||
* *this at all. The quotient is 0 and *this is already the remainder (so leave it alone).
|
||||
*/
|
||||
if (len < b.len) {
|
||||
q.len = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
// At this point we know (*this).len >= b.len > 0. (Whew!)
|
||||
|
||||
/*
|
||||
* Overall method:
|
||||
*
|
||||
* For each appropriate i and i2, decreasing:
|
||||
* Subtract (b << (i blocks and i2 bits)) from *this, storing the
|
||||
* result in subtractBuf.
|
||||
* If the subtraction succeeds with a nonnegative result:
|
||||
* Turn on bit i2 of block i of the quotient q.
|
||||
* Copy subtractBuf back into *this.
|
||||
* Otherwise bit i2 of block i remains off, and *this is unchanged.
|
||||
*
|
||||
* Eventually q will contain the entire quotient, and *this will
|
||||
* be left with the remainder.
|
||||
*
|
||||
* subtractBuf[x] corresponds to blk[x], not blk[x+i], since 2005.01.11.
|
||||
* But on a single iteration, we don't touch the i lowest blocks of blk
|
||||
* (and don't use those of subtractBuf) because these blocks are
|
||||
* unaffected by the subtraction: we are subtracting
|
||||
* (b << (i blocks and i2 bits)), which ends in at least `i' zero
|
||||
* blocks. */
|
||||
// Variables for the calculation
|
||||
Index i, j, k;
|
||||
unsigned int i2;
|
||||
Blk temp;
|
||||
bool borrowIn, borrowOut;
|
||||
|
||||
/*
|
||||
* Make sure we have an extra zero block just past the value.
|
||||
*
|
||||
* When we attempt a subtraction, we might shift `b' so
|
||||
* its first block begins a few bits left of the dividend,
|
||||
* and then we'll try to compare these extra bits with
|
||||
* a nonexistent block to the left of the dividend. The
|
||||
* extra zero block ensures sensible behavior; we need
|
||||
* an extra block in `subtractBuf' for exactly the same reason.
|
||||
*/
|
||||
Index origLen = len; // Save real length.
|
||||
/* To avoid an out-of-bounds access in case of reallocation, allocate
|
||||
* first and then increment the logical length. */
|
||||
allocateAndCopy(len + 1);
|
||||
len++;
|
||||
blk[origLen] = 0; // Zero the added block.
|
||||
|
||||
// subtractBuf holds part of the result of a subtraction; see above.
|
||||
Blk *subtractBuf = new Blk[len];
|
||||
|
||||
// Set preliminary length for quotient and make room
|
||||
q.len = origLen - b.len + 1;
|
||||
q.allocate(q.len);
|
||||
// Zero out the quotient
|
||||
for (i = 0; i < q.len; i++)
|
||||
q.blk[i] = 0;
|
||||
|
||||
// For each possible left-shift of b in blocks...
|
||||
i = q.len;
|
||||
while (i > 0) {
|
||||
i--;
|
||||
// For each possible left-shift of b in bits...
|
||||
// (Remember, N is the number of bits in a Blk.)
|
||||
q.blk[i] = 0;
|
||||
i2 = N;
|
||||
while (i2 > 0) {
|
||||
i2--;
|
||||
/*
|
||||
* Subtract b, shifted left i blocks and i2 bits, from *this,
|
||||
* and store the answer in subtractBuf. In the for loop, `k == i + j'.
|
||||
*
|
||||
* Compare this to the middle section of `multiply'. They
|
||||
* are in many ways analogous. See especially the discussion
|
||||
* of `getShiftedBlock'.
|
||||
*/
|
||||
for (j = 0, k = i, borrowIn = false; j <= b.len; j++, k++) {
|
||||
temp = blk[k] - getShiftedBlock(b, j, i2);
|
||||
borrowOut = (temp > blk[k]);
|
||||
if (borrowIn) {
|
||||
borrowOut |= (temp == 0);
|
||||
temp--;
|
||||
}
|
||||
// Since 2005.01.11, indices of `subtractBuf' directly match those of `blk', so use `k'.
|
||||
subtractBuf[k] = temp;
|
||||
borrowIn = borrowOut;
|
||||
}
|
||||
// No more extra iteration to deal with `bHigh'.
|
||||
// Roll-over a borrow as necessary.
|
||||
for (; k < origLen && borrowIn; k++) {
|
||||
borrowIn = (blk[k] == 0);
|
||||
subtractBuf[k] = blk[k] - 1;
|
||||
}
|
||||
/*
|
||||
* If the subtraction was performed successfully (!borrowIn),
|
||||
* set bit i2 in block i of the quotient.
|
||||
*
|
||||
* Then, copy the portion of subtractBuf filled by the subtraction
|
||||
* back to *this. This portion starts with block i and ends--
|
||||
* where? Not necessarily at block `i + b.len'! Well, we
|
||||
* increased k every time we saved a block into subtractBuf, so
|
||||
* the region of subtractBuf we copy is just [i, k).
|
||||
*/
|
||||
if (!borrowIn) {
|
||||
q.blk[i] |= (Blk(1) << i2);
|
||||
while (k > i) {
|
||||
k--;
|
||||
blk[k] = subtractBuf[k];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Zap possible leading zero in quotient
|
||||
if (q.blk[q.len - 1] == 0)
|
||||
q.len--;
|
||||
// Zap any/all leading zeros in remainder
|
||||
zapLeadingZeros();
|
||||
// Deallocate subtractBuf.
|
||||
// (Thanks to Brad Spencer for noticing my accidental omission of this!)
|
||||
delete [] subtractBuf;
|
||||
}
|
||||
|
||||
/* BITWISE OPERATORS
|
||||
* These are straightforward blockwise operations except that they differ in
|
||||
* the output length and the necessity of zapLeadingZeros. */
|
||||
|
||||
void BigUnsigned::bitAnd(const BigUnsigned &a, const BigUnsigned &b) {
|
||||
DTRT_ALIASED(this == &a || this == &b, bitAnd(a, b));
|
||||
// The bitwise & can't be longer than either operand.
|
||||
len = (a.len >= b.len) ? b.len : a.len;
|
||||
allocate(len);
|
||||
Index i;
|
||||
for (i = 0; i < len; i++)
|
||||
blk[i] = a.blk[i] & b.blk[i];
|
||||
zapLeadingZeros();
|
||||
}
|
||||
|
||||
void BigUnsigned::bitOr(const BigUnsigned &a, const BigUnsigned &b) {
|
||||
DTRT_ALIASED(this == &a || this == &b, bitOr(a, b));
|
||||
Index i;
|
||||
const BigUnsigned *a2, *b2;
|
||||
if (a.len >= b.len) {
|
||||
a2 = &a;
|
||||
b2 = &b;
|
||||
} else {
|
||||
a2 = &b;
|
||||
b2 = &a;
|
||||
}
|
||||
allocate(a2->len);
|
||||
for (i = 0; i < b2->len; i++)
|
||||
blk[i] = a2->blk[i] | b2->blk[i];
|
||||
for (; i < a2->len; i++)
|
||||
blk[i] = a2->blk[i];
|
||||
len = a2->len;
|
||||
// Doesn't need zapLeadingZeros.
|
||||
}
|
||||
|
||||
void BigUnsigned::bitXor(const BigUnsigned &a, const BigUnsigned &b) {
|
||||
DTRT_ALIASED(this == &a || this == &b, bitXor(a, b));
|
||||
Index i;
|
||||
const BigUnsigned *a2, *b2;
|
||||
if (a.len >= b.len) {
|
||||
a2 = &a;
|
||||
b2 = &b;
|
||||
} else {
|
||||
a2 = &b;
|
||||
b2 = &a;
|
||||
}
|
||||
allocate(a2->len);
|
||||
for (i = 0; i < b2->len; i++)
|
||||
blk[i] = a2->blk[i] ^ b2->blk[i];
|
||||
for (; i < a2->len; i++)
|
||||
blk[i] = a2->blk[i];
|
||||
len = a2->len;
|
||||
zapLeadingZeros();
|
||||
}
|
||||
|
||||
void BigUnsigned::bitShiftLeft(const BigUnsigned &a, int b) {
|
||||
DTRT_ALIASED(this == &a, bitShiftLeft(a, b));
|
||||
if (b < 0) {
|
||||
if (b << 1 == 0)
|
||||
throw "BigUnsigned::bitShiftLeft: "
|
||||
"Pathological shift amount not implemented";
|
||||
else {
|
||||
bitShiftRight(a, -b);
|
||||
return;
|
||||
}
|
||||
}
|
||||
Index shiftBlocks = b / N;
|
||||
unsigned int shiftBits = b % N;
|
||||
// + 1: room for high bits nudged left into another block
|
||||
len = a.len + shiftBlocks + 1;
|
||||
allocate(len);
|
||||
Index i, j;
|
||||
for (i = 0; i < shiftBlocks; i++)
|
||||
blk[i] = 0;
|
||||
for (j = 0, i = shiftBlocks; j <= a.len; j++, i++)
|
||||
blk[i] = getShiftedBlock(a, j, shiftBits);
|
||||
// Zap possible leading zero
|
||||
if (blk[len - 1] == 0)
|
||||
len--;
|
||||
}
|
||||
|
||||
void BigUnsigned::bitShiftRight(const BigUnsigned &a, int b) {
|
||||
DTRT_ALIASED(this == &a, bitShiftRight(a, b));
|
||||
if (b < 0) {
|
||||
if (b << 1 == 0)
|
||||
throw "BigUnsigned::bitShiftRight: "
|
||||
"Pathological shift amount not implemented";
|
||||
else {
|
||||
bitShiftLeft(a, -b);
|
||||
return;
|
||||
}
|
||||
}
|
||||
// This calculation is wacky, but expressing the shift as a left bit shift
|
||||
// within each block lets us use getShiftedBlock.
|
||||
Index rightShiftBlocks = (b + N - 1) / N;
|
||||
unsigned int leftShiftBits = N * rightShiftBlocks - b;
|
||||
// Now (N * rightShiftBlocks - leftShiftBits) == b
|
||||
// and 0 <= leftShiftBits < N.
|
||||
if (rightShiftBlocks >= a.len + 1) {
|
||||
// All of a is guaranteed to be shifted off, even considering the left
|
||||
// bit shift.
|
||||
len = 0;
|
||||
return;
|
||||
}
|
||||
// Now we're allocating a positive amount.
|
||||
// + 1: room for high bits nudged left into another block
|
||||
len = a.len + 1 - rightShiftBlocks;
|
||||
allocate(len);
|
||||
Index i, j;
|
||||
for (j = rightShiftBlocks, i = 0; j <= a.len; j++, i++)
|
||||
blk[i] = getShiftedBlock(a, j, leftShiftBits);
|
||||
// Zap possible leading zero
|
||||
if (blk[len - 1] == 0)
|
||||
len--;
|
||||
}
|
||||
|
||||
// INCREMENT/DECREMENT OPERATORS
|
||||
|
||||
// Prefix increment
|
||||
void BigUnsigned::operator ++() {
|
||||
Index i;
|
||||
bool carry = true;
|
||||
for (i = 0; i < len && carry; i++) {
|
||||
blk[i]++;
|
||||
carry = (blk[i] == 0);
|
||||
}
|
||||
if (carry) {
|
||||
// Allocate and then increase length, as in divideWithRemainder
|
||||
allocateAndCopy(len + 1);
|
||||
len++;
|
||||
blk[i] = 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Postfix increment: same as prefix
|
||||
void BigUnsigned::operator ++(int) {
|
||||
operator ++();
|
||||
}
|
||||
|
||||
// Prefix decrement
|
||||
void BigUnsigned::operator --() {
|
||||
if (len == 0)
|
||||
throw "BigUnsigned::operator --(): Cannot decrement an unsigned zero";
|
||||
Index i;
|
||||
bool borrow = true;
|
||||
for (i = 0; borrow; i++) {
|
||||
borrow = (blk[i] == 0);
|
||||
blk[i]--;
|
||||
}
|
||||
// Zap possible leading zero (there can only be one)
|
||||
if (blk[len - 1] == 0)
|
||||
len--;
|
||||
}
|
||||
|
||||
// Postfix decrement: same as prefix
|
||||
void BigUnsigned::operator --(int) {
|
||||
operator --();
|
||||
}
|
|
@ -1,418 +0,0 @@
|
|||
#ifndef BIGUNSIGNED_H
|
||||
#define BIGUNSIGNED_H
|
||||
|
||||
#include "NumberlikeArray.hh"
|
||||
|
||||
/* A BigUnsigned object represents a nonnegative integer of size limited only by
|
||||
* available memory. BigUnsigneds support most mathematical operators and can
|
||||
* be converted to and from most primitive integer types.
|
||||
*
|
||||
* The number is stored as a NumberlikeArray of unsigned longs as if it were
|
||||
* written in base 256^sizeof(unsigned long). The least significant block is
|
||||
* first, and the length is such that the most significant block is nonzero. */
|
||||
class BigUnsigned : protected NumberlikeArray<unsigned long> {
|
||||
|
||||
public:
|
||||
// Enumeration for the result of a comparison.
|
||||
enum CmpRes { less = -1, equal = 0, greater = 1 };
|
||||
|
||||
// BigUnsigneds are built with a Blk type of unsigned long.
|
||||
typedef unsigned long Blk;
|
||||
|
||||
typedef NumberlikeArray<Blk>::Index Index;
|
||||
using NumberlikeArray<Blk>::N;
|
||||
|
||||
protected:
|
||||
// Creates a BigUnsigned with a capacity; for internal use.
|
||||
BigUnsigned(int, Index c) : NumberlikeArray<Blk>(0, c) {}
|
||||
|
||||
// Decreases len to eliminate any leading zero blocks.
|
||||
void zapLeadingZeros() {
|
||||
while (len > 0 && blk[len - 1] == 0)
|
||||
len--;
|
||||
}
|
||||
|
||||
public:
|
||||
// Constructs zero.
|
||||
BigUnsigned() : NumberlikeArray<Blk>() {}
|
||||
|
||||
// Copy constructor
|
||||
BigUnsigned(const BigUnsigned &x) : NumberlikeArray<Blk>(x) {}
|
||||
|
||||
// Assignment operator
|
||||
void operator=(const BigUnsigned &x) {
|
||||
NumberlikeArray<Blk>::operator =(x);
|
||||
}
|
||||
|
||||
// Constructor that copies from a given array of blocks.
|
||||
BigUnsigned(const Blk *b, Index blen) : NumberlikeArray<Blk>(b, blen) {
|
||||
// Eliminate any leading zeros we may have been passed.
|
||||
zapLeadingZeros();
|
||||
}
|
||||
|
||||
// Destructor. NumberlikeArray does the delete for us.
|
||||
~BigUnsigned() {}
|
||||
|
||||
// Constructors from primitive integer types
|
||||
BigUnsigned(unsigned long x);
|
||||
BigUnsigned( long x);
|
||||
BigUnsigned(unsigned int x);
|
||||
BigUnsigned( int x);
|
||||
BigUnsigned(unsigned short x);
|
||||
BigUnsigned( short x);
|
||||
protected:
|
||||
// Helpers
|
||||
template <class X> void initFromPrimitive (X x);
|
||||
template <class X> void initFromSignedPrimitive(X x);
|
||||
public:
|
||||
|
||||
/* Converters to primitive integer types
|
||||
* The implicit conversion operators caused trouble, so these are now
|
||||
* named. */
|
||||
unsigned long toUnsignedLong () const;
|
||||
long toLong () const;
|
||||
unsigned int toUnsignedInt () const;
|
||||
int toInt () const;
|
||||
unsigned short toUnsignedShort() const;
|
||||
short toShort () const;
|
||||
protected:
|
||||
// Helpers
|
||||
template <class X> X convertToSignedPrimitive() const;
|
||||
template <class X> X convertToPrimitive () const;
|
||||
public:
|
||||
|
||||
// BIT/BLOCK ACCESSORS
|
||||
|
||||
// Expose these from NumberlikeArray directly.
|
||||
using NumberlikeArray<Blk>::getCapacity;
|
||||
using NumberlikeArray<Blk>::getLength;
|
||||
|
||||
/* Returns the requested block, or 0 if it is beyond the length (as if
|
||||
* the number had 0s infinitely to the left). */
|
||||
Blk getBlock(Index i) const { return i >= len ? 0 : blk[i]; }
|
||||
/* Sets the requested block. The number grows or shrinks as necessary. */
|
||||
void setBlock(Index i, Blk newBlock);
|
||||
|
||||
// The number is zero if and only if the canonical length is zero.
|
||||
bool isZero() const { return NumberlikeArray<Blk>::isEmpty(); }
|
||||
|
||||
/* Returns the length of the number in bits, i.e., zero if the number
|
||||
* is zero and otherwise one more than the largest value of bi for
|
||||
* which getBit(bi) returns true. */
|
||||
Index bitLength() const;
|
||||
/* Get the state of bit bi, which has value 2^bi. Bits beyond the
|
||||
* number's length are considered to be 0. */
|
||||
bool getBit(Index bi) const {
|
||||
return (getBlock(bi / N) & (Blk(1) << (bi % N))) != 0;
|
||||
}
|
||||
/* Sets the state of bit bi to newBit. The number grows or shrinks as
|
||||
* necessary. */
|
||||
void setBit(Index bi, bool newBit);
|
||||
|
||||
// COMPARISONS
|
||||
|
||||
// Compares this to x like Perl's <=>
|
||||
CmpRes compareTo(const BigUnsigned &x) const;
|
||||
|
||||
// Ordinary comparison operators
|
||||
bool operator ==(const BigUnsigned &x) const {
|
||||
return NumberlikeArray<Blk>::operator ==(x);
|
||||
}
|
||||
bool operator !=(const BigUnsigned &x) const {
|
||||
return NumberlikeArray<Blk>::operator !=(x);
|
||||
}
|
||||
bool operator < (const BigUnsigned &x) const { return compareTo(x) == less ; }
|
||||
bool operator <=(const BigUnsigned &x) const { return compareTo(x) != greater; }
|
||||
bool operator >=(const BigUnsigned &x) const { return compareTo(x) != less ; }
|
||||
bool operator > (const BigUnsigned &x) const { return compareTo(x) == greater; }
|
||||
|
||||
/*
|
||||
* BigUnsigned and BigInteger both provide three kinds of operators.
|
||||
* Here ``big-integer'' refers to BigInteger or BigUnsigned.
|
||||
*
|
||||
* (1) Overloaded ``return-by-value'' operators:
|
||||
* +, -, *, /, %, unary -, &, |, ^, <<, >>.
|
||||
* Big-integer code using these operators looks identical to code using
|
||||
* the primitive integer types. These operators take one or two
|
||||
* big-integer inputs and return a big-integer result, which can then
|
||||
* be assigned to a BigInteger variable or used in an expression.
|
||||
* Example:
|
||||
* BigInteger a(1), b = 1;
|
||||
* BigInteger c = a + b;
|
||||
*
|
||||
* (2) Overloaded assignment operators:
|
||||
* +=, -=, *=, /=, %=, flipSign, &=, |=, ^=, <<=, >>=, ++, --.
|
||||
* Again, these are used on big integers just like on ints. They take
|
||||
* one writable big integer that both provides an operand and receives a
|
||||
* result. Most also take a second read-only operand.
|
||||
* Example:
|
||||
* BigInteger a(1), b(1);
|
||||
* a += b;
|
||||
*
|
||||
* (3) Copy-less operations: `add', `subtract', etc.
|
||||
* These named methods take operands as arguments and store the result
|
||||
* in the receiver (*this), avoiding unnecessary copies and allocations.
|
||||
* `divideWithRemainder' is special: it both takes the dividend from and
|
||||
* stores the remainder into the receiver, and it takes a separate
|
||||
* object in which to store the quotient. NOTE: If you are wondering
|
||||
* why these don't return a value, you probably mean to use the
|
||||
* overloaded return-by-value operators instead.
|
||||
*
|
||||
* Examples:
|
||||
* BigInteger a(43), b(7), c, d;
|
||||
*
|
||||
* c = a + b; // Now c == 50.
|
||||
* c.add(a, b); // Same effect but without the two copies.
|
||||
*
|
||||
* c.divideWithRemainder(b, d);
|
||||
* // 50 / 7; now d == 7 (quotient) and c == 1 (remainder).
|
||||
*
|
||||
* // ``Aliased'' calls now do the right thing using a temporary
|
||||
* // copy, but see note on `divideWithRemainder'.
|
||||
* a.add(a, b);
|
||||
*/
|
||||
|
||||
// COPY-LESS OPERATIONS
|
||||
|
||||
// These 8: Arguments are read-only operands, result is saved in *this.
|
||||
void add(const BigUnsigned &a, const BigUnsigned &b);
|
||||
void subtract(const BigUnsigned &a, const BigUnsigned &b);
|
||||
void multiply(const BigUnsigned &a, const BigUnsigned &b);
|
||||
void bitAnd(const BigUnsigned &a, const BigUnsigned &b);
|
||||
void bitOr(const BigUnsigned &a, const BigUnsigned &b);
|
||||
void bitXor(const BigUnsigned &a, const BigUnsigned &b);
|
||||
/* Negative shift amounts translate to opposite-direction shifts,
|
||||
* except for -2^(8*sizeof(int)-1) which is unimplemented. */
|
||||
void bitShiftLeft(const BigUnsigned &a, int b);
|
||||
void bitShiftRight(const BigUnsigned &a, int b);
|
||||
|
||||
/* `a.divideWithRemainder(b, q)' is like `q = a / b, a %= b'.
|
||||
* / and % use semantics similar to Knuth's, which differ from the
|
||||
* primitive integer semantics under division by zero. See the
|
||||
* implementation in BigUnsigned.cc for details.
|
||||
* `a.divideWithRemainder(b, a)' throws an exception: it doesn't make
|
||||
* sense to write quotient and remainder into the same variable. */
|
||||
void divideWithRemainder(const BigUnsigned &b, BigUnsigned &q);
|
||||
|
||||
/* `divide' and `modulo' are no longer offered. Use
|
||||
* `divideWithRemainder' instead. */
|
||||
|
||||
// OVERLOADED RETURN-BY-VALUE OPERATORS
|
||||
BigUnsigned operator +(const BigUnsigned &x) const;
|
||||
BigUnsigned operator -(const BigUnsigned &x) const;
|
||||
BigUnsigned operator *(const BigUnsigned &x) const;
|
||||
BigUnsigned operator /(const BigUnsigned &x) const;
|
||||
BigUnsigned operator %(const BigUnsigned &x) const;
|
||||
/* OK, maybe unary minus could succeed in one case, but it really
|
||||
* shouldn't be used, so it isn't provided. */
|
||||
BigUnsigned operator &(const BigUnsigned &x) const;
|
||||
BigUnsigned operator |(const BigUnsigned &x) const;
|
||||
BigUnsigned operator ^(const BigUnsigned &x) const;
|
||||
BigUnsigned operator <<(int b) const;
|
||||
BigUnsigned operator >>(int b) const;
|
||||
|
||||
// OVERLOADED ASSIGNMENT OPERATORS
|
||||
void operator +=(const BigUnsigned &x);
|
||||
void operator -=(const BigUnsigned &x);
|
||||
void operator *=(const BigUnsigned &x);
|
||||
void operator /=(const BigUnsigned &x);
|
||||
void operator %=(const BigUnsigned &x);
|
||||
void operator &=(const BigUnsigned &x);
|
||||
void operator |=(const BigUnsigned &x);
|
||||
void operator ^=(const BigUnsigned &x);
|
||||
void operator <<=(int b);
|
||||
void operator >>=(int b);
|
||||
|
||||
/* INCREMENT/DECREMENT OPERATORS
|
||||
* To discourage messy coding, these do not return *this, so prefix
|
||||
* and postfix behave the same. */
|
||||
void operator ++( );
|
||||
void operator ++(int);
|
||||
void operator --( );
|
||||
void operator --(int);
|
||||
|
||||
// Helper function that needs access to BigUnsigned internals
|
||||
friend Blk getShiftedBlock(const BigUnsigned &num, Index x,
|
||||
unsigned int y);
|
||||
|
||||
// See BigInteger.cc.
|
||||
template <class X>
|
||||
friend X convertBigUnsignedToPrimitiveAccess(const BigUnsigned &a);
|
||||
};
|
||||
|
||||
/* Implementing the return-by-value and assignment operators in terms of the
|
||||
* copy-less operations. The copy-less operations are responsible for making
|
||||
* any necessary temporary copies to work around aliasing. */
|
||||
|
||||
inline BigUnsigned BigUnsigned::operator +(const BigUnsigned &x) const {
|
||||
BigUnsigned ans;
|
||||
ans.add(*this, x);
|
||||
return ans;
|
||||
}
|
||||
inline BigUnsigned BigUnsigned::operator -(const BigUnsigned &x) const {
|
||||
BigUnsigned ans;
|
||||
ans.subtract(*this, x);
|
||||
return ans;
|
||||
}
|
||||
inline BigUnsigned BigUnsigned::operator *(const BigUnsigned &x) const {
|
||||
BigUnsigned ans;
|
||||
ans.multiply(*this, x);
|
||||
return ans;
|
||||
}
|
||||
inline BigUnsigned BigUnsigned::operator /(const BigUnsigned &x) const {
|
||||
if (x.isZero()) throw "BigUnsigned::operator /: division by zero";
|
||||
BigUnsigned q, r;
|
||||
r = *this;
|
||||
r.divideWithRemainder(x, q);
|
||||
return q;
|
||||
}
|
||||
inline BigUnsigned BigUnsigned::operator %(const BigUnsigned &x) const {
|
||||
if (x.isZero()) throw "BigUnsigned::operator %: division by zero";
|
||||
BigUnsigned q, r;
|
||||
r = *this;
|
||||
r.divideWithRemainder(x, q);
|
||||
return r;
|
||||
}
|
||||
inline BigUnsigned BigUnsigned::operator &(const BigUnsigned &x) const {
|
||||
BigUnsigned ans;
|
||||
ans.bitAnd(*this, x);
|
||||
return ans;
|
||||
}
|
||||
inline BigUnsigned BigUnsigned::operator |(const BigUnsigned &x) const {
|
||||
BigUnsigned ans;
|
||||
ans.bitOr(*this, x);
|
||||
return ans;
|
||||
}
|
||||
inline BigUnsigned BigUnsigned::operator ^(const BigUnsigned &x) const {
|
||||
BigUnsigned ans;
|
||||
ans.bitXor(*this, x);
|
||||
return ans;
|
||||
}
|
||||
inline BigUnsigned BigUnsigned::operator <<(int b) const {
|
||||
BigUnsigned ans;
|
||||
ans.bitShiftLeft(*this, b);
|
||||
return ans;
|
||||
}
|
||||
inline BigUnsigned BigUnsigned::operator >>(int b) const {
|
||||
BigUnsigned ans;
|
||||
ans.bitShiftRight(*this, b);
|
||||
return ans;
|
||||
}
|
||||
|
||||
inline void BigUnsigned::operator +=(const BigUnsigned &x) {
|
||||
add(*this, x);
|
||||
}
|
||||
inline void BigUnsigned::operator -=(const BigUnsigned &x) {
|
||||
subtract(*this, x);
|
||||
}
|
||||
inline void BigUnsigned::operator *=(const BigUnsigned &x) {
|
||||
multiply(*this, x);
|
||||
}
|
||||
inline void BigUnsigned::operator /=(const BigUnsigned &x) {
|
||||
if (x.isZero()) throw "BigUnsigned::operator /=: division by zero";
|
||||
/* The following technique is slightly faster than copying *this first
|
||||
* when x is large. */
|
||||
BigUnsigned q;
|
||||
divideWithRemainder(x, q);
|
||||
// *this contains the remainder, but we overwrite it with the quotient.
|
||||
*this = q;
|
||||
}
|
||||
inline void BigUnsigned::operator %=(const BigUnsigned &x) {
|
||||
if (x.isZero()) throw "BigUnsigned::operator %=: division by zero";
|
||||
BigUnsigned q;
|
||||
// Mods *this by x. Don't care about quotient left in q.
|
||||
divideWithRemainder(x, q);
|
||||
}
|
||||
inline void BigUnsigned::operator &=(const BigUnsigned &x) {
|
||||
bitAnd(*this, x);
|
||||
}
|
||||
inline void BigUnsigned::operator |=(const BigUnsigned &x) {
|
||||
bitOr(*this, x);
|
||||
}
|
||||
inline void BigUnsigned::operator ^=(const BigUnsigned &x) {
|
||||
bitXor(*this, x);
|
||||
}
|
||||
inline void BigUnsigned::operator <<=(int b) {
|
||||
bitShiftLeft(*this, b);
|
||||
}
|
||||
inline void BigUnsigned::operator >>=(int b) {
|
||||
bitShiftRight(*this, b);
|
||||
}
|
||||
|
||||
/* Templates for conversions of BigUnsigned to and from primitive integers.
|
||||
* BigInteger.cc needs to instantiate convertToPrimitive, and the uses in
|
||||
* BigUnsigned.cc didn't do the trick; I think g++ inlined convertToPrimitive
|
||||
* instead of generating linkable instantiations. So for consistency, I put
|
||||
* all the templates here. */
|
||||
|
||||
// CONSTRUCTION FROM PRIMITIVE INTEGERS
|
||||
|
||||
/* Initialize this BigUnsigned from the given primitive integer. The same
|
||||
* pattern works for all primitive integer types, so I put it into a template to
|
||||
* reduce code duplication. (Don't worry: this is protected and we instantiate
|
||||
* it only with primitive integer types.) Type X could be signed, but x is
|
||||
* known to be nonnegative. */
|
||||
template <class X>
|
||||
void BigUnsigned::initFromPrimitive(X x) {
|
||||
if (x == 0)
|
||||
; // NumberlikeArray already initialized us to zero.
|
||||
else {
|
||||
// Create a single block. blk is NULL; no need to delete it.
|
||||
cap = 1;
|
||||
blk = new Blk[1];
|
||||
len = 1;
|
||||
blk[0] = Blk(x);
|
||||
}
|
||||
}
|
||||
|
||||
/* Ditto, but first check that x is nonnegative. I could have put the check in
|
||||
* initFromPrimitive and let the compiler optimize it out for unsigned-type
|
||||
* instantiations, but I wanted to avoid the warning stupidly issued by g++ for
|
||||
* a condition that is constant in *any* instantiation, even if not in all. */
|
||||
template <class X>
|
||||
void BigUnsigned::initFromSignedPrimitive(X x) {
|
||||
if (x < 0)
|
||||
throw "BigUnsigned constructor: "
|
||||
"Cannot construct a BigUnsigned from a negative number";
|
||||
else
|
||||
initFromPrimitive(x);
|
||||
}
|
||||
|
||||
// CONVERSION TO PRIMITIVE INTEGERS
|
||||
|
||||
/* Template with the same idea as initFromPrimitive. This might be slightly
|
||||
* slower than the previous version with the masks, but it's much shorter and
|
||||
* clearer, which is the library's stated goal. */
|
||||
template <class X>
|
||||
X BigUnsigned::convertToPrimitive() const {
|
||||
if (len == 0)
|
||||
// The number is zero; return zero.
|
||||
return 0;
|
||||
else if (len == 1) {
|
||||
// The single block might fit in an X. Try the conversion.
|
||||
X x = X(blk[0]);
|
||||
// Make sure the result accurately represents the block.
|
||||
if (Blk(x) == blk[0])
|
||||
// Successful conversion.
|
||||
return x;
|
||||
// Otherwise fall through.
|
||||
}
|
||||
throw "BigUnsigned::to<Primitive>: "
|
||||
"Value is too big to fit in the requested type";
|
||||
}
|
||||
|
||||
/* Wrap the above in an x >= 0 test to make sure we got a nonnegative result,
|
||||
* not a negative one that happened to convert back into the correct nonnegative
|
||||
* one. (E.g., catch incorrect conversion of 2^31 to the long -2^31.) Again,
|
||||
* separated to avoid a g++ warning. */
|
||||
template <class X>
|
||||
X BigUnsigned::convertToSignedPrimitive() const {
|
||||
X x = convertToPrimitive<X>();
|
||||
if (x >= 0)
|
||||
return x;
|
||||
else
|
||||
throw "BigUnsigned::to(Primitive): "
|
||||
"Value is too big to fit in the requested type";
|
||||
}
|
||||
|
||||
#endif
|
|
@ -1,125 +0,0 @@
|
|||
#include "BigUnsignedInABase.hh"
|
||||
|
||||
BigUnsignedInABase::BigUnsignedInABase(const Digit *d, Index l, Base base)
|
||||
: NumberlikeArray<Digit>(d, l), base(base) {
|
||||
// Check the base
|
||||
if (base < 2)
|
||||
throw "BigUnsignedInABase::BigUnsignedInABase(const Digit *, Index, Base): The base must be at least 2";
|
||||
|
||||
// Validate the digits.
|
||||
for (Index i = 0; i < l; i++)
|
||||
if (blk[i] >= base)
|
||||
throw "BigUnsignedInABase::BigUnsignedInABase(const Digit *, Index, Base): A digit is too large for the specified base";
|
||||
|
||||
// Eliminate any leading zeros we may have been passed.
|
||||
zapLeadingZeros();
|
||||
}
|
||||
|
||||
namespace {
|
||||
unsigned int bitLen(unsigned int x) {
|
||||
unsigned int len = 0;
|
||||
while (x > 0) {
|
||||
x >>= 1;
|
||||
len++;
|
||||
}
|
||||
return len;
|
||||
}
|
||||
unsigned int ceilingDiv(unsigned int a, unsigned int b) {
|
||||
return (a + b - 1) / b;
|
||||
}
|
||||
}
|
||||
|
||||
BigUnsignedInABase::BigUnsignedInABase(const BigUnsigned &x, Base base) {
|
||||
// Check the base
|
||||
if (base < 2)
|
||||
throw "BigUnsignedInABase(BigUnsigned, Base): The base must be at least 2";
|
||||
this->base = base;
|
||||
|
||||
// Get an upper bound on how much space we need
|
||||
int maxBitLenOfX = x.getLength() * BigUnsigned::N;
|
||||
int minBitsPerDigit = bitLen(base) - 1;
|
||||
int maxDigitLenOfX = ceilingDiv(maxBitLenOfX, minBitsPerDigit);
|
||||
len = maxDigitLenOfX; // Another change to comply with `staying in bounds'.
|
||||
allocate(len); // Get the space
|
||||
|
||||
BigUnsigned x2(x), buBase(base);
|
||||
Index digitNum = 0;
|
||||
|
||||
while (!x2.isZero()) {
|
||||
// Get last digit. This is like `lastDigit = x2 % buBase, x2 /= buBase'.
|
||||
BigUnsigned lastDigit(x2);
|
||||
lastDigit.divideWithRemainder(buBase, x2);
|
||||
// Save the digit.
|
||||
blk[digitNum] = lastDigit.toUnsignedShort();
|
||||
// Move on. We can't run out of room: we figured it out above.
|
||||
digitNum++;
|
||||
}
|
||||
|
||||
// Save the actual length.
|
||||
len = digitNum;
|
||||
}
|
||||
|
||||
BigUnsignedInABase::operator BigUnsigned() const {
|
||||
BigUnsigned ans(0), buBase(base), temp;
|
||||
Index digitNum = len;
|
||||
while (digitNum > 0) {
|
||||
digitNum--;
|
||||
temp.multiply(ans, buBase);
|
||||
ans.add(temp, BigUnsigned(blk[digitNum]));
|
||||
}
|
||||
return ans;
|
||||
}
|
||||
|
||||
BigUnsignedInABase::BigUnsignedInABase(const std::string &s, Base base) {
|
||||
// Check the base.
|
||||
if (base > 36)
|
||||
throw "BigUnsignedInABase(std::string, Base): The default string conversion routines use the symbol set 0-9, A-Z and therefore support only up to base 36. You tried a conversion with a base over 36; write your own string conversion routine.";
|
||||
// Save the base.
|
||||
// This pattern is seldom seen in C++, but the analogous ``this.'' is common in Java.
|
||||
this->base = base;
|
||||
|
||||
// `s.length()' is a `size_t', while `len' is a `NumberlikeArray::Index',
|
||||
// also known as an `unsigned int'. Some compilers warn without this cast.
|
||||
len = Index(s.length());
|
||||
allocate(len);
|
||||
|
||||
Index digitNum, symbolNumInString;
|
||||
for (digitNum = 0; digitNum < len; digitNum++) {
|
||||
symbolNumInString = len - 1 - digitNum;
|
||||
char theSymbol = s[symbolNumInString];
|
||||
if (theSymbol >= '0' && theSymbol <= '9')
|
||||
blk[digitNum] = theSymbol - '0';
|
||||
else if (theSymbol >= 'A' && theSymbol <= 'Z')
|
||||
blk[digitNum] = theSymbol - 'A' + 10;
|
||||
else if (theSymbol >= 'a' && theSymbol <= 'z')
|
||||
blk[digitNum] = theSymbol - 'a' + 10;
|
||||
else
|
||||
throw "BigUnsignedInABase(std::string, Base): Bad symbol in input. Only 0-9, A-Z, a-z are accepted.";
|
||||
|
||||
if (blk[digitNum] >= base)
|
||||
throw "BigUnsignedInABase::BigUnsignedInABase(const Digit *, Index, Base): A digit is too large for the specified base";
|
||||
}
|
||||
zapLeadingZeros();
|
||||
}
|
||||
|
||||
BigUnsignedInABase::operator std::string() const {
|
||||
if (base > 36)
|
||||
throw "BigUnsignedInABase ==> std::string: The default string conversion routines use the symbol set 0-9, A-Z and therefore support only up to base 36. You tried a conversion with a base over 36; write your own string conversion routine.";
|
||||
if (len == 0)
|
||||
return std::string("0");
|
||||
// Some compilers don't have push_back, so use a char * buffer instead.
|
||||
char *s = new char[len + 1];
|
||||
s[len] = '\0';
|
||||
Index digitNum, symbolNumInString;
|
||||
for (symbolNumInString = 0; symbolNumInString < len; symbolNumInString++) {
|
||||
digitNum = len - 1 - symbolNumInString;
|
||||
Digit theDigit = blk[digitNum];
|
||||
if (theDigit < 10)
|
||||
s[symbolNumInString] = char('0' + theDigit);
|
||||
else
|
||||
s[symbolNumInString] = char('A' + theDigit - 10);
|
||||
}
|
||||
std::string s2(s);
|
||||
delete [] s;
|
||||
return s2;
|
||||
}
|
|
@ -1,122 +0,0 @@
|
|||
#ifndef BIGUNSIGNEDINABASE_H
|
||||
#define BIGUNSIGNEDINABASE_H
|
||||
|
||||
#include "NumberlikeArray.hh"
|
||||
#include "BigUnsigned.hh"
|
||||
#include <string>
|
||||
|
||||
/*
|
||||
* A BigUnsignedInABase object represents a nonnegative integer of size limited
|
||||
* only by available memory, represented in a user-specified base that can fit
|
||||
* in an `unsigned short' (most can, and this saves memory).
|
||||
*
|
||||
* BigUnsignedInABase is intended as an intermediary class with little
|
||||
* functionality of its own. BigUnsignedInABase objects can be constructed
|
||||
* from, and converted to, BigUnsigneds (requiring multiplication, mods, etc.)
|
||||
* and `std::string's (by switching digit values for appropriate characters).
|
||||
*
|
||||
* BigUnsignedInABase is similar to BigUnsigned. Note the following:
|
||||
*
|
||||
* (1) They represent the number in exactly the same way, except that
|
||||
* BigUnsignedInABase uses ``digits'' (or Digit) where BigUnsigned uses
|
||||
* ``blocks'' (or Blk).
|
||||
*
|
||||
* (2) Both use the management features of NumberlikeArray. (In fact, my desire
|
||||
* to add a BigUnsignedInABase class without duplicating a lot of code led me to
|
||||
* introduce NumberlikeArray.)
|
||||
*
|
||||
* (3) The only arithmetic operation supported by BigUnsignedInABase is an
|
||||
* equality test. Use BigUnsigned for arithmetic.
|
||||
*/
|
||||
|
||||
class BigUnsignedInABase : protected NumberlikeArray<unsigned short> {
|
||||
|
||||
public:
|
||||
// The digits of a BigUnsignedInABase are unsigned shorts.
|
||||
typedef unsigned short Digit;
|
||||
// That's also the type of a base.
|
||||
typedef Digit Base;
|
||||
|
||||
protected:
|
||||
// The base in which this BigUnsignedInABase is expressed
|
||||
Base base;
|
||||
|
||||
// Creates a BigUnsignedInABase with a capacity; for internal use.
|
||||
BigUnsignedInABase(int, Index c) : NumberlikeArray<Digit>(0, c) {}
|
||||
|
||||
// Decreases len to eliminate any leading zero digits.
|
||||
void zapLeadingZeros() {
|
||||
while (len > 0 && blk[len - 1] == 0)
|
||||
len--;
|
||||
}
|
||||
|
||||
public:
|
||||
// Constructs zero in base 2.
|
||||
BigUnsignedInABase() : NumberlikeArray<Digit>(), base(2) {}
|
||||
|
||||
// Copy constructor
|
||||
BigUnsignedInABase(const BigUnsignedInABase &x) : NumberlikeArray<Digit>(x), base(x.base) {}
|
||||
|
||||
// Assignment operator
|
||||
void operator =(const BigUnsignedInABase &x) {
|
||||
NumberlikeArray<Digit>::operator =(x);
|
||||
base = x.base;
|
||||
}
|
||||
|
||||
// Constructor that copies from a given array of digits.
|
||||
BigUnsignedInABase(const Digit *d, Index l, Base base);
|
||||
|
||||
// Destructor. NumberlikeArray does the delete for us.
|
||||
~BigUnsignedInABase() {}
|
||||
|
||||
// LINKS TO BIGUNSIGNED
|
||||
BigUnsignedInABase(const BigUnsigned &x, Base base);
|
||||
operator BigUnsigned() const;
|
||||
|
||||
/* LINKS TO STRINGS
|
||||
*
|
||||
* These use the symbols ``0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'' to
|
||||
* represent digits of 0 through 35. When parsing strings, lowercase is
|
||||
* also accepted.
|
||||
*
|
||||
* All string representations are big-endian (big-place-value digits
|
||||
* first). (Computer scientists have adopted zero-based counting; why
|
||||
* can't they tolerate little-endian numbers?)
|
||||
*
|
||||
* No string representation has a ``base indicator'' like ``0x''.
|
||||
*
|
||||
* An exception is made for zero: it is converted to ``0'' and not the
|
||||
* empty string.
|
||||
*
|
||||
* If you want different conventions, write your own routines to go
|
||||
* between BigUnsignedInABase and strings. It's not hard.
|
||||
*/
|
||||
operator std::string() const;
|
||||
BigUnsignedInABase(const std::string &s, Base base);
|
||||
|
||||
public:
|
||||
|
||||
// ACCESSORS
|
||||
Base getBase() const { return base; }
|
||||
|
||||
// Expose these from NumberlikeArray directly.
|
||||
using NumberlikeArray<Digit>::getCapacity;
|
||||
using NumberlikeArray<Digit>::getLength;
|
||||
|
||||
/* Returns the requested digit, or 0 if it is beyond the length (as if
|
||||
* the number had 0s infinitely to the left). */
|
||||
Digit getDigit(Index i) const { return i >= len ? 0 : blk[i]; }
|
||||
|
||||
// The number is zero if and only if the canonical length is zero.
|
||||
bool isZero() const { return NumberlikeArray<Digit>::isEmpty(); }
|
||||
|
||||
/* Equality test. For the purposes of this test, two BigUnsignedInABase
|
||||
* values must have the same base to be equal. */
|
||||
bool operator ==(const BigUnsignedInABase &x) const {
|
||||
return base == x.base && NumberlikeArray<Digit>::operator ==(x);
|
||||
}
|
||||
bool operator !=(const BigUnsignedInABase &x) const { return !operator ==(x); }
|
||||
|
||||
};
|
||||
|
||||
#endif
|
|
@ -1,146 +0,0 @@
|
|||
Change Log
|
||||
|
||||
These entries tell you what was added, fixed, or improved in each version as
|
||||
compared to the previous one. In case you haven't noticed, a version number
|
||||
roughly corresponds to the release date of that version in `YYYY.MM.DD[.N]'
|
||||
format, where `.N' goes `.2', `.3', etc. if there are multiple versions on the
|
||||
same day. The topmost version listed is the one you have.
|
||||
|
||||
2010.04.30
|
||||
----------
|
||||
- Strengthen the advice about build/IDE configuration in the README.
|
||||
|
||||
2009.05.03
|
||||
----------
|
||||
- BigUnsigned::{get,set}Bit: Change two remaining `1 <<' to `Blk(1) <<' to work
|
||||
on systems where sizeof(unsigned int) != sizeof(Blk). Bug reported by Brad
|
||||
Spencer.
|
||||
- dataToBigInteger: Change a `delete' to `delete []' to avoid leaking memory.
|
||||
Bug reported by Nicolás Carrasco.
|
||||
|
||||
2009.03.26
|
||||
----------
|
||||
- BigUnsignedInABase(std::string) Reject digits too big for the base.
|
||||
Bug reported by Niakam Kazemi.
|
||||
|
||||
2008.07.20
|
||||
----------
|
||||
Dennis Yew pointed out serious problems with ambiguities and unwanted
|
||||
conversions when mixing BigInteger/BigUnsigned and primitive integers. To fix
|
||||
these, I removed the implicit conversions from BigInteger/BigUnsigned to
|
||||
primitive integers and from BigInteger to BigUnsigned. Removing the
|
||||
BigInteger-to-BigUnsigned conversion required changing BigInteger to have a
|
||||
BigUnsigned field instead of inheriting from it; this was a complex task but
|
||||
ultimately gave a saner design. At the same time, I went through the entire
|
||||
codebase, making the formatting and comments prettier and reworking anything I
|
||||
thought was unclear. I also added a testsuite (currently for 32-bit systems
|
||||
only); it doesn't yet cover the entire library but should help to ensure that
|
||||
things work the way they should.
|
||||
|
||||
A number of changes from version 2007.07.07 break compatibility with existing
|
||||
code that uses the library, but updating that code should be pretty easy:
|
||||
- BigInteger can no longer be implicitly converted to BigUnsigned. Use
|
||||
getMagnitude() instead.
|
||||
- BigUnsigned and BigInteger can no longer be implicitly converted to primitive
|
||||
integers. Use the toInt() family of functions instead.
|
||||
- The easy* functions have been renamed to more mature names:
|
||||
bigUnsignedToString, bigIntegerToString, stringToBigUnsigned,
|
||||
stringToBigInteger, dataToBigInteger.
|
||||
- BigInteger no longer supports bitwise operations. Get the magnitude with
|
||||
getMagnitude() and operate on that instead.
|
||||
- The old {BigUnsigned,BigInteger}::{divide,modulo} copy-less options have been
|
||||
removed. Use divideWithRemainder instead.
|
||||
- Added a base argument to BigUnsignedInABase's digit-array constructor. I
|
||||
ope no one used that constructor in its broken state anyway.
|
||||
|
||||
Other notable changes:
|
||||
- Added BigUnsigned functions setBlock, bitLength, getBit, setBit.
|
||||
- The bit-shifting operations now support negative shift amounts, which shift in
|
||||
the other direction.
|
||||
- Added some big-integer algorithms in BigIntegerAlgorithms.hh: gcd,
|
||||
extendedEuclidean, modinv, modexp.
|
||||
|
||||
2007.07.07
|
||||
----------
|
||||
Update the "Running the sample program produces this output:" comment in
|
||||
sample.cc for the bitwise operators.
|
||||
|
||||
2007.06.14
|
||||
----------
|
||||
- Implement << and >> for BigUnsigned in response to email from Marco Schulze.
|
||||
- Fix name: DOTR_ALIASED -> DTRT_ALIASED.
|
||||
- Demonstrate all bitwise operators (&, |, ^, <<, >>) in sample.cc.
|
||||
|
||||
2007.02.16
|
||||
----------
|
||||
Boris Dessy pointed out that the library threw an exception on "a *= a", so I changed all the put-here operations to handle aliased calls correctly using a temporary copy instead of throwing exceptions.
|
||||
|
||||
2006.08.14
|
||||
----------
|
||||
In BigUnsigned::bitXor, change allocate(b2->len) to allocate(a2->len): we should allocate enough space for the longer number, not the shorter one! Thanks to Sriram Sankararaman for pointing this out.
|
||||
|
||||
2006.05.03
|
||||
----------
|
||||
I ran the sample program using valgrind and discovered a `delete s' that should be `delete [] s' and a `len++' before an `allocateAndCopy(len)' that should have been after an `allocateAndCopy(len + 1)'. I fixed both. Yay for valgrind!
|
||||
|
||||
2006.05.01
|
||||
----------
|
||||
I fixed incorrect results reported by Mohand Mezmaz and related memory corruption on platforms where Blk is bigger than int. I replaced (1 << x) with (Blk(1) << x) in two places in BigUnsigned.cc.
|
||||
|
||||
2006.04.24
|
||||
----------
|
||||
Two bug fixes: BigUnsigned "++x" no longer segfaults when x grows in length, and BigUnsigned == and != are now redeclared so as to be usable. I redid the Makefile: I removed the *.tag mechanism and hard-coded the library's header dependencies, I added comments, and I made the Makefile more useful for building one's own programs instead of just the sample.
|
||||
|
||||
2006.02.26
|
||||
----------
|
||||
A few tweaks in preparation for a group to distribute the library. The project Web site has moved; I updated the references. I fixed a typo and added a missing function in NumberlikeArray.hh. I'm using Eclipse now, so you get Eclipse project files.
|
||||
|
||||
2005.03.30
|
||||
----------
|
||||
Sam Larkin found a bug in `BigInteger::subtract'; I fixed it.
|
||||
|
||||
2005.01.18
|
||||
----------
|
||||
I fixed some problems with `easyDataToBI'. Due to some multiply declared variables, this function would not compile. However, it is a template function, so the compiler parses it and doesn't compile the parsed representation until something uses the function; this is how I missed the problems. I also removed debugging output from this function.
|
||||
|
||||
2005.01.17
|
||||
----------
|
||||
A fix to some out-of-bounds accesses reported by Milan Tomic (see the comment under `BigUnsigned::divideWithRemainder'). `BigUnsigned::multiply' and `BigUnsigned::divideWithRemainder' implementations neatened up a bit with the help of a function `getShiftedBlock'. I (finally!) introduced a constant `BigUnsigned::N', the number of bits in a `BigUnsigned::Blk', which varies depending on machine word size. In both code and comments, it replaces the much clunkier `8*sizeof(Blk)'. Numerous other small changes. There's a new conversion routine `easyDataToBI' that will convert almost any format of binary data to a `BigInteger'.
|
||||
|
||||
I have inserted a significant number of new comments. Most explain unobvious aspects of the code.
|
||||
|
||||
2005.01.06
|
||||
----------
|
||||
Some changes to the way zero-length arrays are handled by `NumberlikeArray', which fixed a memory leak reported by Milan Tomic.
|
||||
|
||||
2004.12.24.2
|
||||
------------
|
||||
I tied down a couple of loose ends involving division/modulo. I added an explanation of put-here vs. overloaded operators in the sample program; this has confused too many people. Miscellaneous other improvements.
|
||||
|
||||
I believe that, at this point, the Big Integer Library makes no assumptions about the word size of the machine it is using. `BigUnsigned::Blk' is always an `unsigned long', whatever that may be, and its size is computed with `sizeof' when necessary. However, just in case, I would be interested to have someone test the library on a non-32-bit machine to see if it works.
|
||||
|
||||
2004.12.24
|
||||
----------
|
||||
This is a _major_ upgrade to the library. Among the things that have changed:
|
||||
|
||||
I wrote the original version of the library, particularly the four ``classical algorithms'' in `BigUnsigned.cc', using array indexing. Then I rewrote it to use pointers because I thought that would be faster. But recently, I revisited the code in `BigUnsigned.cc' and found that I could not begin to understand what it was doing.
|
||||
|
||||
I have decided that the drawbacks of pointers, increased coding difficulty and reduced code readability, far outweigh their speed benefits. Plus, any modern optimizing compiler should produce fast code either way. Therefore, I rewrote the library to use array indexing again. (Thank goodness for regular-expression find-and-replace. It saved me a lot of time.)
|
||||
|
||||
The put-here operations `divide' and `modulo' of each of `BigUnsigned' and `BigInteger' have been supplanted by a single operation `divideWithRemainder'. Read the profuse comments for more information on its exact behavior.
|
||||
|
||||
There is a new class `BigUnsignedInABase' that is like `BigUnsigned' but uses a user-specified, small base instead of `256 ^ sizeof(unsigned long)'. Much of the code common to the two has been factored out into `NumberlikeArray'.
|
||||
|
||||
`BigUnsignedInABase' facilitates conversion between `BigUnsigned's and digit-by-digit string representations using `std::string'. Convenience routines to do this conversion are in `BigIntegerUtils.hh'. `iostream' compatibility has been improved.
|
||||
|
||||
I would like to thank Chris Morbitzer for the e-mail message that catalyzed this major upgrade. He wanted a way to convert a string to a BigInteger. One thing just led to another, roughly in reverse order from how they are listed here.
|
||||
|
||||
2004.1216
|
||||
---------
|
||||
Brad Spencer pointed out a memory leak in `BigUnsigned::divide'. It is fixed in the December 16, 2004 version.
|
||||
|
||||
2004.1205
|
||||
---------
|
||||
After months of inactivity, I fixed a bug in the `BigInteger' division routine; thanks to David Allen for reporting the bug. I also added simple routines for decimal output to `std::ostream's, and there is a demo that prints out powers of 3.
|
||||
|
||||
~~~~
|
|
@ -1,73 +0,0 @@
|
|||
# Mention default target.
|
||||
all:
|
||||
|
||||
# Implicit rule to compile C++ files. Modify to your taste.
|
||||
%.o: %.cc
|
||||
g++ -c -O2 -Wall -Wextra -pedantic $<
|
||||
|
||||
# Components of the library.
|
||||
library-objects = \
|
||||
BigUnsigned.o \
|
||||
BigInteger.o \
|
||||
BigIntegerAlgorithms.o \
|
||||
BigUnsignedInABase.o \
|
||||
BigIntegerUtils.o \
|
||||
|
||||
library-headers = \
|
||||
NumberlikeArray.hh \
|
||||
BigUnsigned.hh \
|
||||
BigInteger.hh \
|
||||
BigIntegerAlgorithms.hh \
|
||||
BigUnsignedInABase.hh \
|
||||
BigIntegerLibrary.hh \
|
||||
|
||||
# To ``make the library'', make all its objects using the implicit rule.
|
||||
library: $(library-objects)
|
||||
|
||||
# Conservatively assume that all the objects depend on all the headers.
|
||||
$(library-objects): $(library-headers)
|
||||
|
||||
# TESTSUITE (NOTE: Currently expects a 32-bit system)
|
||||
# Compiling the testsuite.
|
||||
testsuite.o: $(library-headers)
|
||||
testsuite: testsuite.o $(library-objects)
|
||||
g++ $^ -o $@
|
||||
# Extract the expected output from the testsuite source.
|
||||
testsuite.expected: testsuite.cc
|
||||
nl -ba -p -s: $< | sed -nre 's,^ +([0-9]+):.*//([^ ]),Line \1: \2,p' >$@
|
||||
# Run the testsuite.
|
||||
.PHONY: test
|
||||
test: testsuite testsuite.expected
|
||||
./run-testsuite
|
||||
testsuite-cleanfiles = \
|
||||
testsuite.o testsuite testsuite.expected \
|
||||
testsuite.out testsuite.err
|
||||
|
||||
# The rules below build a program that uses the library. They are preset to
|
||||
# build ``sample'' from ``sample.cc''. You can change the name(s) of the
|
||||
# source file(s) and program file to build your own program, or you can write
|
||||
# your own Makefile.
|
||||
|
||||
# Components of the program.
|
||||
program = sample
|
||||
program-objects = sample.o
|
||||
|
||||
# Conservatively assume all the program source files depend on all the library
|
||||
# headers. You can change this if it is not the case.
|
||||
$(program-objects) : $(library-headers)
|
||||
|
||||
# How to link the program. The implicit rule covers individual objects.
|
||||
$(program) : $(program-objects) $(library-objects)
|
||||
g++ $^ -o $@
|
||||
|
||||
# Delete all generated files we know about.
|
||||
clean :
|
||||
rm -f $(library-objects) $(testsuite-cleanfiles) $(program-objects) $(program)
|
||||
|
||||
# I removed the *.tag dependency tracking system because it had few advantages
|
||||
# over manually entering all the dependencies. If there were a portable,
|
||||
# reliable dependency tracking system, I'd use it, but I know of no such;
|
||||
# cons and depcomp are almost good enough.
|
||||
|
||||
# Come back and define default target.
|
||||
all : library $(program)
|
|
@ -1,177 +0,0 @@
|
|||
#ifndef NUMBERLIKEARRAY_H
|
||||
#define NUMBERLIKEARRAY_H
|
||||
|
||||
// Make sure we have NULL.
|
||||
#ifndef NULL
|
||||
#define NULL 0
|
||||
#endif
|
||||
|
||||
/* A NumberlikeArray<Blk> object holds a heap-allocated array of Blk with a
|
||||
* length and a capacity and provides basic memory management features.
|
||||
* BigUnsigned and BigUnsignedInABase both subclass it.
|
||||
*
|
||||
* NumberlikeArray provides no information hiding. Subclasses should use
|
||||
* nonpublic inheritance and manually expose members as desired using
|
||||
* declarations like this:
|
||||
*
|
||||
* public:
|
||||
* NumberlikeArray< the-type-argument >::getLength;
|
||||
*/
|
||||
template <class Blk>
|
||||
class NumberlikeArray {
|
||||
public:
|
||||
|
||||
// Type for the index of a block in the array
|
||||
typedef unsigned int Index;
|
||||
// The number of bits in a block, defined below.
|
||||
static const unsigned int N;
|
||||
|
||||
// The current allocated capacity of this NumberlikeArray (in blocks)
|
||||
Index cap;
|
||||
// The actual length of the value stored in this NumberlikeArray (in blocks)
|
||||
Index len;
|
||||
// Heap-allocated array of the blocks (can be NULL if len == 0)
|
||||
Blk *blk;
|
||||
|
||||
// Constructs a ``zero'' NumberlikeArray with the given capacity.
|
||||
NumberlikeArray(Index c) : cap(c), len(0) {
|
||||
blk = (cap > 0) ? (new Blk[cap]) : NULL;
|
||||
}
|
||||
|
||||
/* Constructs a zero NumberlikeArray without allocating a backing array.
|
||||
* A subclass that doesn't know the needed capacity at initialization
|
||||
* time can use this constructor and then overwrite blk without first
|
||||
* deleting it. */
|
||||
NumberlikeArray() : cap(0), len(0) {
|
||||
blk = NULL;
|
||||
}
|
||||
|
||||
// Destructor. Note that `delete NULL' is a no-op.
|
||||
~NumberlikeArray() {
|
||||
delete [] blk;
|
||||
}
|
||||
|
||||
/* Ensures that the array has at least the requested capacity; may
|
||||
* destroy the contents. */
|
||||
void allocate(Index c);
|
||||
|
||||
/* Ensures that the array has at least the requested capacity; does not
|
||||
* destroy the contents. */
|
||||
void allocateAndCopy(Index c);
|
||||
|
||||
// Copy constructor
|
||||
NumberlikeArray(const NumberlikeArray<Blk> &x);
|
||||
|
||||
// Assignment operator
|
||||
void operator=(const NumberlikeArray<Blk> &x);
|
||||
|
||||
// Constructor that copies from a given array of blocks
|
||||
NumberlikeArray(const Blk *b, Index blen);
|
||||
|
||||
// ACCESSORS
|
||||
Index getCapacity() const { return cap; }
|
||||
Index getLength() const { return len; }
|
||||
Blk getBlock(Index i) const { return blk[i]; }
|
||||
bool isEmpty() const { return len == 0; }
|
||||
|
||||
/* Equality comparison: checks if both objects have the same length and
|
||||
* equal (==) array elements to that length. Subclasses may wish to
|
||||
* override. */
|
||||
bool operator ==(const NumberlikeArray<Blk> &x) const;
|
||||
|
||||
bool operator !=(const NumberlikeArray<Blk> &x) const {
|
||||
return !operator ==(x);
|
||||
}
|
||||
};
|
||||
|
||||
/* BEGIN TEMPLATE DEFINITIONS. They are present here so that source files that
|
||||
* include this header file can generate the necessary real definitions. */
|
||||
|
||||
template <class Blk>
|
||||
const unsigned int NumberlikeArray<Blk>::N = 8 * sizeof(Blk);
|
||||
|
||||
template <class Blk>
|
||||
void NumberlikeArray<Blk>::allocate(Index c) {
|
||||
// If the requested capacity is more than the current capacity...
|
||||
if (c > cap) {
|
||||
// Delete the old number array
|
||||
delete [] blk;
|
||||
// Allocate the new array
|
||||
cap = c;
|
||||
blk = new Blk[cap];
|
||||
}
|
||||
}
|
||||
|
||||
template <class Blk>
|
||||
void NumberlikeArray<Blk>::allocateAndCopy(Index c) {
|
||||
// If the requested capacity is more than the current capacity...
|
||||
if (c > cap) {
|
||||
Blk *oldBlk = blk;
|
||||
// Allocate the new number array
|
||||
cap = c;
|
||||
blk = new Blk[cap];
|
||||
// Copy number blocks
|
||||
Index i;
|
||||
for (i = 0; i < len; i++)
|
||||
blk[i] = oldBlk[i];
|
||||
// Delete the old array
|
||||
delete [] oldBlk;
|
||||
}
|
||||
}
|
||||
|
||||
template <class Blk>
|
||||
NumberlikeArray<Blk>::NumberlikeArray(const NumberlikeArray<Blk> &x)
|
||||
: len(x.len) {
|
||||
// Create array
|
||||
cap = len;
|
||||
blk = new Blk[cap];
|
||||
// Copy blocks
|
||||
Index i;
|
||||
for (i = 0; i < len; i++)
|
||||
blk[i] = x.blk[i];
|
||||
}
|
||||
|
||||
template <class Blk>
|
||||
void NumberlikeArray<Blk>::operator=(const NumberlikeArray<Blk> &x) {
|
||||
/* Calls like a = a have no effect; catch them before the aliasing
|
||||
* causes a problem */
|
||||
if (this == &x)
|
||||
return;
|
||||
// Copy length
|
||||
len = x.len;
|
||||
// Expand array if necessary
|
||||
allocate(len);
|
||||
// Copy number blocks
|
||||
Index i;
|
||||
for (i = 0; i < len; i++)
|
||||
blk[i] = x.blk[i];
|
||||
}
|
||||
|
||||
template <class Blk>
|
||||
NumberlikeArray<Blk>::NumberlikeArray(const Blk *b, Index blen)
|
||||
: cap(blen), len(blen) {
|
||||
// Create array
|
||||
blk = new Blk[cap];
|
||||
// Copy blocks
|
||||
Index i;
|
||||
for (i = 0; i < len; i++)
|
||||
blk[i] = b[i];
|
||||
}
|
||||
|
||||
template <class Blk>
|
||||
bool NumberlikeArray<Blk>::operator ==(const NumberlikeArray<Blk> &x) const {
|
||||
if (len != x.len)
|
||||
// Definitely unequal.
|
||||
return false;
|
||||
else {
|
||||
// Compare corresponding blocks one by one.
|
||||
Index i;
|
||||
for (i = 0; i < len; i++)
|
||||
if (blk[i] != x.blk[i])
|
||||
return false;
|
||||
// No blocks differed, so the objects are equal.
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
|
@ -1,71 +0,0 @@
|
|||
|
||||
C++ Big Integer Library
|
||||
(see ChangeLog for version)
|
||||
|
||||
http://mattmccutchen.net/bigint/
|
||||
|
||||
Written and maintained by Matt McCutchen <matt@mattmccutchen.net>
|
||||
|
||||
You can use this library in a C++ program to do arithmetic on integers of size
|
||||
limited only by your computer's memory. The library provides BigUnsigned and
|
||||
BigInteger classes that represent nonnegative integers and signed integers,
|
||||
respectively. Most of the C++ arithmetic operators are overloaded for these
|
||||
classes, so big-integer calculations are as easy as:
|
||||
|
||||
#include "BigIntegerLibrary.hh"
|
||||
|
||||
BigInteger a = 65536;
|
||||
cout << (a * a * a * a * a * a * a * a);
|
||||
|
||||
(prints 340282366920938463463374607431768211456)
|
||||
|
||||
The code in `sample.cc' demonstrates the most important features of the library.
|
||||
To get started quickly, read the code and explanations in that file and run it.
|
||||
If you want more detail or a feature not shown in `sample.cc', consult the
|
||||
consult the actual header and source files, which are thoroughly commented.
|
||||
|
||||
This library emphasizes ease of use and clarity of implementation over speed;
|
||||
some users will prefer GMP (http://swox.com/gmp/), which is faster. The code is
|
||||
intended to be reasonably portable across computers and modern C++ compilers; in
|
||||
particular, it uses whatever word size the computer provides (32-bit, 64-bit, or
|
||||
otherwise).
|
||||
|
||||
Compiling programs that use the library
|
||||
---------------------------------------
|
||||
The library consists of a folder full of C++ header files (`.hh') and source
|
||||
files (`.cc'). Your own programs should `#include' the necessary header files
|
||||
and link with the source files. A makefile that builds the sample program
|
||||
(`sample.cc') is included; you can adapt it to replace the sample with your own
|
||||
program.
|
||||
|
||||
Alternatively, you can use your own build system or IDE. In that case, you must
|
||||
put the library header files where the compiler will find them and arrange to
|
||||
have your program linked with the library source files; otherwise, you will get
|
||||
errors about missing header files or "undefined references". To learn how to do
|
||||
this, consult the documentation for the build system or IDE; don't bother asking
|
||||
me. Adding all the library files to your project will work in many IDEs but may
|
||||
not be the most desirable approach.
|
||||
|
||||
Resources
|
||||
---------
|
||||
The library's Web site (above) provides links to released versions, the current
|
||||
development version, and a mailing list for release announcements, questions,
|
||||
bug reports, and other discussion of the library. I would be delighted to hear
|
||||
from you if you like this library and/or find a good use for it.
|
||||
|
||||
Bugs and enhancements
|
||||
---------------------
|
||||
The library has been tested by me and others but is by no means bug-free. If
|
||||
you find a bug, please report it, whether it comes in the form of compiling
|
||||
trouble, a mathematically inaccurate result, or a memory-management blooper
|
||||
(since I use Java, these are altogether too common in my C++). I generally fix
|
||||
all reported bugs. You are also welcome to request enhancements, but I am
|
||||
unlikely to do substantial amounts of work on enhancements at this point.
|
||||
|
||||
Legal
|
||||
-----
|
||||
I, Matt McCutchen, the sole author of the original Big Integer Library, waive my
|
||||
copyright to it, placing it in the public domain. The library comes with
|
||||
absolutely no warranty.
|
||||
|
||||
~~~~
|
|
@ -1,14 +0,0 @@
|
|||
#ifndef _LIBICONV_H
|
||||
#define _LIBICONV_H
|
||||
#include <stddef.h>
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
typedef void* iconv_t;
|
||||
iconv_t iconv_open(const char *tocode, const char *fromcode);
|
||||
int iconv_close(iconv_t cd);
|
||||
size_t iconv(iconv_t cd, char **inbuf, size_t *inbytesleft, char **outbuf, size_t *outbytesleft);
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
#endif//_LIBICONV_H
|
|
@ -1,247 +0,0 @@
|
|||
// ISO C9x compliant stdint.h for Microsoft Visual Studio
|
||||
// Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124
|
||||
//
|
||||
// Copyright (c) 2006-2008 Alexander Chemeris
|
||||
//
|
||||
// Redistribution and use in source and binary forms, with or without
|
||||
// modification, are permitted provided that the following conditions are met:
|
||||
//
|
||||
// 1. Redistributions of source code must retain the above copyright notice,
|
||||
// this list of conditions and the following disclaimer.
|
||||
//
|
||||
// 2. Redistributions in binary form must reproduce the above copyright
|
||||
// notice, this list of conditions and the following disclaimer in the
|
||||
// documentation and/or other materials provided with the distribution.
|
||||
//
|
||||
// 3. The name of the author may be used to endorse or promote products
|
||||
// derived from this software without specific prior written permission.
|
||||
//
|
||||
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
|
||||
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
|
||||
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
|
||||
// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
||||
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
|
||||
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
|
||||
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
|
||||
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
|
||||
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
//
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
#ifndef _MSC_VER // [
|
||||
#error "Use this header only with Microsoft Visual C++ compilers!"
|
||||
#endif // _MSC_VER ]
|
||||
|
||||
#ifndef _MSC_STDINT_H_ // [
|
||||
#define _MSC_STDINT_H_
|
||||
|
||||
#if _MSC_VER > 1000
|
||||
#pragma once
|
||||
#endif
|
||||
|
||||
#include <limits.h>
|
||||
|
||||
// For Visual Studio 6 in C++ mode and for many Visual Studio versions when
|
||||
// compiling for ARM we should wrap <wchar.h> include with 'extern "C++" {}'
|
||||
// or compiler give many errors like this:
|
||||
// error C2733: second C linkage of overloaded function 'wmemchr' not allowed
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
# include <wchar.h>
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
// Define _W64 macros to mark types changing their size, like intptr_t.
|
||||
#ifndef _W64
|
||||
# if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300
|
||||
# define _W64 __w64
|
||||
# else
|
||||
# define _W64
|
||||
# endif
|
||||
#endif
|
||||
|
||||
|
||||
// 7.18.1 Integer types
|
||||
|
||||
// 7.18.1.1 Exact-width integer types
|
||||
|
||||
// Visual Studio 6 and Embedded Visual C++ 4 doesn't
|
||||
// realize that, e.g. char has the same size as __int8
|
||||
// so we give up on __intX for them.
|
||||
#if (_MSC_VER < 1300)
|
||||
typedef signed char int8_t;
|
||||
typedef signed short int16_t;
|
||||
typedef signed int int32_t;
|
||||
typedef unsigned char uint8_t;
|
||||
typedef unsigned short uint16_t;
|
||||
typedef unsigned int uint32_t;
|
||||
#else
|
||||
typedef signed __int8 int8_t;
|
||||
typedef signed __int16 int16_t;
|
||||
typedef signed __int32 int32_t;
|
||||
typedef unsigned __int8 uint8_t;
|
||||
typedef unsigned __int16 uint16_t;
|
||||
typedef unsigned __int32 uint32_t;
|
||||
#endif
|
||||
typedef signed __int64 int64_t;
|
||||
typedef unsigned __int64 uint64_t;
|
||||
|
||||
|
||||
// 7.18.1.2 Minimum-width integer types
|
||||
typedef int8_t int_least8_t;
|
||||
typedef int16_t int_least16_t;
|
||||
typedef int32_t int_least32_t;
|
||||
typedef int64_t int_least64_t;
|
||||
typedef uint8_t uint_least8_t;
|
||||
typedef uint16_t uint_least16_t;
|
||||
typedef uint32_t uint_least32_t;
|
||||
typedef uint64_t uint_least64_t;
|
||||
|
||||
// 7.18.1.3 Fastest minimum-width integer types
|
||||
typedef int8_t int_fast8_t;
|
||||
typedef int16_t int_fast16_t;
|
||||
typedef int32_t int_fast32_t;
|
||||
typedef int64_t int_fast64_t;
|
||||
typedef uint8_t uint_fast8_t;
|
||||
typedef uint16_t uint_fast16_t;
|
||||
typedef uint32_t uint_fast32_t;
|
||||
typedef uint64_t uint_fast64_t;
|
||||
|
||||
// 7.18.1.4 Integer types capable of holding object pointers
|
||||
#ifdef _WIN64 // [
|
||||
typedef signed __int64 intptr_t;
|
||||
typedef unsigned __int64 uintptr_t;
|
||||
#else // _WIN64 ][
|
||||
typedef _W64 signed int intptr_t;
|
||||
typedef _W64 unsigned int uintptr_t;
|
||||
#endif // _WIN64 ]
|
||||
|
||||
// 7.18.1.5 Greatest-width integer types
|
||||
typedef int64_t intmax_t;
|
||||
typedef uint64_t uintmax_t;
|
||||
|
||||
|
||||
// 7.18.2 Limits of specified-width integer types
|
||||
|
||||
#if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) // [ See footnote 220 at page 257 and footnote 221 at page 259
|
||||
|
||||
// 7.18.2.1 Limits of exact-width integer types
|
||||
#define INT8_MIN ((int8_t)_I8_MIN)
|
||||
#define INT8_MAX _I8_MAX
|
||||
#define INT16_MIN ((int16_t)_I16_MIN)
|
||||
#define INT16_MAX _I16_MAX
|
||||
#define INT32_MIN ((int32_t)_I32_MIN)
|
||||
#define INT32_MAX _I32_MAX
|
||||
#define INT64_MIN ((int64_t)_I64_MIN)
|
||||
#define INT64_MAX _I64_MAX
|
||||
#define UINT8_MAX _UI8_MAX
|
||||
#define UINT16_MAX _UI16_MAX
|
||||
#define UINT32_MAX _UI32_MAX
|
||||
#define UINT64_MAX _UI64_MAX
|
||||
|
||||
// 7.18.2.2 Limits of minimum-width integer types
|
||||
#define INT_LEAST8_MIN INT8_MIN
|
||||
#define INT_LEAST8_MAX INT8_MAX
|
||||
#define INT_LEAST16_MIN INT16_MIN
|
||||
#define INT_LEAST16_MAX INT16_MAX
|
||||
#define INT_LEAST32_MIN INT32_MIN
|
||||
#define INT_LEAST32_MAX INT32_MAX
|
||||
#define INT_LEAST64_MIN INT64_MIN
|
||||
#define INT_LEAST64_MAX INT64_MAX
|
||||
#define UINT_LEAST8_MAX UINT8_MAX
|
||||
#define UINT_LEAST16_MAX UINT16_MAX
|
||||
#define UINT_LEAST32_MAX UINT32_MAX
|
||||
#define UINT_LEAST64_MAX UINT64_MAX
|
||||
|
||||
// 7.18.2.3 Limits of fastest minimum-width integer types
|
||||
#define INT_FAST8_MIN INT8_MIN
|
||||
#define INT_FAST8_MAX INT8_MAX
|
||||
#define INT_FAST16_MIN INT16_MIN
|
||||
#define INT_FAST16_MAX INT16_MAX
|
||||
#define INT_FAST32_MIN INT32_MIN
|
||||
#define INT_FAST32_MAX INT32_MAX
|
||||
#define INT_FAST64_MIN INT64_MIN
|
||||
#define INT_FAST64_MAX INT64_MAX
|
||||
#define UINT_FAST8_MAX UINT8_MAX
|
||||
#define UINT_FAST16_MAX UINT16_MAX
|
||||
#define UINT_FAST32_MAX UINT32_MAX
|
||||
#define UINT_FAST64_MAX UINT64_MAX
|
||||
|
||||
// 7.18.2.4 Limits of integer types capable of holding object pointers
|
||||
#ifdef _WIN64 // [
|
||||
# define INTPTR_MIN INT64_MIN
|
||||
# define INTPTR_MAX INT64_MAX
|
||||
# define UINTPTR_MAX UINT64_MAX
|
||||
#else // _WIN64 ][
|
||||
# define INTPTR_MIN INT32_MIN
|
||||
# define INTPTR_MAX INT32_MAX
|
||||
# define UINTPTR_MAX UINT32_MAX
|
||||
#endif // _WIN64 ]
|
||||
|
||||
// 7.18.2.5 Limits of greatest-width integer types
|
||||
#define INTMAX_MIN INT64_MIN
|
||||
#define INTMAX_MAX INT64_MAX
|
||||
#define UINTMAX_MAX UINT64_MAX
|
||||
|
||||
// 7.18.3 Limits of other integer types
|
||||
|
||||
#ifdef _WIN64 // [
|
||||
# define PTRDIFF_MIN _I64_MIN
|
||||
# define PTRDIFF_MAX _I64_MAX
|
||||
#else // _WIN64 ][
|
||||
# define PTRDIFF_MIN _I32_MIN
|
||||
# define PTRDIFF_MAX _I32_MAX
|
||||
#endif // _WIN64 ]
|
||||
|
||||
#define SIG_ATOMIC_MIN INT_MIN
|
||||
#define SIG_ATOMIC_MAX INT_MAX
|
||||
|
||||
#ifndef SIZE_MAX // [
|
||||
# ifdef _WIN64 // [
|
||||
# define SIZE_MAX _UI64_MAX
|
||||
# else // _WIN64 ][
|
||||
# define SIZE_MAX _UI32_MAX
|
||||
# endif // _WIN64 ]
|
||||
#endif // SIZE_MAX ]
|
||||
|
||||
// WCHAR_MIN and WCHAR_MAX are also defined in <wchar.h>
|
||||
#ifndef WCHAR_MIN // [
|
||||
# define WCHAR_MIN 0
|
||||
#endif // WCHAR_MIN ]
|
||||
#ifndef WCHAR_MAX // [
|
||||
# define WCHAR_MAX _UI16_MAX
|
||||
#endif // WCHAR_MAX ]
|
||||
|
||||
#define WINT_MIN 0
|
||||
#define WINT_MAX _UI16_MAX
|
||||
|
||||
#endif // __STDC_LIMIT_MACROS ]
|
||||
|
||||
|
||||
// 7.18.4 Limits of other integer types
|
||||
|
||||
#if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260
|
||||
|
||||
// 7.18.4.1 Macros for minimum-width integer constants
|
||||
|
||||
#define INT8_C(val) val##i8
|
||||
#define INT16_C(val) val##i16
|
||||
#define INT32_C(val) val##i32
|
||||
#define INT64_C(val) val##i64
|
||||
|
||||
#define UINT8_C(val) val##ui8
|
||||
#define UINT16_C(val) val##ui16
|
||||
#define UINT32_C(val) val##ui32
|
||||
#define UINT64_C(val) val##ui64
|
||||
|
||||
// 7.18.4.2 Macros for greatest-width integer constants
|
||||
#define INTMAX_C INT64_C
|
||||
#define UINTMAX_C UINT64_C
|
||||
|
||||
#endif // __STDC_CONSTANT_MACROS ]
|
||||
|
||||
|
||||
#endif // _MSC_STDINT_H_ ]
|
File diff suppressed because it is too large
Load diff
|
@ -1,40 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
/*
|
||||
* Created by Christian Brunschen on 13/05/2008.
|
||||
* Copyright 2008 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/BarcodeFormat.h>
|
||||
|
||||
const char* zxing::BarcodeFormat::barcodeFormatNames[] = {
|
||||
0,
|
||||
"AZTEC",
|
||||
"CODABAR",
|
||||
"CODE_39",
|
||||
"CODE_93",
|
||||
"CODE_128",
|
||||
"DATA_MATRIX",
|
||||
"EAN_8",
|
||||
"EAN_13",
|
||||
"ITF",
|
||||
"MAXICODE",
|
||||
"PDF_417",
|
||||
"QR_CODE",
|
||||
"RSS_14",
|
||||
"RSS_EXPANDED",
|
||||
"UPC_A",
|
||||
"UPC_E",
|
||||
"UPC_EAN_EXTENSION"
|
||||
};
|
|
@ -1,60 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
#ifndef __BARCODE_FORMAT_H__
|
||||
#define __BARCODE_FORMAT_H__
|
||||
|
||||
/*
|
||||
* BarcodeFormat.h
|
||||
* zxing
|
||||
*
|
||||
* Copyright 2010 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
namespace zxing {
|
||||
|
||||
class BarcodeFormat {
|
||||
public:
|
||||
// if you update the enum, update BarcodeFormat.cpp
|
||||
|
||||
enum Value {
|
||||
NONE,
|
||||
AZTEC,
|
||||
CODABAR,
|
||||
CODE_39,
|
||||
CODE_93,
|
||||
CODE_128,
|
||||
DATA_MATRIX,
|
||||
EAN_8,
|
||||
EAN_13,
|
||||
ITF,
|
||||
MAXICODE,
|
||||
PDF_417,
|
||||
QR_CODE,
|
||||
RSS_14,
|
||||
RSS_EXPANDED,
|
||||
UPC_A,
|
||||
UPC_E,
|
||||
UPC_EAN_EXTENSION
|
||||
};
|
||||
|
||||
BarcodeFormat(Value v) : value(v) {}
|
||||
const Value value;
|
||||
operator Value () const {return value;}
|
||||
|
||||
static char const* barcodeFormatNames[];
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif // __BARCODE_FORMAT_H__
|
|
@ -1,45 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
/*
|
||||
* Binarizer.cpp
|
||||
* zxing
|
||||
*
|
||||
* Created by Ralf Kistner on 16/10/2009.
|
||||
* Copyright 2008 ZXing authors All rights reserved.
|
||||
* Modified by Lukasz Warchol on 02/02/2010.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/Binarizer.h>
|
||||
|
||||
namespace zxing {
|
||||
|
||||
Binarizer::Binarizer(Ref<LuminanceSource> source) : source_(source) {
|
||||
}
|
||||
|
||||
Binarizer::~Binarizer() {
|
||||
}
|
||||
|
||||
Ref<LuminanceSource> Binarizer::getLuminanceSource() const {
|
||||
return source_;
|
||||
}
|
||||
|
||||
int Binarizer::getWidth() const {
|
||||
return source_->getWidth();
|
||||
}
|
||||
|
||||
int Binarizer::getHeight() const {
|
||||
return source_->getHeight();
|
||||
}
|
||||
|
||||
}
|
|
@ -1,50 +0,0 @@
|
|||
#ifndef BINARIZER_H_
|
||||
#define BINARIZER_H_
|
||||
|
||||
/*
|
||||
* Binarizer.h
|
||||
* zxing
|
||||
*
|
||||
* Copyright 2010 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/LuminanceSource.h>
|
||||
#include <zxing/common/BitArray.h>
|
||||
#include <zxing/common/BitMatrix.h>
|
||||
#include <zxing/common/Counted.h>
|
||||
|
||||
namespace zxing {
|
||||
|
||||
class Binarizer : public Counted {
|
||||
private:
|
||||
Ref<LuminanceSource> source_;
|
||||
|
||||
public:
|
||||
Binarizer(Ref<LuminanceSource> source);
|
||||
virtual ~Binarizer();
|
||||
|
||||
virtual Ref<BitArray> getBlackRow(int y, Ref<BitArray> row) = 0;
|
||||
virtual Ref<BitMatrix> getBlackMatrix() = 0;
|
||||
|
||||
Ref<LuminanceSource> getLuminanceSource() const ;
|
||||
virtual Ref<Binarizer> createBinarizer(Ref<LuminanceSource> source) = 0;
|
||||
|
||||
int getWidth() const;
|
||||
int getHeight() const;
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
#endif /* BINARIZER_H_ */
|
|
@ -1,70 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
/*
|
||||
* Copyright 2010 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/BinaryBitmap.h>
|
||||
|
||||
using zxing::Ref;
|
||||
using zxing::BitArray;
|
||||
using zxing::BitMatrix;
|
||||
using zxing::LuminanceSource;
|
||||
using zxing::BinaryBitmap;
|
||||
|
||||
// VC++
|
||||
using zxing::Binarizer;
|
||||
|
||||
BinaryBitmap::BinaryBitmap(Ref<Binarizer> binarizer) : binarizer_(binarizer) {
|
||||
}
|
||||
|
||||
BinaryBitmap::~BinaryBitmap() {
|
||||
}
|
||||
|
||||
Ref<BitArray> BinaryBitmap::getBlackRow(int y, Ref<BitArray> row) {
|
||||
return binarizer_->getBlackRow(y, row);
|
||||
}
|
||||
|
||||
Ref<BitMatrix> BinaryBitmap::getBlackMatrix() {
|
||||
return binarizer_->getBlackMatrix();
|
||||
}
|
||||
|
||||
int BinaryBitmap::getWidth() const {
|
||||
return getLuminanceSource()->getWidth();
|
||||
}
|
||||
|
||||
int BinaryBitmap::getHeight() const {
|
||||
return getLuminanceSource()->getHeight();
|
||||
}
|
||||
|
||||
Ref<LuminanceSource> BinaryBitmap::getLuminanceSource() const {
|
||||
return binarizer_->getLuminanceSource();
|
||||
}
|
||||
|
||||
|
||||
bool BinaryBitmap::isCropSupported() const {
|
||||
return getLuminanceSource()->isCropSupported();
|
||||
}
|
||||
|
||||
Ref<BinaryBitmap> BinaryBitmap::crop(int left, int top, int width, int height) {
|
||||
return Ref<BinaryBitmap> (new BinaryBitmap(binarizer_->createBinarizer(getLuminanceSource()->crop(left, top, width, height))));
|
||||
}
|
||||
|
||||
bool BinaryBitmap::isRotateSupported() const {
|
||||
return getLuminanceSource()->isRotateSupported();
|
||||
}
|
||||
|
||||
Ref<BinaryBitmap> BinaryBitmap::rotateCounterClockwise() {
|
||||
return Ref<BinaryBitmap> (new BinaryBitmap(binarizer_->createBinarizer(getLuminanceSource()->rotateCounterClockwise())));
|
||||
}
|
|
@ -1,56 +0,0 @@
|
|||
#ifndef __BINARYBITMAP_H__
|
||||
#define __BINARYBITMAP_H__
|
||||
|
||||
/*
|
||||
* BinaryBitmap.h
|
||||
* zxing
|
||||
*
|
||||
* Copyright 2010 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/common/Counted.h>
|
||||
#include <zxing/common/BitMatrix.h>
|
||||
#include <zxing/common/BitArray.h>
|
||||
#include <zxing/Binarizer.h>
|
||||
|
||||
namespace zxing {
|
||||
|
||||
class BinaryBitmap : public Counted {
|
||||
private:
|
||||
Ref<Binarizer> binarizer_;
|
||||
|
||||
public:
|
||||
BinaryBitmap(Ref<Binarizer> binarizer);
|
||||
virtual ~BinaryBitmap();
|
||||
|
||||
Ref<BitArray> getBlackRow(int y, Ref<BitArray> row);
|
||||
Ref<BitMatrix> getBlackMatrix();
|
||||
|
||||
Ref<LuminanceSource> getLuminanceSource() const;
|
||||
|
||||
int getWidth() const;
|
||||
int getHeight() const;
|
||||
|
||||
bool isRotateSupported() const;
|
||||
Ref<BinaryBitmap> rotateCounterClockwise();
|
||||
|
||||
bool isCropSupported() const;
|
||||
Ref<BinaryBitmap> crop(int left, int top, int width, int height);
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif /* BINARYBITMAP_H_ */
|
|
@ -1,28 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
/*
|
||||
* ChecksumException.cpp
|
||||
* zxing
|
||||
*
|
||||
* Created by Christian Brunschen on 13/05/2008.
|
||||
* Copyright 2008 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/ChecksumException.h>
|
||||
|
||||
using zxing::ChecksumException;
|
||||
|
||||
ChecksumException::ChecksumException() throw() {}
|
||||
ChecksumException::ChecksumException(const char *msg) throw() : ReaderException(msg) {}
|
||||
ChecksumException::~ChecksumException() throw() {}
|
|
@ -1,34 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
|
||||
#ifndef __CHECKSUM_EXCEPTION_H__
|
||||
#define __NOT_FOUND_EXCEPTION_H__
|
||||
|
||||
/*
|
||||
* Copyright 20011 ZXing authors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/ReaderException.h>
|
||||
|
||||
namespace zxing {
|
||||
class ChecksumException : public ReaderException {
|
||||
typedef ReaderException Base;
|
||||
public:
|
||||
ChecksumException() throw();
|
||||
ChecksumException(const char *msg) throw();
|
||||
~ChecksumException() throw();
|
||||
};
|
||||
}
|
||||
|
||||
#endif // __CHECKSUM_EXCEPTION_H__
|
|
@ -1,142 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
/*
|
||||
* DecodeHintType.cpp
|
||||
* zxing
|
||||
*
|
||||
* Copyright 2010 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/DecodeHints.h>
|
||||
#include <zxing/common/IllegalArgumentException.h>
|
||||
|
||||
using zxing::Ref;
|
||||
using zxing::ResultPointCallback;
|
||||
using zxing::DecodeHintType;
|
||||
using zxing::DecodeHints;
|
||||
|
||||
// VC++
|
||||
using zxing::BarcodeFormat;
|
||||
|
||||
const DecodeHintType DecodeHints::CHARACTER_SET;
|
||||
|
||||
const DecodeHints DecodeHints::PRODUCT_HINT(
|
||||
UPC_A_HINT |
|
||||
UPC_E_HINT |
|
||||
EAN_13_HINT |
|
||||
EAN_8_HINT |
|
||||
RSS_14_HINT
|
||||
);
|
||||
|
||||
const DecodeHints DecodeHints::ONED_HINT(
|
||||
CODE_39_HINT |
|
||||
CODE_93_HINT |
|
||||
CODE_128_HINT |
|
||||
ITF_HINT |
|
||||
CODABAR_HINT |
|
||||
DecodeHints::PRODUCT_HINT
|
||||
);
|
||||
|
||||
const DecodeHints DecodeHints::DEFAULT_HINT(
|
||||
ONED_HINT |
|
||||
QR_CODE_HINT |
|
||||
DATA_MATRIX_HINT |
|
||||
AZTEC_HINT |
|
||||
PDF_417_HINT
|
||||
);
|
||||
|
||||
DecodeHints::DecodeHints() {
|
||||
hints = 0;
|
||||
}
|
||||
|
||||
DecodeHints::DecodeHints(DecodeHintType init) {
|
||||
hints = init;
|
||||
}
|
||||
|
||||
void DecodeHints::addFormat(BarcodeFormat toadd) {
|
||||
switch (toadd) {
|
||||
case BarcodeFormat::AZTEC: hints |= AZTEC_HINT; break;
|
||||
case BarcodeFormat::CODABAR: hints |= CODABAR_HINT; break;
|
||||
case BarcodeFormat::CODE_39: hints |= CODE_39_HINT; break;
|
||||
case BarcodeFormat::CODE_93: hints |= CODE_93_HINT; break;
|
||||
case BarcodeFormat::CODE_128: hints |= CODE_128_HINT; break;
|
||||
case BarcodeFormat::DATA_MATRIX: hints |= DATA_MATRIX_HINT; break;
|
||||
case BarcodeFormat::EAN_8: hints |= EAN_8_HINT; break;
|
||||
case BarcodeFormat::EAN_13: hints |= EAN_13_HINT; break;
|
||||
case BarcodeFormat::ITF: hints |= ITF_HINT; break;
|
||||
case BarcodeFormat::MAXICODE: hints |= MAXICODE_HINT; break;
|
||||
case BarcodeFormat::PDF_417: hints |= PDF_417_HINT; break;
|
||||
case BarcodeFormat::QR_CODE: hints |= QR_CODE_HINT; break;
|
||||
case BarcodeFormat::RSS_14: hints |= RSS_14_HINT; break;
|
||||
case BarcodeFormat::RSS_EXPANDED: hints |= RSS_EXPANDED_HINT; break;
|
||||
case BarcodeFormat::UPC_A: hints |= UPC_A_HINT; break;
|
||||
case BarcodeFormat::UPC_E: hints |= UPC_E_HINT; break;
|
||||
case BarcodeFormat::UPC_EAN_EXTENSION: hints |= UPC_EAN_EXTENSION_HINT; break;
|
||||
default: throw IllegalArgumentException("Unrecognizd barcode format");
|
||||
}
|
||||
}
|
||||
|
||||
bool DecodeHints::containsFormat(BarcodeFormat tocheck) const {
|
||||
DecodeHintType checkAgainst = 0;
|
||||
switch (tocheck) {
|
||||
case BarcodeFormat::AZTEC: checkAgainst |= AZTEC_HINT; break;
|
||||
case BarcodeFormat::CODABAR: checkAgainst |= CODABAR_HINT; break;
|
||||
case BarcodeFormat::CODE_39: checkAgainst |= CODE_39_HINT; break;
|
||||
case BarcodeFormat::CODE_93: checkAgainst |= CODE_93_HINT; break;
|
||||
case BarcodeFormat::CODE_128: checkAgainst |= CODE_128_HINT; break;
|
||||
case BarcodeFormat::DATA_MATRIX: checkAgainst |= DATA_MATRIX_HINT; break;
|
||||
case BarcodeFormat::EAN_8: checkAgainst |= EAN_8_HINT; break;
|
||||
case BarcodeFormat::EAN_13: checkAgainst |= EAN_13_HINT; break;
|
||||
case BarcodeFormat::ITF: checkAgainst |= ITF_HINT; break;
|
||||
case BarcodeFormat::MAXICODE: checkAgainst |= MAXICODE_HINT; break;
|
||||
case BarcodeFormat::PDF_417: checkAgainst |= PDF_417_HINT; break;
|
||||
case BarcodeFormat::QR_CODE: checkAgainst |= QR_CODE_HINT; break;
|
||||
case BarcodeFormat::RSS_14: checkAgainst |= RSS_14_HINT; break;
|
||||
case BarcodeFormat::RSS_EXPANDED: checkAgainst |= RSS_EXPANDED_HINT; break;
|
||||
case BarcodeFormat::UPC_A: checkAgainst |= UPC_A_HINT; break;
|
||||
case BarcodeFormat::UPC_E: checkAgainst |= UPC_E_HINT; break;
|
||||
case BarcodeFormat::UPC_EAN_EXTENSION: checkAgainst |= UPC_EAN_EXTENSION_HINT; break;
|
||||
default: throw IllegalArgumentException("Unrecognizd barcode format");
|
||||
}
|
||||
return (hints & checkAgainst) != 0;
|
||||
}
|
||||
|
||||
void DecodeHints::setTryHarder(bool toset) {
|
||||
if (toset) {
|
||||
hints |= TRYHARDER_HINT;
|
||||
} else {
|
||||
hints &= ~TRYHARDER_HINT;
|
||||
}
|
||||
}
|
||||
|
||||
bool DecodeHints::getTryHarder() const {
|
||||
return (hints & TRYHARDER_HINT) != 0;
|
||||
}
|
||||
|
||||
void DecodeHints::setResultPointCallback(Ref<ResultPointCallback> const& _callback) {
|
||||
callback = _callback;
|
||||
}
|
||||
|
||||
Ref<ResultPointCallback> DecodeHints::getResultPointCallback() const {
|
||||
return callback;
|
||||
}
|
||||
|
||||
DecodeHints zxing::operator | (DecodeHints const& l, DecodeHints const& r) {
|
||||
DecodeHints result (l);
|
||||
result.hints |= r.hints;
|
||||
if (!result.callback) {
|
||||
result.callback = r.callback;
|
||||
}
|
||||
return result;
|
||||
}
|
|
@ -1,85 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
#ifndef __DECODEHINTS_H_
|
||||
#define __DECODEHINTS_H_
|
||||
/*
|
||||
* DecodeHintType.h
|
||||
* zxing
|
||||
*
|
||||
* Copyright 2010 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/BarcodeFormat.h>
|
||||
#include <zxing/ResultPointCallback.h>
|
||||
|
||||
namespace zxing {
|
||||
|
||||
typedef unsigned int DecodeHintType;
|
||||
class DecodeHints;
|
||||
DecodeHints operator | (DecodeHints const&, DecodeHints const&);
|
||||
|
||||
class DecodeHints {
|
||||
private:
|
||||
DecodeHintType hints;
|
||||
Ref<ResultPointCallback> callback;
|
||||
|
||||
public:
|
||||
static const DecodeHintType AZTEC_HINT = 1 << BarcodeFormat::AZTEC;
|
||||
static const DecodeHintType CODABAR_HINT = 1 << BarcodeFormat::CODABAR;
|
||||
static const DecodeHintType CODE_39_HINT = 1 << BarcodeFormat::CODE_39;
|
||||
static const DecodeHintType CODE_93_HINT = 1 << BarcodeFormat::CODE_93;
|
||||
static const DecodeHintType CODE_128_HINT = 1 << BarcodeFormat::CODE_128;
|
||||
static const DecodeHintType DATA_MATRIX_HINT = 1 << BarcodeFormat::DATA_MATRIX;
|
||||
static const DecodeHintType EAN_8_HINT = 1 << BarcodeFormat::EAN_8;
|
||||
static const DecodeHintType EAN_13_HINT = 1 << BarcodeFormat::EAN_13;
|
||||
static const DecodeHintType ITF_HINT = 1 << BarcodeFormat::ITF;
|
||||
static const DecodeHintType MAXICODE_HINT = 1 << BarcodeFormat::MAXICODE;
|
||||
static const DecodeHintType PDF_417_HINT = 1 << BarcodeFormat::PDF_417;
|
||||
static const DecodeHintType QR_CODE_HINT = 1 << BarcodeFormat::QR_CODE;
|
||||
static const DecodeHintType RSS_14_HINT = 1 << BarcodeFormat::RSS_14;
|
||||
static const DecodeHintType RSS_EXPANDED_HINT = 1 << BarcodeFormat::RSS_EXPANDED;
|
||||
static const DecodeHintType UPC_A_HINT = 1 << BarcodeFormat::UPC_A;
|
||||
static const DecodeHintType UPC_E_HINT = 1 << BarcodeFormat::UPC_E;
|
||||
static const DecodeHintType UPC_EAN_EXTENSION_HINT = 1 << BarcodeFormat::UPC_EAN_EXTENSION;
|
||||
|
||||
static const DecodeHintType TRYHARDER_HINT = 1 << 31;
|
||||
static const DecodeHintType CHARACTER_SET = 1 << 30;
|
||||
// static const DecodeHintType ALLOWED_LENGTHS = 1 << 29;
|
||||
// static const DecodeHintType ASSUME_CODE_39_CHECK_DIGIT = 1 << 28;
|
||||
static const DecodeHintType ASSUME_GS1 = 1 << 27;
|
||||
// static const DecodeHintType NEED_RESULT_POINT_CALLBACK = 1 << 26;
|
||||
|
||||
static const DecodeHints PRODUCT_HINT;
|
||||
static const DecodeHints ONED_HINT;
|
||||
static const DecodeHints DEFAULT_HINT;
|
||||
|
||||
DecodeHints();
|
||||
DecodeHints(DecodeHintType init);
|
||||
|
||||
void addFormat(BarcodeFormat toadd);
|
||||
bool containsFormat(BarcodeFormat tocheck) const;
|
||||
bool isEmpty() const {return (hints==0);}
|
||||
void clear() {hints=0;}
|
||||
void setTryHarder(bool toset);
|
||||
bool getTryHarder() const;
|
||||
|
||||
void setResultPointCallback(Ref<ResultPointCallback> const&);
|
||||
Ref<ResultPointCallback> getResultPointCallback() const;
|
||||
|
||||
friend DecodeHints operator | (DecodeHints const&, DecodeHints const&);
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif
|
|
@ -1,43 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
/*
|
||||
* Exception.cpp
|
||||
* ZXing
|
||||
*
|
||||
* Created by Christian Brunschen on 03/06/2008.
|
||||
* Copyright 2008-2011 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
|
||||
*/
|
||||
|
||||
#include <zxing/ZXing.h>
|
||||
#include <zxing/Exception.h>
|
||||
#include <string.h>
|
||||
|
||||
using zxing::Exception;
|
||||
|
||||
void Exception::deleteMessage() {
|
||||
delete [] message;
|
||||
}
|
||||
|
||||
char const* Exception::copy(char const* msg) {
|
||||
char* message = 0;
|
||||
if (msg) {
|
||||
int l = strlen(msg)+1;
|
||||
if (l) {
|
||||
message = new char[l];
|
||||
strcpy(message, msg);
|
||||
}
|
||||
}
|
||||
return message;
|
||||
}
|
|
@ -1,51 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
#ifndef __EXCEPTION_H__
|
||||
#define __EXCEPTION_H__
|
||||
|
||||
/*
|
||||
* Exception.h
|
||||
* ZXing
|
||||
*
|
||||
* Copyright 2010 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <string>
|
||||
#include <exception>
|
||||
|
||||
namespace zxing {
|
||||
|
||||
class Exception : public std::exception {
|
||||
private:
|
||||
char const* const message;
|
||||
|
||||
public:
|
||||
Exception() throw() : message(0) {}
|
||||
Exception(const char* msg) throw() : message(copy(msg)) {}
|
||||
Exception(Exception const& that) throw() : std::exception(that), message(copy(that.message)) {}
|
||||
~Exception() throw() {
|
||||
if(message) {
|
||||
deleteMessage();
|
||||
}
|
||||
}
|
||||
char const* what() const throw() {return message ? message : "";}
|
||||
|
||||
private:
|
||||
static char const* copy(char const*);
|
||||
void deleteMessage();
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif // __EXCEPTION_H__
|
|
@ -1,41 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
/*
|
||||
* FormatException.cpp
|
||||
* zxing
|
||||
*
|
||||
* Created by Christian Brunschen on 13/05/2008.
|
||||
* Copyright 2008 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/FormatException.h>
|
||||
|
||||
namespace zxing {
|
||||
|
||||
FormatException::FormatException() {}
|
||||
|
||||
FormatException::FormatException(const char *msg) :
|
||||
ReaderException(msg) {
|
||||
}
|
||||
|
||||
FormatException::~FormatException() throw() {
|
||||
}
|
||||
|
||||
FormatException const&
|
||||
FormatException::getFormatInstance() {
|
||||
static FormatException instance;
|
||||
return instance;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,37 +0,0 @@
|
|||
#ifndef __FORMAT_EXCEPTION_H__
|
||||
#define __FORMAT_EXCEPTION_H__
|
||||
|
||||
/*
|
||||
* FormatException.h
|
||||
* zxing
|
||||
*
|
||||
* Copyright 2010 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/ReaderException.h>
|
||||
|
||||
namespace zxing {
|
||||
|
||||
class FormatException : public ReaderException {
|
||||
public:
|
||||
FormatException();
|
||||
FormatException(const char *msg);
|
||||
~FormatException() throw();
|
||||
|
||||
static FormatException const& getFormatInstance();
|
||||
};
|
||||
|
||||
}
|
||||
#endif // __FORMAT_EXCEPTION_H__
|
|
@ -1,35 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
|
||||
#ifndef __ILLEGAL_STATE_EXCEPTION_H__
|
||||
#define __ILLEGAL_STATE_EXCEPTION_H__
|
||||
|
||||
/*
|
||||
* Copyright 20011 ZXing authors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may illegal use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/ReaderException.h>
|
||||
|
||||
namespace zxing {
|
||||
|
||||
class IllegalStateException : public ReaderException {
|
||||
public:
|
||||
IllegalStateException() throw() {}
|
||||
IllegalStateException(const char *msg) throw() : ReaderException(msg) {}
|
||||
~IllegalStateException() throw() {}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif // __ILLEGAL_STATE_EXCEPTION_H__
|
|
@ -1,68 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
/*
|
||||
* Copyright 2013 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/ZXing.h>
|
||||
#include <zxing/InvertedLuminanceSource.h>
|
||||
|
||||
using zxing::boolean;
|
||||
using zxing::Ref;
|
||||
using zxing::ArrayRef;
|
||||
using zxing::LuminanceSource;
|
||||
using zxing::InvertedLuminanceSource;
|
||||
|
||||
InvertedLuminanceSource::InvertedLuminanceSource(Ref<LuminanceSource> const& delegate_)
|
||||
: Super(delegate_->getWidth(), delegate_->getHeight()), delegate(delegate_) {}
|
||||
|
||||
ArrayRef<char> InvertedLuminanceSource::getRow(int y, ArrayRef<char> row) const {
|
||||
row = delegate->getRow(y, row);
|
||||
int width = getWidth();
|
||||
for (int i = 0; i < width; i++) {
|
||||
row[i] = (byte) (255 - (row[i] & 0xFF));
|
||||
}
|
||||
return row;
|
||||
}
|
||||
|
||||
ArrayRef<char> InvertedLuminanceSource::getMatrix() const {
|
||||
ArrayRef<char> matrix = delegate->getMatrix();
|
||||
int length = getWidth() * getHeight();
|
||||
ArrayRef<char> invertedMatrix(length);
|
||||
for (int i = 0; i < length; i++) {
|
||||
invertedMatrix[i] = (byte) (255 - (matrix[i] & 0xFF));
|
||||
}
|
||||
return invertedMatrix;
|
||||
}
|
||||
|
||||
zxing::boolean InvertedLuminanceSource::isCropSupported() const {
|
||||
return delegate->isCropSupported();
|
||||
}
|
||||
|
||||
Ref<LuminanceSource> InvertedLuminanceSource::crop(int left, int top, int width, int height) const {
|
||||
return Ref<LuminanceSource>(new InvertedLuminanceSource(delegate->crop(left, top, width, height)));
|
||||
}
|
||||
|
||||
boolean InvertedLuminanceSource::isRotateSupported() const {
|
||||
return delegate->isRotateSupported();
|
||||
}
|
||||
|
||||
Ref<LuminanceSource> InvertedLuminanceSource::invert() const {
|
||||
return delegate;
|
||||
}
|
||||
|
||||
Ref<LuminanceSource> InvertedLuminanceSource::rotateCounterClockwise() const {
|
||||
return Ref<LuminanceSource>(new InvertedLuminanceSource(delegate->rotateCounterClockwise()));
|
||||
}
|
||||
|
|
@ -1,48 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
#ifndef __INVERTEDLUMINANCESOURCE_H__
|
||||
#define __INVERTEDLUMINANCESOURCE_H__
|
||||
/*
|
||||
* Copyright 2013 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/ZXing.h>
|
||||
#include <zxing/LuminanceSource.h>
|
||||
|
||||
namespace zxing {
|
||||
|
||||
class InvertedLuminanceSource : public LuminanceSource {
|
||||
private:
|
||||
typedef LuminanceSource Super;
|
||||
const Ref<LuminanceSource> delegate;
|
||||
|
||||
public:
|
||||
InvertedLuminanceSource(Ref<LuminanceSource> const&);
|
||||
|
||||
ArrayRef<char> getRow(int y, ArrayRef<char> row) const;
|
||||
ArrayRef<char> getMatrix() const;
|
||||
|
||||
boolean isCropSupported() const;
|
||||
Ref<LuminanceSource> crop(int left, int top, int width, int height) const;
|
||||
|
||||
boolean isRotateSupported() const;
|
||||
|
||||
virtual Ref<LuminanceSource> invert() const;
|
||||
|
||||
Ref<LuminanceSource> rotateCounterClockwise() const;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif /* INVERTEDLUMINANCESOURCE_H_ */
|
|
@ -1,86 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
/*
|
||||
* LuminanceSource.cpp
|
||||
* zxing
|
||||
*
|
||||
* Copyright 2008 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <sstream>
|
||||
#include <zxing/LuminanceSource.h>
|
||||
#include <zxing/InvertedLuminanceSource.h>
|
||||
#include <zxing/common/IllegalArgumentException.h>
|
||||
|
||||
using zxing::Ref;
|
||||
using zxing::LuminanceSource;
|
||||
|
||||
LuminanceSource::LuminanceSource(int width_, int height_) :width(width_), height(height_) {}
|
||||
|
||||
LuminanceSource::~LuminanceSource() {}
|
||||
|
||||
bool LuminanceSource::isCropSupported() const {
|
||||
return false;
|
||||
}
|
||||
|
||||
Ref<LuminanceSource> LuminanceSource::crop(int, int, int, int) const {
|
||||
throw IllegalArgumentException("This luminance source does not support cropping.");
|
||||
}
|
||||
|
||||
bool LuminanceSource::isRotateSupported() const {
|
||||
return false;
|
||||
}
|
||||
|
||||
Ref<LuminanceSource> LuminanceSource::rotateCounterClockwise() const {
|
||||
throw IllegalArgumentException("This luminance source does not support rotation.");
|
||||
}
|
||||
|
||||
LuminanceSource::operator std::string() const {
|
||||
ArrayRef<char> row;
|
||||
std::ostringstream oss;
|
||||
for (int y = 0; y < getHeight(); y++) {
|
||||
row = getRow(y, row);
|
||||
for (int x = 0; x < getWidth(); x++) {
|
||||
int luminance = row[x] & 0xFF;
|
||||
char c;
|
||||
if (luminance < 0x40) {
|
||||
c = '#';
|
||||
} else if (luminance < 0x80) {
|
||||
c = '+';
|
||||
} else if (luminance < 0xC0) {
|
||||
c = '.';
|
||||
} else {
|
||||
c = ' ';
|
||||
}
|
||||
oss << c;
|
||||
}
|
||||
oss << '\n';
|
||||
}
|
||||
return oss.str();
|
||||
}
|
||||
|
||||
Ref<LuminanceSource> LuminanceSource::invert() const {
|
||||
|
||||
// N.B.: this only works because we use counted objects with the
|
||||
// count in the object. This is _not_ how things like shared_ptr
|
||||
// work. They do not allow you to make a smart pointer from a native
|
||||
// pointer more than once. If we ever switch to (something like)
|
||||
// shared_ptr's, the luminace source is going to have keep a weak
|
||||
// pointer to itself from which it can create a strong pointer as
|
||||
// needed. And, FWIW, that has nasty semantics in the face of
|
||||
// exceptions during construction.
|
||||
|
||||
return Ref<LuminanceSource>
|
||||
(new InvertedLuminanceSource(Ref<LuminanceSource>(const_cast<LuminanceSource*>(this))));
|
||||
}
|
|
@ -1,59 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
#ifndef __LUMINANCESOURCE_H__
|
||||
#define __LUMINANCESOURCE_H__
|
||||
/*
|
||||
* LuminanceSource.h
|
||||
* zxing
|
||||
*
|
||||
* Copyright 2010 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/common/Counted.h>
|
||||
#include <zxing/common/Array.h>
|
||||
#include <string.h>
|
||||
|
||||
namespace zxing {
|
||||
|
||||
class LuminanceSource : public Counted {
|
||||
private:
|
||||
const int width;
|
||||
const int height;
|
||||
|
||||
public:
|
||||
LuminanceSource(int width, int height);
|
||||
virtual ~LuminanceSource();
|
||||
|
||||
int getWidth() const { return width; }
|
||||
int getHeight() const { return height; }
|
||||
|
||||
// Callers take ownership of the returned memory and must call delete [] on it themselves.
|
||||
virtual ArrayRef<char> getRow(int y, ArrayRef<char> row) const = 0;
|
||||
virtual ArrayRef<char> getMatrix() const = 0;
|
||||
|
||||
virtual bool isCropSupported() const;
|
||||
virtual Ref<LuminanceSource> crop(int left, int top, int width, int height) const;
|
||||
|
||||
virtual bool isRotateSupported() const;
|
||||
|
||||
virtual Ref<LuminanceSource> invert() const;
|
||||
|
||||
virtual Ref<LuminanceSource> rotateCounterClockwise() const;
|
||||
|
||||
operator std::string () const;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif /* LUMINANCESOURCE_H_ */
|
|
@ -1,124 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
/*
|
||||
* Copyright 2010 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/ZXing.h>
|
||||
#include <zxing/MultiFormatReader.h>
|
||||
#include <zxing/qrcode/QRCodeReader.h>
|
||||
#include <zxing/datamatrix/DataMatrixReader.h>
|
||||
#include <zxing/aztec/AztecReader.h>
|
||||
#include <zxing/pdf417/PDF417Reader.h>
|
||||
#include <zxing/oned/MultiFormatUPCEANReader.h>
|
||||
#include <zxing/oned/MultiFormatOneDReader.h>
|
||||
#include <zxing/ReaderException.h>
|
||||
|
||||
using zxing::Ref;
|
||||
using zxing::Result;
|
||||
using zxing::MultiFormatReader;
|
||||
|
||||
// VC++
|
||||
using zxing::DecodeHints;
|
||||
using zxing::BinaryBitmap;
|
||||
|
||||
MultiFormatReader::MultiFormatReader() {}
|
||||
|
||||
Ref<Result> MultiFormatReader::decode(Ref<BinaryBitmap> image) {
|
||||
setHints(DecodeHints::DEFAULT_HINT);
|
||||
return decodeInternal(image);
|
||||
}
|
||||
|
||||
Ref<Result> MultiFormatReader::decode(Ref<BinaryBitmap> image, DecodeHints hints) {
|
||||
setHints(hints);
|
||||
return decodeInternal(image);
|
||||
}
|
||||
|
||||
Ref<Result> MultiFormatReader::decodeWithState(Ref<BinaryBitmap> image) {
|
||||
// Make sure to set up the default state so we don't crash
|
||||
if (readers_.size() == 0) {
|
||||
setHints(DecodeHints::DEFAULT_HINT);
|
||||
}
|
||||
return decodeInternal(image);
|
||||
}
|
||||
|
||||
void MultiFormatReader::setHints(DecodeHints hints) {
|
||||
hints_ = hints;
|
||||
readers_.clear();
|
||||
bool tryHarder = hints.getTryHarder();
|
||||
|
||||
bool addOneDReader = hints.containsFormat(BarcodeFormat::UPC_E) ||
|
||||
hints.containsFormat(BarcodeFormat::UPC_A) ||
|
||||
hints.containsFormat(BarcodeFormat::UPC_E) ||
|
||||
hints.containsFormat(BarcodeFormat::EAN_13) ||
|
||||
hints.containsFormat(BarcodeFormat::EAN_8) ||
|
||||
hints.containsFormat(BarcodeFormat::CODABAR) ||
|
||||
hints.containsFormat(BarcodeFormat::CODE_39) ||
|
||||
hints.containsFormat(BarcodeFormat::CODE_93) ||
|
||||
hints.containsFormat(BarcodeFormat::CODE_128) ||
|
||||
hints.containsFormat(BarcodeFormat::ITF) ||
|
||||
hints.containsFormat(BarcodeFormat::RSS_14) ||
|
||||
hints.containsFormat(BarcodeFormat::RSS_EXPANDED);
|
||||
if (addOneDReader && !tryHarder) {
|
||||
readers_.push_back(Ref<Reader>(new zxing::oned::MultiFormatOneDReader(hints)));
|
||||
}
|
||||
if (hints.containsFormat(BarcodeFormat::QR_CODE)) {
|
||||
readers_.push_back(Ref<Reader>(new zxing::qrcode::QRCodeReader()));
|
||||
}
|
||||
if (hints.containsFormat(BarcodeFormat::DATA_MATRIX)) {
|
||||
readers_.push_back(Ref<Reader>(new zxing::datamatrix::DataMatrixReader()));
|
||||
}
|
||||
if (hints.containsFormat(BarcodeFormat::AZTEC)) {
|
||||
readers_.push_back(Ref<Reader>(new zxing::aztec::AztecReader()));
|
||||
}
|
||||
if (hints.containsFormat(BarcodeFormat::PDF_417)) {
|
||||
readers_.push_back(Ref<Reader>(new zxing::pdf417::PDF417Reader()));
|
||||
}
|
||||
/*
|
||||
if (hints.contains(BarcodeFormat.MAXICODE)) {
|
||||
readers.add(new MaxiCodeReader());
|
||||
}
|
||||
*/
|
||||
if (addOneDReader && tryHarder) {
|
||||
readers_.push_back(Ref<Reader>(new zxing::oned::MultiFormatOneDReader(hints)));
|
||||
}
|
||||
if (readers_.size() == 0) {
|
||||
if (!tryHarder) {
|
||||
readers_.push_back(Ref<Reader>(new zxing::oned::MultiFormatOneDReader(hints)));
|
||||
}
|
||||
readers_.push_back(Ref<Reader>(new zxing::qrcode::QRCodeReader()));
|
||||
readers_.push_back(Ref<Reader>(new zxing::datamatrix::DataMatrixReader()));
|
||||
readers_.push_back(Ref<Reader>(new zxing::aztec::AztecReader()));
|
||||
readers_.push_back(Ref<Reader>(new zxing::pdf417::PDF417Reader()));
|
||||
// readers.add(new MaxiCodeReader());
|
||||
|
||||
if (tryHarder) {
|
||||
readers_.push_back(Ref<Reader>(new zxing::oned::MultiFormatOneDReader(hints)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ref<Result> MultiFormatReader::decodeInternal(Ref<BinaryBitmap> image) {
|
||||
for (unsigned int i = 0; i < readers_.size(); i++) {
|
||||
try {
|
||||
return readers_[i]->decode(image, hints_);
|
||||
} catch (ReaderException const& re) {
|
||||
(void)re;
|
||||
// continue
|
||||
}
|
||||
}
|
||||
throw ReaderException("No code detected");
|
||||
}
|
||||
|
||||
MultiFormatReader::~MultiFormatReader() {}
|
|
@ -1,48 +0,0 @@
|
|||
#ifndef __MULTI_FORMAT_READER_H__
|
||||
#define __MULTI_FORMAT_READER_H__
|
||||
|
||||
/*
|
||||
* MultiFormatBarcodeReader.h
|
||||
* ZXing
|
||||
*
|
||||
* Copyright 2010 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
|
||||
#include <zxing/Reader.h>
|
||||
#include <zxing/common/BitArray.h>
|
||||
#include <zxing/Result.h>
|
||||
#include <zxing/DecodeHints.h>
|
||||
|
||||
namespace zxing {
|
||||
class MultiFormatReader : public Reader {
|
||||
private:
|
||||
Ref<Result> decodeInternal(Ref<BinaryBitmap> image);
|
||||
|
||||
std::vector<Ref<Reader> > readers_;
|
||||
DecodeHints hints_;
|
||||
|
||||
public:
|
||||
MultiFormatReader();
|
||||
|
||||
Ref<Result> decode(Ref<BinaryBitmap> image);
|
||||
Ref<Result> decode(Ref<BinaryBitmap> image, DecodeHints hints);
|
||||
Ref<Result> decodeWithState(Ref<BinaryBitmap> image);
|
||||
void setHints(DecodeHints hints);
|
||||
~MultiFormatReader();
|
||||
};
|
||||
}
|
||||
|
||||
#endif
|
|
@ -1,35 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
|
||||
#ifndef __NOT_FOUND_EXCEPTION_H__
|
||||
#define __NOT_FOUND_EXCEPTION_H__
|
||||
|
||||
/*
|
||||
* Copyright 20011 ZXing authors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/ReaderException.h>
|
||||
|
||||
namespace zxing {
|
||||
|
||||
class NotFoundException : public ReaderException {
|
||||
public:
|
||||
NotFoundException() throw() {}
|
||||
NotFoundException(const char *msg) throw() : ReaderException(msg) {}
|
||||
~NotFoundException() throw() {}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif // __NOT_FOUND_EXCEPTION_H__
|
|
@ -1,31 +0,0 @@
|
|||
/*
|
||||
* Reader.cpp
|
||||
* zxing
|
||||
*
|
||||
* Created by Christian Brunschen on 13/05/2008.
|
||||
* Copyright 2008 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/Reader.h>
|
||||
|
||||
namespace zxing {
|
||||
|
||||
Reader::~Reader() { }
|
||||
|
||||
Ref<Result> Reader::decode(Ref<BinaryBitmap> image) {
|
||||
return decode(image, DecodeHints::DEFAULT_HINT);
|
||||
}
|
||||
|
||||
}
|
|
@ -1,40 +0,0 @@
|
|||
#ifndef __READER_H__
|
||||
#define __READER_H__
|
||||
|
||||
/*
|
||||
* Reader.h
|
||||
* zxing
|
||||
*
|
||||
* Copyright 2010 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/BinaryBitmap.h>
|
||||
#include <zxing/Result.h>
|
||||
#include <zxing/DecodeHints.h>
|
||||
|
||||
namespace zxing {
|
||||
|
||||
class Reader : public Counted {
|
||||
protected:
|
||||
Reader() {}
|
||||
public:
|
||||
virtual Ref<Result> decode(Ref<BinaryBitmap> image);
|
||||
virtual Ref<Result> decode(Ref<BinaryBitmap> image, DecodeHints hints) = 0;
|
||||
virtual ~Reader();
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif // __READER_H__
|
|
@ -1,37 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
#ifndef __READER_EXCEPTION_H__
|
||||
#define __READER_EXCEPTION_H__
|
||||
|
||||
/*
|
||||
* ReaderException.h
|
||||
* zxing
|
||||
*
|
||||
* Copyright 2010 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/Exception.h>
|
||||
|
||||
namespace zxing {
|
||||
|
||||
class ReaderException : public Exception {
|
||||
public:
|
||||
ReaderException() throw() {}
|
||||
ReaderException(char const* msg) throw() : Exception(msg) {}
|
||||
~ReaderException() throw() {}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif // __READER_EXCEPTION_H__
|
|
@ -1,61 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
/*
|
||||
* Result.cpp
|
||||
* zxing
|
||||
*
|
||||
* Created by Christian Brunschen on 13/05/2008.
|
||||
* Copyright 2008 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/Result.h>
|
||||
|
||||
using zxing::Result;
|
||||
using zxing::Ref;
|
||||
using zxing::ArrayRef;
|
||||
using zxing::String;
|
||||
using zxing::ResultPoint;
|
||||
|
||||
// VC++
|
||||
using zxing::BarcodeFormat;
|
||||
|
||||
Result::Result(Ref<String> text,
|
||||
ArrayRef<char> rawBytes,
|
||||
ArrayRef< Ref<ResultPoint> > resultPoints,
|
||||
BarcodeFormat format) :
|
||||
text_(text), rawBytes_(rawBytes), resultPoints_(resultPoints), format_(format) {
|
||||
}
|
||||
|
||||
Result::~Result() {
|
||||
}
|
||||
|
||||
Ref<String> Result::getText() {
|
||||
return text_;
|
||||
}
|
||||
|
||||
ArrayRef<char> Result::getRawBytes() {
|
||||
return rawBytes_;
|
||||
}
|
||||
|
||||
ArrayRef< Ref<ResultPoint> > const& Result::getResultPoints() const {
|
||||
return resultPoints_;
|
||||
}
|
||||
|
||||
ArrayRef< Ref<ResultPoint> >& Result::getResultPoints() {
|
||||
return resultPoints_;
|
||||
}
|
||||
|
||||
zxing::BarcodeFormat Result::getBarcodeFormat() const {
|
||||
return format_;
|
||||
}
|
|
@ -1,55 +0,0 @@
|
|||
#ifndef __RESULT_H__
|
||||
#define __RESULT_H__
|
||||
|
||||
/*
|
||||
* Result.h
|
||||
* zxing
|
||||
*
|
||||
* Copyright 2010 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <string>
|
||||
#include <zxing/common/Array.h>
|
||||
#include <zxing/common/Counted.h>
|
||||
#include <zxing/common/Str.h>
|
||||
#include <zxing/ResultPoint.h>
|
||||
#include <zxing/BarcodeFormat.h>
|
||||
|
||||
namespace zxing {
|
||||
|
||||
class Result : public Counted {
|
||||
private:
|
||||
Ref<String> text_;
|
||||
ArrayRef<char> rawBytes_;
|
||||
ArrayRef< Ref<ResultPoint> > resultPoints_;
|
||||
BarcodeFormat format_;
|
||||
|
||||
public:
|
||||
Result(Ref<String> text,
|
||||
ArrayRef<char> rawBytes,
|
||||
ArrayRef< Ref<ResultPoint> > resultPoints,
|
||||
BarcodeFormat format);
|
||||
~Result();
|
||||
Ref<String> getText();
|
||||
ArrayRef<char> getRawBytes();
|
||||
ArrayRef< Ref<ResultPoint> > const& getResultPoints() const;
|
||||
ArrayRef< Ref<ResultPoint> >& getResultPoints();
|
||||
BarcodeFormat getBarcodeFormat() const;
|
||||
|
||||
friend std::ostream& operator<<(std::ostream &out, Result& result);
|
||||
};
|
||||
|
||||
}
|
||||
#endif // __RESULT_H__
|
|
@ -1,34 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
/*
|
||||
* ResultIO.cpp
|
||||
* zxing
|
||||
*
|
||||
* Created by Christian Brunschen on 13/05/2008.
|
||||
* Copyright 2008 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/Result.h>
|
||||
|
||||
using zxing::Result;
|
||||
using std::ostream;
|
||||
|
||||
ostream& zxing::operator<<(ostream &out, Result& result) {
|
||||
if (result.text_ != 0) {
|
||||
out << result.text_->getText();
|
||||
} else {
|
||||
out << "[" << result.rawBytes_->size() << " bytes]";
|
||||
}
|
||||
return out;
|
||||
}
|
|
@ -1,108 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
/*
|
||||
* ResultPoint.cpp
|
||||
* zxing
|
||||
*
|
||||
* Created by Christian Brunschen on 13/05/2008.
|
||||
* Copyright 2008 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/ResultPoint.h>
|
||||
#include <zxing/common/detector/MathUtils.h>
|
||||
|
||||
using zxing::common::detector::MathUtils;
|
||||
|
||||
namespace zxing {
|
||||
|
||||
ResultPoint::ResultPoint() : posX_(0), posY_(0) {}
|
||||
|
||||
ResultPoint::ResultPoint(float x, float y) : posX_(x), posY_(y) {}
|
||||
|
||||
ResultPoint::ResultPoint(int x, int y) : posX_(float(x)), posY_(float(y)) {}
|
||||
|
||||
ResultPoint::~ResultPoint() {}
|
||||
|
||||
float ResultPoint::getX() const {
|
||||
return posX_;
|
||||
}
|
||||
|
||||
float ResultPoint::getY() const {
|
||||
return posY_;
|
||||
}
|
||||
|
||||
bool ResultPoint::equals(Ref<ResultPoint> other) {
|
||||
return posX_ == other->getX() && posY_ == other->getY();
|
||||
}
|
||||
|
||||
/**
|
||||
* <p>Orders an array of three ResultPoints in an order [A,B,C] such that AB < AC and
|
||||
* BC < AC and the angle between BC and BA is less than 180 degrees.
|
||||
*/
|
||||
void ResultPoint::orderBestPatterns(std::vector<Ref<ResultPoint> > &patterns) {
|
||||
// Find distances between pattern centers
|
||||
float zeroOneDistance = distance(patterns[0]->getX(), patterns[1]->getX(),patterns[0]->getY(), patterns[1]->getY());
|
||||
float oneTwoDistance = distance(patterns[1]->getX(), patterns[2]->getX(),patterns[1]->getY(), patterns[2]->getY());
|
||||
float zeroTwoDistance = distance(patterns[0]->getX(), patterns[2]->getX(),patterns[0]->getY(), patterns[2]->getY());
|
||||
|
||||
Ref<ResultPoint> pointA, pointB, pointC;
|
||||
// Assume one closest to other two is B; A and C will just be guesses at first
|
||||
if (oneTwoDistance >= zeroOneDistance && oneTwoDistance >= zeroTwoDistance) {
|
||||
pointB = patterns[0];
|
||||
pointA = patterns[1];
|
||||
pointC = patterns[2];
|
||||
} else if (zeroTwoDistance >= oneTwoDistance && zeroTwoDistance >= zeroOneDistance) {
|
||||
pointB = patterns[1];
|
||||
pointA = patterns[0];
|
||||
pointC = patterns[2];
|
||||
} else {
|
||||
pointB = patterns[2];
|
||||
pointA = patterns[0];
|
||||
pointC = patterns[1];
|
||||
}
|
||||
|
||||
// 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) {
|
||||
Ref<ResultPoint> temp = pointA;
|
||||
pointA = pointC;
|
||||
pointC = temp;
|
||||
}
|
||||
|
||||
patterns[0] = pointA;
|
||||
patterns[1] = pointB;
|
||||
patterns[2] = pointC;
|
||||
}
|
||||
|
||||
float ResultPoint::distance(Ref<ResultPoint> pattern1, Ref<ResultPoint> pattern2) {
|
||||
return MathUtils::distance(pattern1->posX_,
|
||||
pattern1->posY_,
|
||||
pattern2->posX_,
|
||||
pattern2->posY_);
|
||||
}
|
||||
|
||||
float ResultPoint::distance(float x1, float x2, float y1, float y2) {
|
||||
float xDiff = x1 - x2;
|
||||
float yDiff = y1 - y2;
|
||||
return (float) sqrt((double) (xDiff * xDiff + yDiff * yDiff));
|
||||
}
|
||||
|
||||
float ResultPoint::crossProductZ(Ref<ResultPoint> pointA, Ref<ResultPoint> pointB, Ref<ResultPoint> pointC) {
|
||||
float bX = pointB->getX();
|
||||
float bY = pointB->getY();
|
||||
return ((pointC->getX() - bX) * (pointA->getY() - bY)) - ((pointC->getY() - bY) * (pointA->getX() - bX));
|
||||
}
|
||||
}
|
|
@ -1,55 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
#ifndef __RESULT_POINT_H__
|
||||
#define __RESULT_POINT_H__
|
||||
|
||||
/*
|
||||
* ResultPoint.h
|
||||
* zxing
|
||||
*
|
||||
* Copyright 2010 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/common/Counted.h>
|
||||
#include <vector>
|
||||
|
||||
namespace zxing {
|
||||
|
||||
class ResultPoint : public Counted {
|
||||
protected:
|
||||
const float posX_;
|
||||
const float posY_;
|
||||
|
||||
public:
|
||||
ResultPoint();
|
||||
ResultPoint(float x, float y);
|
||||
ResultPoint(int x, int y);
|
||||
virtual ~ResultPoint();
|
||||
|
||||
virtual float getX() const;
|
||||
virtual float getY() const;
|
||||
|
||||
bool equals(Ref<ResultPoint> other);
|
||||
|
||||
static void orderBestPatterns(std::vector<Ref<ResultPoint> > &patterns);
|
||||
static float distance(Ref<ResultPoint> point1, Ref<ResultPoint> point2);
|
||||
static float distance(float x1, float x2, float y1, float y2);
|
||||
|
||||
private:
|
||||
static float crossProductZ(Ref<ResultPoint> pointA, Ref<ResultPoint> pointB, Ref<ResultPoint> pointC);
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif // __RESULT_POINT_H__
|
|
@ -1,26 +0,0 @@
|
|||
/*
|
||||
* ResultPointCallback.cpp
|
||||
* zxing
|
||||
*
|
||||
* Copyright 2010 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/ResultPointCallback.h>
|
||||
|
||||
namespace zxing {
|
||||
|
||||
ResultPointCallback::~ResultPointCallback() {}
|
||||
|
||||
}
|
|
@ -1,39 +0,0 @@
|
|||
#ifndef __RESULT_POINT_CALLBACK_H__
|
||||
#define __RESULT_POINT_CALLBACK_H__
|
||||
|
||||
/*
|
||||
* ResultPointCallback.h
|
||||
* zxing
|
||||
*
|
||||
* Copyright 2010 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/common/Counted.h>
|
||||
|
||||
namespace zxing {
|
||||
|
||||
class ResultPoint;
|
||||
|
||||
class ResultPointCallback : public Counted {
|
||||
protected:
|
||||
ResultPointCallback() {}
|
||||
public:
|
||||
virtual void foundPossibleResultPoint(ResultPoint const& point) = 0;
|
||||
virtual ~ResultPointCallback();
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif // __RESULT_POINT_CALLBACK_H__
|
|
@ -1,133 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
/*
|
||||
* Copyright 2013 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
#ifndef __ZXING_H_
|
||||
#define __ZXING_H_
|
||||
|
||||
#define ZXING_ARRAY_LEN(v) ((int)(sizeof(v)/sizeof(v[0])))
|
||||
#define ZX_LOG_DIGITS(digits) \
|
||||
((digits == 8) ? 3 : \
|
||||
((digits == 16) ? 4 : \
|
||||
((digits == 32) ? 5 : \
|
||||
((digits == 64) ? 6 : \
|
||||
((digits == 128) ? 7 : \
|
||||
(-1))))))
|
||||
|
||||
#ifndef ZXING_DEBUG
|
||||
#define ZXING_DEBUG 0
|
||||
#endif
|
||||
|
||||
namespace zxing {
|
||||
typedef char byte;
|
||||
typedef bool boolean;
|
||||
}
|
||||
|
||||
#include <limits>
|
||||
|
||||
#if defined(_WIN32) || defined(_WIN64)
|
||||
|
||||
#include <float.h>
|
||||
|
||||
namespace zxing {
|
||||
inline bool isnan(float v) {return _isnan(v) != 0;}
|
||||
inline bool isnan(double v) {return _isnan(v) != 0;}
|
||||
inline float nan() {return std::numeric_limits<float>::quiet_NaN();}
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
#include <cmath>
|
||||
|
||||
namespace zxing {
|
||||
inline bool isnan(float v) {return std::isnan(v);}
|
||||
inline bool isnan(double v) {return std::isnan(v);}
|
||||
inline float nan() {return std::numeric_limits<float>::quiet_NaN();}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
#if ZXING_DEBUG
|
||||
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
|
||||
using std::cout;
|
||||
using std::cerr;
|
||||
using std::endl;
|
||||
using std::flush;
|
||||
using std::string;
|
||||
using std::ostream;
|
||||
|
||||
#if ZXING_DEBUG_TIMER
|
||||
|
||||
#include <sys/time.h>
|
||||
|
||||
namespace zxing {
|
||||
|
||||
class DebugTimer {
|
||||
public:
|
||||
DebugTimer(char const* string_) : chars(string_) {
|
||||
gettimeofday(&start, 0);
|
||||
}
|
||||
|
||||
DebugTimer(std::string const& string_) : chars(0), string(string_) {
|
||||
gettimeofday(&start, 0);
|
||||
}
|
||||
|
||||
void mark(char const* string) {
|
||||
struct timeval end;
|
||||
gettimeofday(&end, 0);
|
||||
int diff =
|
||||
(end.tv_sec - start.tv_sec)*1000*1000+(end.tv_usec - start.tv_usec);
|
||||
|
||||
cerr << diff << " " << string << '\n';
|
||||
}
|
||||
|
||||
void mark(std::string string) {
|
||||
mark(string.c_str());
|
||||
}
|
||||
|
||||
~DebugTimer() {
|
||||
if (chars) {
|
||||
mark(chars);
|
||||
} else {
|
||||
mark(string.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
char const* const chars;
|
||||
std::string string;
|
||||
struct timeval start;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#define ZXING_TIME(string) DebugTimer __timer__ (string)
|
||||
#define ZXING_TIME_MARK(string) __timer__.mark(string)
|
||||
|
||||
#endif
|
||||
|
||||
#endif // ZXING_DEBUG
|
||||
|
||||
#ifndef ZXING_TIME
|
||||
#define ZXING_TIME(string) (void)0
|
||||
#endif
|
||||
#ifndef ZXING_TIME_MARK
|
||||
#define ZXING_TIME_MARK(string) (void)0
|
||||
#endif
|
||||
|
||||
#endif
|
|
@ -1,54 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
/*
|
||||
* AtztecDetecorResult.cpp
|
||||
* zxing
|
||||
*
|
||||
* Created by Lukas Stabe on 08/02/2012.
|
||||
* Copyright 2012 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/aztec/AztecDetectorResult.h>
|
||||
|
||||
using zxing::aztec::AztecDetectorResult;
|
||||
|
||||
// VC++
|
||||
using zxing::Ref;
|
||||
using zxing::ArrayRef;
|
||||
using zxing::BitMatrix;
|
||||
using zxing::ResultPoint;
|
||||
|
||||
|
||||
AztecDetectorResult::AztecDetectorResult(Ref<BitMatrix> bits,
|
||||
ArrayRef< Ref<ResultPoint> > points,
|
||||
bool compact,
|
||||
int nbDatablocks,
|
||||
int nbLayers)
|
||||
: DetectorResult(bits, points),
|
||||
compact_(compact),
|
||||
nbDatablocks_(nbDatablocks),
|
||||
nbLayers_(nbLayers) {
|
||||
}
|
||||
|
||||
bool AztecDetectorResult::isCompact() {
|
||||
return compact_;
|
||||
}
|
||||
|
||||
int AztecDetectorResult::getNBDatablocks() {
|
||||
return nbDatablocks_;
|
||||
}
|
||||
|
||||
int AztecDetectorResult::getNBLayers() {
|
||||
return nbLayers_;
|
||||
}
|
|
@ -1,48 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
/*
|
||||
* AtztecDetecorResult.h
|
||||
* zxing
|
||||
*
|
||||
* Created by Lukas Stabe on 08/02/2012.
|
||||
* Copyright 2012 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/common/DetectorResult.h>
|
||||
|
||||
#ifndef ZXingWidget_AtztecDetecorResult_h
|
||||
#define ZXingWidget_AtztecDetecorResult_h
|
||||
|
||||
namespace zxing {
|
||||
namespace aztec {
|
||||
|
||||
class AztecDetectorResult : public DetectorResult {
|
||||
private:
|
||||
bool compact_;
|
||||
int nbDatablocks_, nbLayers_;
|
||||
public:
|
||||
AztecDetectorResult(Ref<BitMatrix> bits,
|
||||
ArrayRef< Ref<ResultPoint> > points,
|
||||
bool compact,
|
||||
int nbDatablocks,
|
||||
int nbLayers);
|
||||
bool isCompact();
|
||||
int getNBDatablocks();
|
||||
int getNBLayers();
|
||||
};
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
|
@ -1,68 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
/*
|
||||
* AztecReader.cpp
|
||||
* zxing
|
||||
*
|
||||
* Created by Lukas Stabe on 08/02/2012.
|
||||
* Copyright 2012 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/aztec/AztecReader.h>
|
||||
#include <zxing/aztec/detector/Detector.h>
|
||||
#include <zxing/common/DecoderResult.h>
|
||||
#include <iostream>
|
||||
|
||||
using zxing::Ref;
|
||||
using zxing::ArrayRef;
|
||||
using zxing::Result;
|
||||
using zxing::aztec::AztecReader;
|
||||
|
||||
// VC++
|
||||
using zxing::BinaryBitmap;
|
||||
using zxing::DecodeHints;
|
||||
|
||||
AztecReader::AztecReader() : decoder_() {
|
||||
// nothing
|
||||
}
|
||||
|
||||
Ref<Result> AztecReader::decode(Ref<zxing::BinaryBitmap> image) {
|
||||
Detector detector(image->getBlackMatrix());
|
||||
|
||||
Ref<AztecDetectorResult> detectorResult(detector.detect());
|
||||
|
||||
ArrayRef< Ref<ResultPoint> > points(detectorResult->getPoints());
|
||||
|
||||
Ref<DecoderResult> decoderResult(decoder_.decode(detectorResult));
|
||||
|
||||
Ref<Result> result(new Result(decoderResult->getText(),
|
||||
decoderResult->getRawBytes(),
|
||||
points,
|
||||
BarcodeFormat::AZTEC));
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
Ref<Result> AztecReader::decode(Ref<BinaryBitmap> image, DecodeHints) {
|
||||
//cout << "decoding with hints not supported for aztec" << "\n" << flush;
|
||||
return this->decode(image);
|
||||
}
|
||||
|
||||
AztecReader::~AztecReader() {
|
||||
// nothing
|
||||
}
|
||||
|
||||
zxing::aztec::Decoder& AztecReader::getDecoder() {
|
||||
return decoder_;
|
||||
}
|
|
@ -1,49 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
/*
|
||||
* AztecReader.h
|
||||
* zxing
|
||||
*
|
||||
* Created by Lukas Stabe on 08/02/2012.
|
||||
* Copyright 2012 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/Reader.h>
|
||||
#include <zxing/aztec/decoder/Decoder.h>
|
||||
#include <zxing/DecodeHints.h>
|
||||
|
||||
#ifndef ZXingWidget_AztecReader_h
|
||||
#define ZXingWidget_AztecReader_h
|
||||
|
||||
namespace zxing {
|
||||
namespace aztec {
|
||||
|
||||
class AztecReader : public Reader {
|
||||
private:
|
||||
Decoder decoder_;
|
||||
|
||||
protected:
|
||||
Decoder &getDecoder();
|
||||
|
||||
public:
|
||||
AztecReader();
|
||||
virtual Ref<Result> decode(Ref<BinaryBitmap> image);
|
||||
virtual Ref<Result> decode(Ref<BinaryBitmap> image, DecodeHints hints);
|
||||
virtual ~AztecReader();
|
||||
};
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
|
@ -1,489 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
/*
|
||||
* Decoder.cpp
|
||||
* zxing
|
||||
*
|
||||
* Created by Lukas Stabe on 08/02/2012.
|
||||
* Copyright 2012 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/aztec/decoder/Decoder.h>
|
||||
#ifndef NO_ICONV
|
||||
#include <iconv.h>
|
||||
#endif
|
||||
#include <iostream>
|
||||
#include <zxing/FormatException.h>
|
||||
#include <zxing/common/reedsolomon/ReedSolomonDecoder.h>
|
||||
#include <zxing/common/reedsolomon/ReedSolomonException.h>
|
||||
#include <zxing/common/reedsolomon/GenericGF.h>
|
||||
#include <zxing/common/IllegalArgumentException.h>
|
||||
#include <zxing/common/DecoderResult.h>
|
||||
|
||||
using zxing::aztec::Decoder;
|
||||
using zxing::DecoderResult;
|
||||
using zxing::String;
|
||||
using zxing::BitArray;
|
||||
using zxing::BitMatrix;
|
||||
using zxing::Ref;
|
||||
|
||||
using std::string;
|
||||
|
||||
namespace {
|
||||
void add(string& result, char character) {
|
||||
#ifndef NO_ICONV
|
||||
char character2 = character & 0xff;
|
||||
char s[] = {character2};
|
||||
char* ss = s;
|
||||
size_t sl = sizeof(s);
|
||||
char d[4];
|
||||
char* ds = d;
|
||||
size_t dl = sizeof(d);
|
||||
iconv_t ic = iconv_open("UTF-8", "ISO-8859-1");
|
||||
iconv(ic, &ss, &sl, &ds, &dl);
|
||||
iconv_close(ic);
|
||||
d[sizeof(d)-dl] = 0;
|
||||
result.append(d);
|
||||
#else
|
||||
result.push_back(character);
|
||||
#endif
|
||||
}
|
||||
|
||||
const int NB_BITS_COMPACT[] = {
|
||||
0, 104, 240, 408, 608
|
||||
};
|
||||
|
||||
const int NB_BITS[] = {
|
||||
0, 128, 288, 480, 704, 960, 1248, 1568, 1920, 2304, 2720, 3168, 3648, 4160, 4704, 5280, 5888, 6528,
|
||||
7200, 7904, 8640, 9408, 10208, 11040, 11904, 12800, 13728, 14688, 15680, 16704, 17760, 18848, 19968
|
||||
};
|
||||
|
||||
const int NB_DATABLOCK_COMPACT[] = {
|
||||
0, 17, 40, 51, 76
|
||||
};
|
||||
|
||||
const int NB_DATABLOCK[] = {
|
||||
0, 21, 48, 60, 88, 120, 156, 196, 240, 230, 272, 316, 364, 416, 470, 528, 588, 652, 720, 790, 864,
|
||||
940, 1020, 920, 992, 1066, 1144, 1224, 1306, 1392, 1480, 1570, 1664
|
||||
};
|
||||
|
||||
const char* UPPER_TABLE[] = {
|
||||
"CTRL_PS", " ", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P",
|
||||
"Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "CTRL_LL", "CTRL_ML", "CTRL_DL", "CTRL_BS"
|
||||
};
|
||||
|
||||
const char* LOWER_TABLE[] = {
|
||||
"CTRL_PS", " ", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p",
|
||||
"q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "CTRL_US", "CTRL_ML", "CTRL_DL", "CTRL_BS"
|
||||
};
|
||||
|
||||
const char* MIXED_TABLE[] = {
|
||||
"CTRL_PS", " ", "\1", "\2", "\3", "\4", "\5", "\6", "\7", "\b", "\t", "\n",
|
||||
"\13", "\f", "\r", "\33", "\34", "\35", "\36", "\37", "@", "\\", "^", "_",
|
||||
"`", "|", "~", "\177", "CTRL_LL", "CTRL_UL", "CTRL_PL", "CTRL_BS"
|
||||
};
|
||||
|
||||
const char* PUNCT_TABLE[] = {
|
||||
"", "\r", "\r\n", ". ", ", ", ": ", "!", "\"", "#", "$", "%", "&", "'", "(", ")",
|
||||
"*", "+", ",", "-", ".", "/", ":", ";", "<", "=", ">", "?", "[", "]", "{", "}", "CTRL_UL"
|
||||
};
|
||||
|
||||
const char* DIGIT_TABLE[] = {
|
||||
"CTRL_PS", " ", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ",", ".", "CTRL_UL", "CTRL_US"
|
||||
};
|
||||
}
|
||||
|
||||
Decoder::Table Decoder::getTable(char t) {
|
||||
switch (t) {
|
||||
case 'L':
|
||||
return LOWER;
|
||||
case 'P':
|
||||
return PUNCT;
|
||||
case 'M':
|
||||
return MIXED;
|
||||
case 'D':
|
||||
return DIGIT;
|
||||
case 'B':
|
||||
return BINARY;
|
||||
case 'U':
|
||||
default:
|
||||
return UPPER;
|
||||
}
|
||||
}
|
||||
|
||||
const char* Decoder::getCharacter(zxing::aztec::Decoder::Table table, int code) {
|
||||
switch (table) {
|
||||
case UPPER:
|
||||
return UPPER_TABLE[code];
|
||||
case LOWER:
|
||||
return LOWER_TABLE[code];
|
||||
case MIXED:
|
||||
return MIXED_TABLE[code];
|
||||
case PUNCT:
|
||||
return PUNCT_TABLE[code];
|
||||
case DIGIT:
|
||||
return DIGIT_TABLE[code];
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
Decoder::Decoder() {
|
||||
// nothing
|
||||
}
|
||||
|
||||
Ref<DecoderResult> Decoder::decode(Ref<zxing::aztec::AztecDetectorResult> detectorResult) {
|
||||
ddata_ = detectorResult;
|
||||
|
||||
// std::printf("getting bits\n");
|
||||
|
||||
Ref<BitMatrix> matrix = detectorResult->getBits();
|
||||
|
||||
if (!ddata_->isCompact()) {
|
||||
// std::printf("removing lines\n");
|
||||
matrix = removeDashedLines(ddata_->getBits());
|
||||
}
|
||||
|
||||
// std::printf("extracting bits\n");
|
||||
Ref<BitArray> rawbits = extractBits(matrix);
|
||||
|
||||
// std::printf("correcting bits\n");
|
||||
Ref<BitArray> aCorrectedBits = correctBits(rawbits);
|
||||
|
||||
// std::printf("decoding bits\n");
|
||||
Ref<String> result = getEncodedData(aCorrectedBits);
|
||||
|
||||
// std::printf("constructing array\n");
|
||||
ArrayRef<char> arrayOut(aCorrectedBits->getSize());
|
||||
for (int i = 0; i < aCorrectedBits->count(); i++) {
|
||||
arrayOut[i] = (char)aCorrectedBits->get(i);
|
||||
}
|
||||
|
||||
// std::printf("returning\n");
|
||||
|
||||
return Ref<DecoderResult>(new DecoderResult(arrayOut, result));
|
||||
}
|
||||
|
||||
Ref<String> Decoder::getEncodedData(Ref<zxing::BitArray> correctedBits) {
|
||||
int endIndex = codewordSize_ * ddata_->getNBDatablocks() - invertedBitCount_;
|
||||
if (endIndex > (int)correctedBits->getSize()) {
|
||||
// std::printf("invalid input\n");
|
||||
throw FormatException("invalid input data");
|
||||
}
|
||||
|
||||
Table lastTable = UPPER;
|
||||
Table table = UPPER;
|
||||
int startIndex = 0;
|
||||
std::string result;
|
||||
bool end = false;
|
||||
bool shift = false;
|
||||
bool switchShift = false;
|
||||
bool binaryShift = false;
|
||||
|
||||
while (!end) {
|
||||
// std::printf("decoooooding\n");
|
||||
|
||||
if (shift) {
|
||||
switchShift = true;
|
||||
} else {
|
||||
lastTable = table;
|
||||
}
|
||||
|
||||
int code;
|
||||
if (binaryShift) {
|
||||
if (endIndex - startIndex < 5) {
|
||||
break;
|
||||
}
|
||||
|
||||
int length = readCode(correctedBits, startIndex, 5);
|
||||
startIndex += 5;
|
||||
if (length == 0) {
|
||||
if (endIndex - startIndex < 11) {
|
||||
break;
|
||||
}
|
||||
|
||||
length = readCode(correctedBits, startIndex, 11) + 31;
|
||||
startIndex += 11;
|
||||
}
|
||||
for (int charCount = 0; charCount < length; charCount++) {
|
||||
if (endIndex - startIndex < 8) {
|
||||
end = true;
|
||||
break;
|
||||
}
|
||||
|
||||
code = readCode(correctedBits, startIndex, 8);
|
||||
add(result, code);
|
||||
startIndex += 8;
|
||||
}
|
||||
binaryShift = false;
|
||||
} else {
|
||||
if (table == BINARY) {
|
||||
if (endIndex - startIndex < 8) {
|
||||
break;
|
||||
}
|
||||
code = readCode(correctedBits, startIndex, 8);
|
||||
startIndex += 8;
|
||||
|
||||
add(result, code);
|
||||
} else {
|
||||
int size = 5;
|
||||
|
||||
if (table == DIGIT) {
|
||||
size = 4;
|
||||
}
|
||||
|
||||
if (endIndex - startIndex < size) {
|
||||
break;
|
||||
}
|
||||
|
||||
code = readCode(correctedBits, startIndex, size);
|
||||
startIndex += size;
|
||||
|
||||
const char *str = getCharacter(table, code);
|
||||
std::string string(str);
|
||||
if ((int)string.find("CTRL_") != -1) {
|
||||
table = getTable(str[5]);
|
||||
|
||||
if (str[6] == 'S') {
|
||||
shift = true;
|
||||
if (str[5] == 'B') {
|
||||
binaryShift = true;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
result.append(string);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
if (switchShift) {
|
||||
table = lastTable;
|
||||
shift = false;
|
||||
switchShift = false;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
return Ref<String>(new String(result));
|
||||
|
||||
}
|
||||
|
||||
Ref<BitArray> Decoder::correctBits(Ref<zxing::BitArray> rawbits) {
|
||||
//return rawbits;
|
||||
// std::printf("decoding stuff:%d datablocks in %d layers\n", ddata_->getNBDatablocks(), ddata_->getNBLayers());
|
||||
|
||||
Ref<GenericGF> gf = GenericGF::AZTEC_DATA_6;
|
||||
|
||||
if (ddata_->getNBLayers() <= 2) {
|
||||
codewordSize_ = 6;
|
||||
gf = GenericGF::AZTEC_DATA_6;
|
||||
} else if (ddata_->getNBLayers() <= 8) {
|
||||
codewordSize_ = 8;
|
||||
gf = GenericGF::AZTEC_DATA_8;
|
||||
} else if (ddata_->getNBLayers() <= 22) {
|
||||
codewordSize_ = 10;
|
||||
gf = GenericGF::AZTEC_DATA_10;
|
||||
} else {
|
||||
codewordSize_ = 12;
|
||||
gf = GenericGF::AZTEC_DATA_12;
|
||||
}
|
||||
|
||||
int numDataCodewords = ddata_->getNBDatablocks();
|
||||
int numECCodewords;
|
||||
int offset;
|
||||
|
||||
if (ddata_->isCompact()) {
|
||||
offset = NB_BITS_COMPACT[ddata_->getNBLayers()] - numCodewords_ * codewordSize_;
|
||||
numECCodewords = NB_DATABLOCK_COMPACT[ddata_->getNBLayers()] - numDataCodewords;
|
||||
} else {
|
||||
offset = NB_BITS[ddata_->getNBLayers()] - numCodewords_ * codewordSize_;
|
||||
numECCodewords = NB_DATABLOCK[ddata_->getNBLayers()] - numDataCodewords;
|
||||
}
|
||||
|
||||
ArrayRef<int> dataWords(numCodewords_);
|
||||
|
||||
for (int i = 0; i < numCodewords_; i++) {
|
||||
int flag = 1;
|
||||
for (int j = 1; j <= codewordSize_; j++) {
|
||||
if (rawbits->get(codewordSize_ * i + codewordSize_ - j + offset)) {
|
||||
dataWords[i] += flag;
|
||||
}
|
||||
flag <<= 1;
|
||||
}
|
||||
|
||||
//
|
||||
//
|
||||
//
|
||||
}
|
||||
|
||||
try {
|
||||
ReedSolomonDecoder rsDecoder(gf);
|
||||
rsDecoder.decode(dataWords, numECCodewords);
|
||||
} catch (ReedSolomonException const& ignored) {
|
||||
(void)ignored;
|
||||
// std::printf("got reed solomon exception:%s, throwing formatexception\n", rse.what());
|
||||
throw FormatException("rs decoding failed");
|
||||
} catch (IllegalArgumentException const& iae) {
|
||||
(void)iae;
|
||||
// std::printf("illegal argument exception: %s", iae.what());
|
||||
}
|
||||
|
||||
offset = 0;
|
||||
invertedBitCount_ = 0;
|
||||
|
||||
Ref<BitArray> correctedBits(new BitArray(numDataCodewords * codewordSize_));
|
||||
for (int i = 0; i < numDataCodewords; i++) {
|
||||
|
||||
bool seriesColor = false;
|
||||
int seriesCount = 0;
|
||||
int flag = 1 << (codewordSize_ - 1);
|
||||
|
||||
for (int j = 0; j < codewordSize_; j++) {
|
||||
|
||||
bool color = (dataWords[i] & flag) == flag;
|
||||
|
||||
if (seriesCount == codewordSize_ - 1) {
|
||||
|
||||
if (color == seriesColor) {
|
||||
throw FormatException("bit was not inverted");
|
||||
}
|
||||
|
||||
seriesColor = false;
|
||||
seriesCount = 0;
|
||||
offset++;
|
||||
invertedBitCount_++;
|
||||
|
||||
} else {
|
||||
|
||||
if (seriesColor == color) {
|
||||
seriesCount++;
|
||||
} else {
|
||||
seriesCount = 1;
|
||||
seriesColor = color;
|
||||
}
|
||||
|
||||
if (color) correctedBits->set(i * codewordSize_ + j - offset);
|
||||
|
||||
}
|
||||
|
||||
flag = ((unsigned int)flag) >> 1;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
return correctedBits;
|
||||
}
|
||||
|
||||
Ref<BitArray> Decoder::extractBits(Ref<zxing::BitMatrix> matrix) {
|
||||
std::vector<bool> rawbits;
|
||||
|
||||
if (ddata_->isCompact()) {
|
||||
if (ddata_->getNBLayers() > 5) { //NB_BITS_COMPACT length
|
||||
throw FormatException("data is too long");
|
||||
}
|
||||
rawbits = std::vector<bool>(NB_BITS_COMPACT[ddata_->getNBLayers()]);
|
||||
numCodewords_ = NB_DATABLOCK_COMPACT[ddata_->getNBLayers()];
|
||||
} else {
|
||||
if (ddata_->getNBLayers() > 33) { //NB_BITS length
|
||||
throw FormatException("data is too long");
|
||||
}
|
||||
rawbits = std::vector<bool>(NB_BITS[ddata_->getNBLayers()]);
|
||||
numCodewords_ = NB_DATABLOCK[ddata_->getNBLayers()];
|
||||
}
|
||||
|
||||
int layer = ddata_->getNBLayers();
|
||||
int size = matrix->getHeight();
|
||||
int rawbitsOffset = 0;
|
||||
int matrixOffset = 0;
|
||||
|
||||
|
||||
while (layer != 0) {
|
||||
|
||||
int flip = 0;
|
||||
for (int i = 0; i < 2 * size - 4; i++) {
|
||||
rawbits[rawbitsOffset + i] = matrix->get(matrixOffset + flip, matrixOffset + i / 2);
|
||||
rawbits[rawbitsOffset + 2 * size - 4 + i] = matrix->get(matrixOffset + i / 2, matrixOffset + size - 1 - flip);
|
||||
flip = (flip + 1) % 2;
|
||||
}
|
||||
|
||||
flip = 0;
|
||||
for (int i = 2 * size + 1; i > 5; i--) {
|
||||
rawbits[rawbitsOffset + 4 * size - 8 + (2 * size - i) + 1] =
|
||||
matrix->get(matrixOffset + size - 1 - flip, matrixOffset + i / 2 - 1);
|
||||
rawbits[rawbitsOffset + 6 * size - 12 + (2 * size - i) + 1] =
|
||||
matrix->get(matrixOffset + i / 2 - 1, matrixOffset + flip);
|
||||
flip = (flip + 1) % 2;
|
||||
}
|
||||
|
||||
matrixOffset += 2;
|
||||
rawbitsOffset += 8 * size - 16;
|
||||
layer--;
|
||||
size -= 4;
|
||||
|
||||
}
|
||||
|
||||
Ref<BitArray> returnValue(new BitArray(rawbits.size()));
|
||||
for (int i = 0; i < (int)rawbits.size(); i++) {
|
||||
if (rawbits[i]) returnValue->set(i);
|
||||
}
|
||||
|
||||
return returnValue;
|
||||
|
||||
}
|
||||
|
||||
Ref<BitMatrix> Decoder::removeDashedLines(Ref<zxing::BitMatrix> matrix) {
|
||||
int nbDashed = 1 + 2 * ((matrix->getWidth() - 1) / 2 / 16);
|
||||
Ref<BitMatrix> newMatrix(new BitMatrix(matrix->getWidth() - nbDashed, matrix->getHeight() - nbDashed));
|
||||
|
||||
int nx = 0;
|
||||
|
||||
for (int x = 0; x < (int)matrix->getWidth(); x++) {
|
||||
|
||||
if ((matrix->getWidth() / 2 - x) % 16 == 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
int ny = 0;
|
||||
for (int y = 0; y < (int)matrix->getHeight(); y++) {
|
||||
|
||||
if ((matrix->getWidth() / 2 - y) % 16 == 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (matrix->get(x, y)) {
|
||||
newMatrix->set(nx, ny);
|
||||
}
|
||||
ny++;
|
||||
|
||||
}
|
||||
nx++;
|
||||
|
||||
}
|
||||
return newMatrix;
|
||||
}
|
||||
|
||||
int Decoder::readCode(Ref<zxing::BitArray> rawbits, int startIndex, int length) {
|
||||
int res = 0;
|
||||
|
||||
for (int i = startIndex; i < startIndex + length; i++) {
|
||||
res <<= 1;
|
||||
if (rawbits->get(i)) {
|
||||
res ++;
|
||||
}
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
|
@ -1,69 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
/*
|
||||
* Decoder.h
|
||||
* zxing
|
||||
*
|
||||
* Created by Lukas Stabe on 08/02/2012.
|
||||
* Copyright 2012 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef __ZXING_AZTEC_DECODER_DECODER_H__
|
||||
#define __ZXING_AZTEC_DECODER_DECODER_H__
|
||||
|
||||
#include <zxing/common/BitMatrix.h>
|
||||
#include <zxing/common/Str.h>
|
||||
#include <zxing/aztec/AztecDetectorResult.h>
|
||||
|
||||
namespace zxing {
|
||||
|
||||
class DecoderResult;
|
||||
|
||||
namespace aztec {
|
||||
|
||||
class Decoder : public Counted {
|
||||
private:
|
||||
enum Table {
|
||||
UPPER,
|
||||
LOWER,
|
||||
MIXED,
|
||||
DIGIT,
|
||||
PUNCT,
|
||||
BINARY
|
||||
};
|
||||
|
||||
static Table getTable(char t);
|
||||
static const char* getCharacter(Table table, int code);
|
||||
|
||||
int numCodewords_;
|
||||
int codewordSize_;
|
||||
Ref<AztecDetectorResult> ddata_;
|
||||
int invertedBitCount_;
|
||||
|
||||
Ref<String> getEncodedData(Ref<BitArray> correctedBits);
|
||||
Ref<BitArray> correctBits(Ref<BitArray> rawbits);
|
||||
Ref<BitArray> extractBits(Ref<BitMatrix> matrix);
|
||||
static Ref<BitMatrix> removeDashedLines(Ref<BitMatrix> matrix);
|
||||
static int readCode(Ref<BitArray> rawbits, int startIndex, int length);
|
||||
|
||||
|
||||
public:
|
||||
Decoder();
|
||||
Ref<DecoderResult> decode(Ref<AztecDetectorResult> detectorResult);
|
||||
};
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
|
@ -1,548 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
/*
|
||||
* Detector.cpp
|
||||
* zxing
|
||||
*
|
||||
* Created by Lukas Stabe on 08/02/2012.
|
||||
* Copyright 2012 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/aztec/detector/Detector.h>
|
||||
#include <zxing/common/GridSampler.h>
|
||||
#include <zxing/common/detector/WhiteRectangleDetector.h>
|
||||
#include <zxing/common/reedsolomon/ReedSolomonDecoder.h>
|
||||
#include <zxing/common/reedsolomon/ReedSolomonException.h>
|
||||
#include <zxing/common/reedsolomon/GenericGF.h>
|
||||
#include <iostream>
|
||||
#include <zxing/common/detector/MathUtils.h>
|
||||
#include <zxing/NotFoundException.h>
|
||||
|
||||
using std::vector;
|
||||
using zxing::aztec::Detector;
|
||||
using zxing::aztec::Point;
|
||||
using zxing::aztec::AztecDetectorResult;
|
||||
using zxing::Ref;
|
||||
using zxing::ArrayRef;
|
||||
using zxing::ResultPoint;
|
||||
using zxing::BitArray;
|
||||
using zxing::BitMatrix;
|
||||
using zxing::common::detector::MathUtils;
|
||||
|
||||
Detector::Detector(Ref<BitMatrix> image):
|
||||
image_(image),
|
||||
nbLayers_(0),
|
||||
nbDataBlocks_(0),
|
||||
nbCenterLayers_(0) {
|
||||
|
||||
}
|
||||
|
||||
Ref<AztecDetectorResult> Detector::detect() {
|
||||
Ref<Point> pCenter = getMatrixCenter();
|
||||
|
||||
std::vector<Ref<Point> > bullEyeCornerPoints = getBullEyeCornerPoints(pCenter);
|
||||
|
||||
extractParameters(bullEyeCornerPoints);
|
||||
|
||||
ArrayRef< Ref<ResultPoint> > corners = getMatrixCornerPoints(bullEyeCornerPoints);
|
||||
|
||||
Ref<BitMatrix> bits =
|
||||
sampleGrid(image_,
|
||||
corners[shift_%4],
|
||||
corners[(shift_+3)%4],
|
||||
corners[(shift_+2)%4],
|
||||
corners[(shift_+1)%4]);
|
||||
|
||||
// std::printf("------------\ndetected: compact:%s, nbDataBlocks:%d, nbLayers:%d\n------------\n",compact_?"YES":"NO", nbDataBlocks_, nbLayers_);
|
||||
|
||||
return Ref<AztecDetectorResult>(new AztecDetectorResult(bits, corners, compact_, nbDataBlocks_, nbLayers_));
|
||||
}
|
||||
|
||||
void Detector::extractParameters(std::vector<Ref<Point> > bullEyeCornerPoints) {
|
||||
int twoCenterLayers = 2 * nbCenterLayers_;
|
||||
// get the bits around the bull's eye
|
||||
Ref<BitArray> resab = sampleLine(bullEyeCornerPoints[0], bullEyeCornerPoints[1], twoCenterLayers+1);
|
||||
Ref<BitArray> resbc = sampleLine(bullEyeCornerPoints[1], bullEyeCornerPoints[2], twoCenterLayers+1);
|
||||
Ref<BitArray> rescd = sampleLine(bullEyeCornerPoints[2], bullEyeCornerPoints[3], twoCenterLayers+1);
|
||||
Ref<BitArray> resda = sampleLine(bullEyeCornerPoints[3], bullEyeCornerPoints[0], twoCenterLayers+1);
|
||||
|
||||
// determin the orientation of the matrix
|
||||
if (resab->get(0) && resab->get(twoCenterLayers)) {
|
||||
shift_ = 0;
|
||||
} else if (resbc->get(0) && resbc->get(twoCenterLayers)) {
|
||||
shift_ = 1;
|
||||
} else if (rescd->get(0) && rescd->get(twoCenterLayers)) {
|
||||
shift_ = 2;
|
||||
} else if (resda->get(0) && resda->get(twoCenterLayers)) {
|
||||
shift_ = 3;
|
||||
} else {
|
||||
// std::printf("could not detemine orientation\n");
|
||||
throw ReaderException("could not determine orientation");
|
||||
}
|
||||
|
||||
//d a
|
||||
//
|
||||
//c b
|
||||
|
||||
//flatten the bits in a single array
|
||||
Ref<BitArray> parameterData(new BitArray(compact_?28:40));
|
||||
Ref<BitArray> shiftedParameterData(new BitArray(compact_?28:40));
|
||||
|
||||
if (compact_) {
|
||||
for (int i = 0; i < 7; i++) {
|
||||
if (resab->get(2+i)) shiftedParameterData->set(i);
|
||||
if (resbc->get(2+i)) shiftedParameterData->set(i+7);
|
||||
if (rescd->get(2+i)) shiftedParameterData->set(i+14);
|
||||
if (resda->get(2+i)) shiftedParameterData->set(i+21);
|
||||
}
|
||||
for (int i = 0; i < 28; i++) {
|
||||
if (shiftedParameterData->get((i+shift_*7)%28)) parameterData->set(i);
|
||||
}
|
||||
|
||||
} else {
|
||||
for (int i = 0; i < 11; i++) {
|
||||
if (i < 5) {
|
||||
if (resab->get(2+i)) shiftedParameterData->set(i);
|
||||
if (resbc->get(2+i)) shiftedParameterData->set(i+10);
|
||||
if (rescd->get(2+i)) shiftedParameterData->set(i+20);
|
||||
if (resda->get(2+i)) shiftedParameterData->set(i+30);
|
||||
}
|
||||
if (i > 5) {
|
||||
if (resab->get(2+i)) shiftedParameterData->set(i-1);
|
||||
if (resbc->get(2+i)) shiftedParameterData->set(i+9);
|
||||
if (rescd->get(2+i)) shiftedParameterData->set(i+19);
|
||||
if (resda->get(2+i)) shiftedParameterData->set(i+29);
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < 40; i++) {
|
||||
if (shiftedParameterData->get((i+shift_*10)%40)) parameterData->set(i);
|
||||
}
|
||||
}
|
||||
|
||||
correctParameterData(parameterData, compact_);
|
||||
|
||||
getParameters(parameterData);
|
||||
}
|
||||
|
||||
ArrayRef< Ref<ResultPoint> >
|
||||
Detector::getMatrixCornerPoints(std::vector<Ref<Point> > bullEyeCornerPoints) {
|
||||
float ratio = (2 * nbLayers_ + (nbLayers_ > 4 ? 1 : 0) + (nbLayers_ - 4) / 8) / (2.0f * nbCenterLayers_);
|
||||
|
||||
int dx = bullEyeCornerPoints[0]->getX() - bullEyeCornerPoints[2]->getX();
|
||||
dx += dx > 0 ? 1 : -1;
|
||||
int dy = bullEyeCornerPoints[0]->getY() - bullEyeCornerPoints[2]->getY();
|
||||
dy += dy > 0 ? 1 : -1;
|
||||
|
||||
int targetcx = MathUtils::round(bullEyeCornerPoints[2]->getX() - ratio * dx);
|
||||
int targetcy = MathUtils::round(bullEyeCornerPoints[2]->getY() - ratio * dy);
|
||||
|
||||
int targetax = MathUtils::round(bullEyeCornerPoints[0]->getX() + ratio * dx);
|
||||
int targetay = MathUtils::round(bullEyeCornerPoints[0]->getY() + ratio * dy);
|
||||
|
||||
dx = bullEyeCornerPoints[1]->getX() - bullEyeCornerPoints[3]->getX();
|
||||
dx += dx > 0 ? 1 : -1;
|
||||
dy = bullEyeCornerPoints[1]->getY() - bullEyeCornerPoints[3]->getY();
|
||||
dy += dy > 0 ? 1 : -1;
|
||||
|
||||
int targetdx = MathUtils::round(bullEyeCornerPoints[3]->getX() - ratio * dx);
|
||||
int targetdy = MathUtils::round(bullEyeCornerPoints[3]->getY() - ratio * dy);
|
||||
int targetbx = MathUtils::round(bullEyeCornerPoints[1]->getX() + ratio * dx);
|
||||
int targetby = MathUtils::round(bullEyeCornerPoints[1]->getY() + ratio * dy);
|
||||
|
||||
if (!isValid(targetax, targetay) ||
|
||||
!isValid(targetbx, targetby) ||
|
||||
|
||||
!isValid(targetcx, targetcy) ||
|
||||
!isValid(targetdx, targetdy)) {
|
||||
throw ReaderException("matrix extends over image bounds");
|
||||
}
|
||||
Array< Ref<ResultPoint> >* array = new Array< Ref<ResultPoint> >();
|
||||
vector< Ref<ResultPoint> >& returnValue (array->values());
|
||||
returnValue.push_back(Ref<ResultPoint>(new ResultPoint(float(targetax), float(targetay))));
|
||||
returnValue.push_back(Ref<ResultPoint>(new ResultPoint(float(targetbx), float(targetby))));
|
||||
returnValue.push_back(Ref<ResultPoint>(new ResultPoint(float(targetcx), float(targetcy))));
|
||||
returnValue.push_back(Ref<ResultPoint>(new ResultPoint(float(targetdx), float(targetdy))));
|
||||
return ArrayRef< Ref<ResultPoint> >(array);
|
||||
}
|
||||
|
||||
void Detector::correctParameterData(Ref<zxing::BitArray> parameterData, bool compact) {
|
||||
int numCodewords;
|
||||
int numDataCodewords;
|
||||
|
||||
if (compact) {
|
||||
numCodewords = 7;
|
||||
numDataCodewords = 2;
|
||||
} else {
|
||||
numCodewords = 10;
|
||||
numDataCodewords = 4;
|
||||
}
|
||||
|
||||
int numECCodewords = numCodewords - numDataCodewords;
|
||||
|
||||
ArrayRef<int> parameterWords(new Array<int>(numCodewords));
|
||||
|
||||
int codewordSize = 4;
|
||||
for (int i = 0; i < numCodewords; i++) {
|
||||
int flag = 1;
|
||||
for (int j = 1; j <= codewordSize; j++) {
|
||||
if (parameterData->get(codewordSize*i + codewordSize - j)) {
|
||||
parameterWords[i] += flag;
|
||||
}
|
||||
flag <<= 1;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
// std::printf("parameter data reed solomon\n");
|
||||
ReedSolomonDecoder rsDecoder(GenericGF::AZTEC_PARAM);
|
||||
rsDecoder.decode(parameterWords, numECCodewords);
|
||||
} catch (ReedSolomonException const& ignored) {
|
||||
(void)ignored;
|
||||
// std::printf("reed solomon decoding failed\n");
|
||||
throw ReaderException("failed to decode parameter data");
|
||||
}
|
||||
|
||||
parameterData->clear();
|
||||
for (int i = 0; i < numDataCodewords; i++) {
|
||||
int flag = 1;
|
||||
for (int j = 1; j <= codewordSize; j++) {
|
||||
if ((parameterWords[i] & flag) == flag) {
|
||||
parameterData->set(i*codewordSize+codewordSize-j);
|
||||
}
|
||||
flag <<= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<Ref<Point> > Detector::getBullEyeCornerPoints(Ref<zxing::aztec::Point> pCenter) {
|
||||
Ref<Point> pina = pCenter;
|
||||
Ref<Point> pinb = pCenter;
|
||||
Ref<Point> pinc = pCenter;
|
||||
Ref<Point> pind = pCenter;
|
||||
|
||||
bool color = true;
|
||||
|
||||
for (nbCenterLayers_ = 1; nbCenterLayers_ < 9; nbCenterLayers_++) {
|
||||
Ref<Point> pouta = getFirstDifferent(pina, color, 1, -1);
|
||||
Ref<Point> poutb = getFirstDifferent(pinb, color, 1, 1);
|
||||
Ref<Point> poutc = getFirstDifferent(pinc, color, -1, 1);
|
||||
Ref<Point> poutd = getFirstDifferent(pind, color, -1, -1);
|
||||
|
||||
//d a
|
||||
//
|
||||
//c b
|
||||
|
||||
if (nbCenterLayers_ > 2) {
|
||||
float q = distance(poutd, pouta) * nbCenterLayers_ / (distance(pind, pina) * (nbCenterLayers_ + 2));
|
||||
if (q < 0.75 || q > 1.25 || !isWhiteOrBlackRectangle(pouta, poutb, poutc, poutd)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
pina = pouta;
|
||||
pinb = poutb;
|
||||
pinc = poutc;
|
||||
pind = poutd;
|
||||
|
||||
color = !color;
|
||||
}
|
||||
|
||||
if (nbCenterLayers_ != 5 && nbCenterLayers_ != 7) {
|
||||
throw ReaderException("encountered wrong bullseye ring count");
|
||||
}
|
||||
|
||||
compact_ = nbCenterLayers_ == 5;
|
||||
|
||||
|
||||
|
||||
float ratio = 0.75f*2 / (2*nbCenterLayers_-3);
|
||||
|
||||
int dx = pina->getX() - pind->getX();
|
||||
int dy = pina->getY() - pinc->getY();
|
||||
|
||||
int targetcx = MathUtils::round(pinc->getX() - ratio * dx);
|
||||
int targetcy = MathUtils::round(pinc->getY() - ratio * dy);
|
||||
int targetax = MathUtils::round(pina->getX() + ratio * dx);
|
||||
int targetay = MathUtils::round(pina->getY() + ratio * dy);
|
||||
|
||||
dx = pinb->getX() - pind->getX();
|
||||
dy = pinb->getY() - pind->getY();
|
||||
|
||||
int targetdx = MathUtils::round(pind->getX() - ratio * dx);
|
||||
int targetdy = MathUtils::round(pind->getY() - ratio * dy);
|
||||
int targetbx = MathUtils::round(pinb->getX() + ratio * dx);
|
||||
int targetby = MathUtils::round(pinb->getY() + ratio * dy);
|
||||
|
||||
if (!isValid(targetax, targetay) ||
|
||||
!isValid(targetbx, targetby) ||
|
||||
!isValid(targetcx, targetcy) ||
|
||||
!isValid(targetdx, targetdy)) {
|
||||
throw ReaderException("bullseye extends over image bounds");
|
||||
}
|
||||
|
||||
std::vector<Ref<Point> > returnValue;
|
||||
returnValue.push_back(Ref<Point>(new Point(targetax, targetay)));
|
||||
returnValue.push_back(Ref<Point>(new Point(targetbx, targetby)));
|
||||
returnValue.push_back(Ref<Point>(new Point(targetcx, targetcy)));
|
||||
returnValue.push_back(Ref<Point>(new Point(targetdx, targetdy)));
|
||||
|
||||
return returnValue;
|
||||
|
||||
}
|
||||
|
||||
Ref<Point> Detector::getMatrixCenter() {
|
||||
Ref<ResultPoint> pointA, pointB, pointC, pointD;
|
||||
try {
|
||||
|
||||
std::vector<Ref<ResultPoint> > cornerPoints = WhiteRectangleDetector(image_).detect();
|
||||
pointA = cornerPoints[0];
|
||||
pointB = cornerPoints[1];
|
||||
pointC = cornerPoints[2];
|
||||
pointD = cornerPoints[3];
|
||||
|
||||
} catch (NotFoundException const& e) {
|
||||
(void)e;
|
||||
|
||||
int cx = image_->getWidth() / 2;
|
||||
int cy = image_->getHeight() / 2;
|
||||
|
||||
pointA = getFirstDifferent(Ref<Point>(new Point(cx+7, cy-7)), false, 1, -1)->toResultPoint();
|
||||
pointB = getFirstDifferent(Ref<Point>(new Point(cx+7, cy+7)), false, 1, 1)->toResultPoint();
|
||||
pointC = getFirstDifferent(Ref<Point>(new Point(cx-7, cy+7)), false, -1, -1)->toResultPoint();
|
||||
pointD = getFirstDifferent(Ref<Point>(new Point(cx-7, cy-7)), false, -1, -1)->toResultPoint();
|
||||
|
||||
}
|
||||
|
||||
int cx = MathUtils::round((pointA->getX() + pointD->getX() + pointB->getX() + pointC->getX()) / 4.0f);
|
||||
int cy = MathUtils::round((pointA->getY() + pointD->getY() + pointB->getY() + pointC->getY()) / 4.0f);
|
||||
|
||||
try {
|
||||
|
||||
std::vector<Ref<ResultPoint> > cornerPoints = WhiteRectangleDetector(image_, 15, cx, cy).detect();
|
||||
pointA = cornerPoints[0];
|
||||
pointB = cornerPoints[1];
|
||||
pointC = cornerPoints[2];
|
||||
pointD = cornerPoints[3];
|
||||
|
||||
} catch (NotFoundException const& e) {
|
||||
(void)e;
|
||||
|
||||
pointA = getFirstDifferent(Ref<Point>(new Point(cx+7, cy-7)), false, 1, -1)->toResultPoint();
|
||||
pointB = getFirstDifferent(Ref<Point>(new Point(cx+7, cy+7)), false, 1, 1)->toResultPoint();
|
||||
pointC = getFirstDifferent(Ref<Point>(new Point(cx-7, cy+7)), false, -1, 1)->toResultPoint();
|
||||
pointD = getFirstDifferent(Ref<Point>(new Point(cx-7, cy-7)), false, -1, -1)->toResultPoint();
|
||||
|
||||
}
|
||||
|
||||
cx = MathUtils::round((pointA->getX() + pointD->getX() + pointB->getX() + pointC->getX()) / 4.0f);
|
||||
cy = MathUtils::round((pointA->getY() + pointD->getY() + pointB->getY() + pointC->getY()) / 4.0f);
|
||||
|
||||
return Ref<Point>(new Point(cx, cy));
|
||||
|
||||
}
|
||||
|
||||
Ref<BitMatrix> Detector::sampleGrid(Ref<zxing::BitMatrix> image,
|
||||
Ref<zxing::ResultPoint> topLeft,
|
||||
Ref<zxing::ResultPoint> bottomLeft,
|
||||
Ref<zxing::ResultPoint> bottomRight,
|
||||
Ref<zxing::ResultPoint> topRight) {
|
||||
int dimension;
|
||||
if (compact_) {
|
||||
dimension = 4 * nbLayers_+11;
|
||||
} else {
|
||||
if (nbLayers_ <= 4) {
|
||||
dimension = 4 * nbLayers_ + 15;
|
||||
} else {
|
||||
dimension = 4 * nbLayers_ + 2 * ((nbLayers_-4)/8 + 1) + 15;
|
||||
}
|
||||
}
|
||||
|
||||
GridSampler sampler = GridSampler::getInstance();
|
||||
|
||||
return sampler.sampleGrid(image,
|
||||
dimension,
|
||||
0.5f,
|
||||
0.5f,
|
||||
dimension - 0.5f,
|
||||
0.5f,
|
||||
dimension - 0.5f,
|
||||
dimension - 0.5f,
|
||||
0.5f,
|
||||
dimension - 0.5f,
|
||||
topLeft->getX(),
|
||||
topLeft->getY(),
|
||||
topRight->getX(),
|
||||
topRight->getY(),
|
||||
bottomRight->getX(),
|
||||
bottomRight->getY(),
|
||||
bottomLeft->getX(),
|
||||
bottomLeft->getY());
|
||||
}
|
||||
|
||||
void Detector::getParameters(Ref<zxing::BitArray> parameterData) {
|
||||
nbLayers_ = 0;
|
||||
nbDataBlocks_ = 0;
|
||||
|
||||
int nbBitsForNbLayers;
|
||||
int nbBitsForNbDatablocks;
|
||||
|
||||
if (compact_) {
|
||||
nbBitsForNbLayers = 2;
|
||||
nbBitsForNbDatablocks = 6;
|
||||
} else {
|
||||
nbBitsForNbLayers = 5;
|
||||
nbBitsForNbDatablocks = 11;
|
||||
}
|
||||
|
||||
for (int i = 0; i < nbBitsForNbLayers; i++) {
|
||||
nbLayers_ <<= 1;
|
||||
if (parameterData->get(i)) {
|
||||
nbLayers_++;
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = nbBitsForNbLayers; i < nbBitsForNbLayers + nbBitsForNbDatablocks; i++) {
|
||||
nbDataBlocks_ <<= 1;
|
||||
if (parameterData->get(i)) {
|
||||
nbDataBlocks_++;
|
||||
}
|
||||
}
|
||||
|
||||
nbLayers_++;
|
||||
nbDataBlocks_++;
|
||||
}
|
||||
|
||||
Ref<BitArray> Detector::sampleLine(Ref<zxing::aztec::Point> p1, Ref<zxing::aztec::Point> p2, int size) {
|
||||
Ref<BitArray> res(new BitArray(size));
|
||||
|
||||
float d = distance(p1, p2);
|
||||
float moduleSize = d / (size-1);
|
||||
float dx = moduleSize * float(p2->getX() - p1->getX())/d;
|
||||
float dy = moduleSize * float(p2->getY() - p1->getY())/d;
|
||||
|
||||
float px = float(p1->getX());
|
||||
float py = float(p1->getY());
|
||||
|
||||
for (int i = 0; i < size; i++) {
|
||||
if (image_->get(MathUtils::round(px), MathUtils::round(py))) res->set(i);
|
||||
px+=dx;
|
||||
py+=dy;
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
bool Detector::isWhiteOrBlackRectangle(Ref<zxing::aztec::Point> p1,
|
||||
Ref<zxing::aztec::Point> p2,
|
||||
Ref<zxing::aztec::Point> p3,
|
||||
Ref<zxing::aztec::Point> p4) {
|
||||
int corr = 3;
|
||||
|
||||
p1 = new Point(p1->getX() - corr, p1->getY() + corr);
|
||||
p2 = new Point(p2->getX() - corr, p2->getY() - corr);
|
||||
p3 = new Point(p3->getX() + corr, p3->getY() - corr);
|
||||
p4 = new Point(p4->getX() + corr, p4->getY() + corr);
|
||||
|
||||
int cInit = getColor(p4, p1);
|
||||
|
||||
if (cInit == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
int c = getColor(p1, p2);
|
||||
|
||||
if (c != cInit) {
|
||||
return false;
|
||||
}
|
||||
|
||||
c = getColor(p2, p3);
|
||||
|
||||
if (c != cInit) {
|
||||
return false;
|
||||
}
|
||||
|
||||
c = getColor(p3, p4);
|
||||
|
||||
if (c != cInit) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
int Detector::getColor(Ref<zxing::aztec::Point> p1, Ref<zxing::aztec::Point> p2) {
|
||||
float d = distance(p1, p2);
|
||||
|
||||
float dx = (p2->getX() - p1->getX()) / d;
|
||||
float dy = (p2->getY() - p1->getY()) / d;
|
||||
|
||||
int error = 0;
|
||||
|
||||
float px = float(p1->getX());
|
||||
float py = float(p1->getY());
|
||||
|
||||
bool colorModel = image_->get(p1->getX(), p1->getY());
|
||||
|
||||
for (int i = 0; i < d; i++) {
|
||||
px += dx;
|
||||
py += dy;
|
||||
if (image_->get(MathUtils::round(px), MathUtils::round(py)) != colorModel) {
|
||||
error ++;
|
||||
}
|
||||
}
|
||||
|
||||
float errRatio = (float)error/d;
|
||||
|
||||
|
||||
if (errRatio > 0.1f && errRatio < 0.9f) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return (errRatio <= 0.1) == colorModel ? 1 : -1;
|
||||
}
|
||||
|
||||
Ref<Point> Detector::getFirstDifferent(Ref<zxing::aztec::Point> init, bool color, int dx, int dy) {
|
||||
int x = init->getX() + dx;
|
||||
int y = init->getY() + dy;
|
||||
|
||||
while (isValid(x, y) && image_->get(x, y) == color) {
|
||||
x += dx;
|
||||
y += dy;
|
||||
}
|
||||
|
||||
x -= dx;
|
||||
y -= dy;
|
||||
|
||||
while (isValid(x, y) && image_->get(x, y) == color) {
|
||||
x += dx;
|
||||
}
|
||||
|
||||
x -= dx;
|
||||
|
||||
while (isValid(x, y) && image_->get(x, y) == color) {
|
||||
y += dy;
|
||||
}
|
||||
|
||||
y -= dy;
|
||||
|
||||
return Ref<Point>(new Point(x, y));
|
||||
}
|
||||
|
||||
bool Detector::isValid(int x, int y) {
|
||||
return x >= 0 && x < (int)image_->getWidth() && y > 0 && y < (int)image_->getHeight();
|
||||
}
|
||||
|
||||
float Detector::distance(Ref<zxing::aztec::Point> a, Ref<zxing::aztec::Point> b) {
|
||||
return sqrtf((float)((a->getX() - b->getX()) * (a->getX() - b->getX()) + (a->getY() - b->getY()) * (a->getY() - b->getY())));
|
||||
}
|
|
@ -1,92 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
/*
|
||||
* Detector.h
|
||||
* zxing
|
||||
*
|
||||
* Created by Lukas Stabe on 08/02/2012.
|
||||
* Copyright 2012 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#ifndef __ZXING_AZTEC_DETECTOR_DETECTOR_H__
|
||||
#define __ZXING_AZTEC_DETECTOR_DETECTOR_H__
|
||||
|
||||
#include <vector>
|
||||
|
||||
#include <zxing/common/BitArray.h>
|
||||
#include <zxing/ResultPoint.h>
|
||||
#include <zxing/common/BitMatrix.h>
|
||||
#include <zxing/DecodeHints.h>
|
||||
#include <zxing/aztec/AztecDetectorResult.h>
|
||||
|
||||
namespace zxing {
|
||||
namespace aztec {
|
||||
|
||||
class Point : public Counted {
|
||||
private:
|
||||
const int x;
|
||||
const int y;
|
||||
|
||||
public:
|
||||
Ref<ResultPoint> toResultPoint() {
|
||||
return Ref<ResultPoint>(new ResultPoint(float(x), float(y)));
|
||||
}
|
||||
|
||||
Point(int ax, int ay) : x(ax), y(ay) {}
|
||||
|
||||
int getX() const { return x; }
|
||||
int getY() const { return y; }
|
||||
};
|
||||
|
||||
class Detector : public Counted {
|
||||
|
||||
private:
|
||||
Ref<BitMatrix> image_;
|
||||
|
||||
bool compact_;
|
||||
int nbLayers_;
|
||||
int nbDataBlocks_;
|
||||
int nbCenterLayers_;
|
||||
int shift_;
|
||||
|
||||
void extractParameters(std::vector<Ref<Point> > bullEyeCornerPoints);
|
||||
ArrayRef< Ref<ResultPoint> > getMatrixCornerPoints(std::vector<Ref<Point> > bullEyeCornerPoints);
|
||||
static void correctParameterData(Ref<BitArray> parameterData, bool compact);
|
||||
std::vector<Ref<Point> > getBullEyeCornerPoints(Ref<Point> pCenter);
|
||||
Ref<Point> getMatrixCenter();
|
||||
Ref<BitMatrix> sampleGrid(Ref<BitMatrix> image,
|
||||
Ref<ResultPoint> topLeft,
|
||||
Ref<ResultPoint> bottomLeft,
|
||||
Ref<ResultPoint> bottomRight,
|
||||
Ref<ResultPoint> topRight);
|
||||
void getParameters(Ref<BitArray> parameterData);
|
||||
Ref<BitArray> sampleLine(Ref<Point> p1, Ref<Point> p2, int size);
|
||||
bool isWhiteOrBlackRectangle(Ref<Point> p1,
|
||||
Ref<Point> p2,
|
||||
Ref<Point> p3,
|
||||
Ref<Point> p4);
|
||||
int getColor(Ref<Point> p1, Ref<Point> p2);
|
||||
Ref<Point> getFirstDifferent(Ref<Point> init, bool color, int dx, int dy);
|
||||
bool isValid(int x, int y);
|
||||
static float distance(Ref<Point> a, Ref<Point> b);
|
||||
|
||||
public:
|
||||
Detector(Ref<BitMatrix> image);
|
||||
Ref<AztecDetectorResult> detect();
|
||||
};
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
|
@ -1,170 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
#ifndef __ARRAY_H__
|
||||
#define __ARRAY_H__
|
||||
|
||||
/*
|
||||
* Array.h
|
||||
* zxing
|
||||
*
|
||||
* Copyright 2010 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <vector>
|
||||
|
||||
#include <zxing/common/Counted.h>
|
||||
|
||||
namespace zxing {
|
||||
|
||||
template<typename T> class Array : public Counted {
|
||||
protected:
|
||||
public:
|
||||
std::vector<T> values_;
|
||||
Array() {}
|
||||
Array(int n) :
|
||||
Counted(), values_(n, T()) {
|
||||
}
|
||||
Array(T const* ts, int n) :
|
||||
Counted(), values_(ts, ts+n) {
|
||||
}
|
||||
Array(T const* ts, T const* te) :
|
||||
Counted(), values_(ts, te) {
|
||||
}
|
||||
Array(T v, int n) :
|
||||
Counted(), values_(n, v) {
|
||||
}
|
||||
Array(std::vector<T> &v) :
|
||||
Counted(), values_(v) {
|
||||
}
|
||||
Array(Array<T> &other) :
|
||||
Counted(), values_(other.values_) {
|
||||
}
|
||||
Array(Array<T> *other) :
|
||||
Counted(), values_(other->values_) {
|
||||
}
|
||||
virtual ~Array() {
|
||||
}
|
||||
Array<T>& operator=(const Array<T> &other) {
|
||||
values_ = other.values_;
|
||||
return *this;
|
||||
}
|
||||
Array<T>& operator=(const std::vector<T> &array) {
|
||||
values_ = array;
|
||||
return *this;
|
||||
}
|
||||
T const& operator[](int i) const {
|
||||
return values_[i];
|
||||
}
|
||||
T& operator[](int i) {
|
||||
return values_[i];
|
||||
}
|
||||
int size() const {
|
||||
return values_.size();
|
||||
}
|
||||
bool empty() const {
|
||||
return values_.size() == 0;
|
||||
}
|
||||
std::vector<T> const& values() const {
|
||||
return values_;
|
||||
}
|
||||
std::vector<T>& values() {
|
||||
return values_;
|
||||
}
|
||||
};
|
||||
|
||||
template<typename T> class ArrayRef : public Counted {
|
||||
private:
|
||||
public:
|
||||
Array<T> *array_;
|
||||
ArrayRef() :
|
||||
array_(0) {
|
||||
}
|
||||
explicit ArrayRef(int n) :
|
||||
array_(0) {
|
||||
reset(new Array<T> (n));
|
||||
}
|
||||
ArrayRef(T *ts, int n) :
|
||||
array_(0) {
|
||||
reset(new Array<T> (ts, n));
|
||||
}
|
||||
ArrayRef(Array<T> *a) :
|
||||
array_(0) {
|
||||
reset(a);
|
||||
}
|
||||
ArrayRef(const ArrayRef &other) :
|
||||
Counted(), array_(0) {
|
||||
reset(other.array_);
|
||||
}
|
||||
|
||||
template<class Y>
|
||||
ArrayRef(const ArrayRef<Y> &other) :
|
||||
array_(0) {
|
||||
reset(static_cast<const Array<T> *>(other.array_));
|
||||
}
|
||||
|
||||
~ArrayRef() {
|
||||
if (array_) {
|
||||
array_->release();
|
||||
}
|
||||
array_ = 0;
|
||||
}
|
||||
|
||||
T const& operator[](int i) const {
|
||||
return (*array_)[i];
|
||||
}
|
||||
|
||||
T& operator[](int i) {
|
||||
return (*array_)[i];
|
||||
}
|
||||
|
||||
void reset(Array<T> *a) {
|
||||
if (a) {
|
||||
a->retain();
|
||||
}
|
||||
if (array_) {
|
||||
array_->release();
|
||||
}
|
||||
array_ = a;
|
||||
}
|
||||
void reset(const ArrayRef<T> &other) {
|
||||
reset(other.array_);
|
||||
}
|
||||
ArrayRef<T>& operator=(const ArrayRef<T> &other) {
|
||||
reset(other);
|
||||
return *this;
|
||||
}
|
||||
ArrayRef<T>& operator=(Array<T> *a) {
|
||||
reset(a);
|
||||
return *this;
|
||||
}
|
||||
|
||||
Array<T>& operator*() const {
|
||||
return *array_;
|
||||
}
|
||||
|
||||
Array<T>* operator->() const {
|
||||
return array_;
|
||||
}
|
||||
|
||||
operator bool () const {
|
||||
return array_ != 0;
|
||||
}
|
||||
bool operator ! () const {
|
||||
return array_ == 0;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace zxing
|
||||
|
||||
#endif // __ARRAY_H__
|
|
@ -1,155 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
/*
|
||||
* Copyright 2010 ZXing authors. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/common/BitArray.h>
|
||||
|
||||
using std::vector;
|
||||
using zxing::BitArray;
|
||||
|
||||
// VC++
|
||||
using zxing::Ref;
|
||||
|
||||
int BitArray::makeArraySize(int size) {
|
||||
return (size + bitsPerWord-1) >> logBits;
|
||||
}
|
||||
|
||||
BitArray::BitArray(int size_)
|
||||
: size(size_), bits(makeArraySize(size)) {}
|
||||
|
||||
BitArray::~BitArray() {
|
||||
}
|
||||
|
||||
int BitArray::getSize() const {
|
||||
return size;
|
||||
}
|
||||
|
||||
void BitArray::setBulk(int i, int newBits) {
|
||||
bits[i >> logBits] = newBits;
|
||||
}
|
||||
|
||||
void BitArray::clear() {
|
||||
int max = bits->size();
|
||||
for (int i = 0; i < max; i++) {
|
||||
bits[i] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
bool BitArray::isRange(int start, int end, bool value) {
|
||||
if (end < start) {
|
||||
throw IllegalArgumentException();
|
||||
}
|
||||
if (end == start) {
|
||||
return true; // empty range matches
|
||||
}
|
||||
end--; // will be easier to treat this as the last actually set bit -- inclusive
|
||||
int firstInt = start >> logBits;
|
||||
int lastInt = end >> logBits;
|
||||
for (int i = firstInt; i <= lastInt; i++) {
|
||||
int firstBit = i > firstInt ? 0 : start & bitsMask;
|
||||
int lastBit = i < lastInt ? (bitsPerWord-1) : end & bitsMask;
|
||||
int mask;
|
||||
if (firstBit == 0 && lastBit == (bitsPerWord-1)) {
|
||||
mask = -1;
|
||||
} else {
|
||||
mask = 0;
|
||||
for (int j = firstBit; j <= lastBit; j++) {
|
||||
mask |= 1 << j;
|
||||
}
|
||||
}
|
||||
|
||||
// Return false if we're looking for 1s and the masked bits[i] isn't all 1s (that is,
|
||||
// equals the mask, or we're looking for 0s and the masked portion is not all 0s
|
||||
if ((bits[i] & mask) != (value ? mask : 0)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
vector<int>& BitArray::getBitArray() {
|
||||
return bits->values();
|
||||
}
|
||||
|
||||
void BitArray::reverse() {
|
||||
ArrayRef<int> newBits(bits->size());
|
||||
int size = this->size;
|
||||
for (int i = 0; i < size; i++) {
|
||||
if (get(size - i - 1)) {
|
||||
newBits[i >> logBits] |= 1 << (i & bitsMask);
|
||||
}
|
||||
}
|
||||
bits = newBits;
|
||||
}
|
||||
|
||||
BitArray::Reverse::Reverse(Ref<BitArray> array_) : array(array_) {
|
||||
array->reverse();
|
||||
}
|
||||
|
||||
BitArray::Reverse::~Reverse() {
|
||||
array->reverse();
|
||||
}
|
||||
|
||||
namespace {
|
||||
// N.B.: This only works for 32 bit ints ...
|
||||
int numberOfTrailingZeros(int i) {
|
||||
// HD, Figure 5-14
|
||||
int y;
|
||||
if (i == 0) return 32;
|
||||
int n = 31;
|
||||
y = i <<16; if (y != 0) { n = n -16; i = y; }
|
||||
y = i << 8; if (y != 0) { n = n - 8; i = y; }
|
||||
y = i << 4; if (y != 0) { n = n - 4; i = y; }
|
||||
y = i << 2; if (y != 0) { n = n - 2; i = y; }
|
||||
return n - (((unsigned int)(i << 1)) >> 31);
|
||||
}
|
||||
}
|
||||
|
||||
int BitArray::getNextSet(int from) {
|
||||
if (from >= size) {
|
||||
return size;
|
||||
}
|
||||
int bitsOffset = from >> logBits;
|
||||
int currentBits = bits[bitsOffset];
|
||||
// mask off lesser bits first
|
||||
currentBits &= ~((1 << (from & bitsMask)) - 1);
|
||||
while (currentBits == 0) {
|
||||
if (++bitsOffset == (int)bits->size()) {
|
||||
return size;
|
||||
}
|
||||
currentBits = bits[bitsOffset];
|
||||
}
|
||||
int result = (bitsOffset << logBits) + numberOfTrailingZeros(currentBits);
|
||||
return result > size ? size : result;
|
||||
}
|
||||
|
||||
int BitArray::getNextUnset(int from) {
|
||||
if (from >= size) {
|
||||
return size;
|
||||
}
|
||||
int bitsOffset = from >> logBits;
|
||||
int currentBits = ~bits[bitsOffset];
|
||||
// mask off lesser bits first
|
||||
currentBits &= ~((1 << (from & bitsMask)) - 1);
|
||||
while (currentBits == 0) {
|
||||
if (++bitsOffset == (int)bits->size()) {
|
||||
return size;
|
||||
}
|
||||
currentBits = ~bits[bitsOffset];
|
||||
}
|
||||
int result = (bitsOffset << logBits) + numberOfTrailingZeros(currentBits);
|
||||
return result > size ? size : result;
|
||||
}
|
|
@ -1,81 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
#ifndef __BIT_ARRAY_H__
|
||||
#define __BIT_ARRAY_H__
|
||||
|
||||
/*
|
||||
* Copyright 2010 ZXing authors. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/ZXing.h>
|
||||
#include <zxing/common/Counted.h>
|
||||
#include <zxing/common/IllegalArgumentException.h>
|
||||
#include <zxing/common/Array.h>
|
||||
#include <vector>
|
||||
#include <limits>
|
||||
#include <iostream>
|
||||
|
||||
namespace zxing {
|
||||
|
||||
class BitArray : public Counted {
|
||||
public:
|
||||
static const int bitsPerWord = std::numeric_limits<unsigned int>::digits;
|
||||
|
||||
private:
|
||||
int size;
|
||||
ArrayRef<int> bits;
|
||||
static const int logBits = ZX_LOG_DIGITS(bitsPerWord);
|
||||
static const int bitsMask = (1 << logBits) - 1;
|
||||
|
||||
public:
|
||||
BitArray(int size);
|
||||
~BitArray();
|
||||
int getSize() const;
|
||||
|
||||
bool get(int i) const {
|
||||
return (bits[i >> logBits] & (1 << (i & bitsMask))) != 0;
|
||||
}
|
||||
|
||||
void set(int i) {
|
||||
bits[i >> logBits] |= 1 << (i & bitsMask);
|
||||
}
|
||||
|
||||
int getNextSet(int from);
|
||||
int getNextUnset(int from);
|
||||
|
||||
void setBulk(int i, int newBits);
|
||||
void setRange(int start, int end);
|
||||
void clear();
|
||||
bool isRange(int start, int end, bool value);
|
||||
std::vector<int>& getBitArray();
|
||||
|
||||
void reverse();
|
||||
|
||||
class Reverse {
|
||||
private:
|
||||
Ref<BitArray> array;
|
||||
public:
|
||||
Reverse(Ref<BitArray> array);
|
||||
~Reverse();
|
||||
};
|
||||
|
||||
private:
|
||||
static int makeArraySize(int size);
|
||||
};
|
||||
|
||||
std::ostream& operator << (std::ostream&, BitArray const&);
|
||||
|
||||
}
|
||||
|
||||
#endif // __BIT_ARRAY_H__
|
|
@ -1,31 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
/*
|
||||
* Copyright 2010 ZXing authors. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/common/BitArray.h>
|
||||
|
||||
using zxing::BitArray;
|
||||
using std::ostream;
|
||||
|
||||
ostream& zxing::operator << (ostream& os, BitArray const& ba) {
|
||||
for (int i = 0, size = ba.getSize(); i < size; i++) {
|
||||
if ((i & 0x07) == 0) {
|
||||
os << ' ';
|
||||
}
|
||||
os << (ba.get(i) ? 'X' : '.');
|
||||
}
|
||||
return os;
|
||||
}
|
|
@ -1,143 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
/*
|
||||
* Copyright 2010 ZXing authors. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/common/BitMatrix.h>
|
||||
#include <zxing/common/IllegalArgumentException.h>
|
||||
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
|
||||
using std::ostream;
|
||||
using std::ostringstream;
|
||||
|
||||
using zxing::BitMatrix;
|
||||
using zxing::BitArray;
|
||||
using zxing::ArrayRef;
|
||||
using zxing::Ref;
|
||||
|
||||
void BitMatrix::init(int width, int height) {
|
||||
if (width < 1 || height < 1) {
|
||||
throw IllegalArgumentException("Both dimensions must be greater than 0");
|
||||
}
|
||||
this->width = width;
|
||||
this->height = height;
|
||||
this->rowSize = (width + bitsPerWord - 1) >> logBits;
|
||||
bits = ArrayRef<int>(rowSize * height);
|
||||
}
|
||||
|
||||
BitMatrix::BitMatrix(int dimension) {
|
||||
init(dimension, dimension);
|
||||
}
|
||||
|
||||
BitMatrix::BitMatrix(int width, int height) {
|
||||
init(width, height);
|
||||
}
|
||||
|
||||
BitMatrix::~BitMatrix() {}
|
||||
|
||||
void BitMatrix::flip(int x, int y) {
|
||||
int offset = y * rowSize + (x >> logBits);
|
||||
bits[offset] ^= 1 << (x & bitsMask);
|
||||
}
|
||||
|
||||
void BitMatrix::setRegion(int left, int top, int width, int height) {
|
||||
if (top < 0 || left < 0) {
|
||||
throw IllegalArgumentException("Left and top must be nonnegative");
|
||||
}
|
||||
if (height < 1 || width < 1) {
|
||||
throw IllegalArgumentException("Height and width must be at least 1");
|
||||
}
|
||||
int right = left + width;
|
||||
int bottom = top + height;
|
||||
if (bottom > this->height || right > this->width) {
|
||||
throw IllegalArgumentException("The region must fit inside the matrix");
|
||||
}
|
||||
for (int y = top; y < bottom; y++) {
|
||||
int offset = y * rowSize;
|
||||
for (int x = left; x < right; x++) {
|
||||
bits[offset + (x >> logBits)] |= 1 << (x & bitsMask);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ref<BitArray> BitMatrix::getRow(int y, Ref<BitArray> row) {
|
||||
if (row.empty() || row->getSize() < width) {
|
||||
row = new BitArray(width);
|
||||
}
|
||||
int offset = y * rowSize;
|
||||
for (int x = 0; x < rowSize; x++) {
|
||||
row->setBulk(x << logBits, bits[offset + x]);
|
||||
}
|
||||
return row;
|
||||
}
|
||||
|
||||
int BitMatrix::getWidth() const {
|
||||
return width;
|
||||
}
|
||||
|
||||
int BitMatrix::getHeight() const {
|
||||
return height;
|
||||
}
|
||||
|
||||
ArrayRef<int> BitMatrix::getTopLeftOnBit() const {
|
||||
int bitsOffset = 0;
|
||||
while (bitsOffset < bits->size() && bits[bitsOffset] == 0) {
|
||||
bitsOffset++;
|
||||
}
|
||||
if (bitsOffset == bits->size()) {
|
||||
return ArrayRef<int>();
|
||||
}
|
||||
int y = bitsOffset / rowSize;
|
||||
int x = (bitsOffset % rowSize) << 5;
|
||||
|
||||
int theBits = bits[bitsOffset];
|
||||
int bit = 0;
|
||||
while ((theBits << (31-bit)) == 0) {
|
||||
bit++;
|
||||
}
|
||||
x += bit;
|
||||
ArrayRef<int> res (2);
|
||||
res[0]=x;
|
||||
res[1]=y;
|
||||
return res;
|
||||
}
|
||||
|
||||
ArrayRef<int> BitMatrix::getBottomRightOnBit() const {
|
||||
int bitsOffset = bits->size() - 1;
|
||||
while (bitsOffset >= 0 && bits[bitsOffset] == 0) {
|
||||
bitsOffset--;
|
||||
}
|
||||
if (bitsOffset < 0) {
|
||||
return ArrayRef<int>();
|
||||
}
|
||||
|
||||
int y = bitsOffset / rowSize;
|
||||
int x = (bitsOffset % rowSize) << 5;
|
||||
|
||||
int theBits = bits[bitsOffset];
|
||||
int bit = 31;
|
||||
while ((theBits >> bit) == 0) {
|
||||
bit--;
|
||||
}
|
||||
x += bit;
|
||||
|
||||
ArrayRef<int> res (2);
|
||||
res[0]=x;
|
||||
res[1]=y;
|
||||
return res;
|
||||
}
|
|
@ -1,91 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
#ifndef __BIT_MATRIX_H__
|
||||
#define __BIT_MATRIX_H__
|
||||
|
||||
/*
|
||||
* BitMatrix.h
|
||||
* zxing
|
||||
*
|
||||
* Copyright 2010 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/common/Counted.h>
|
||||
#include <zxing/common/BitArray.h>
|
||||
#include <zxing/common/Array.h>
|
||||
#include <limits>
|
||||
|
||||
namespace zxing {
|
||||
|
||||
class BitMatrix : public Counted {
|
||||
public:
|
||||
static const int bitsPerWord = std::numeric_limits<unsigned int>::digits;
|
||||
|
||||
private:
|
||||
int width;
|
||||
int height;
|
||||
int rowSize;
|
||||
ArrayRef<int> bits;
|
||||
|
||||
#define ZX_LOG_DIGITS(digits) \
|
||||
((digits == 8) ? 3 : \
|
||||
((digits == 16) ? 4 : \
|
||||
((digits == 32) ? 5 : \
|
||||
((digits == 64) ? 6 : \
|
||||
((digits == 128) ? 7 : \
|
||||
(-1))))))
|
||||
|
||||
static const int logBits = ZX_LOG_DIGITS(bitsPerWord);
|
||||
static const int bitsMask = (1 << logBits) - 1;
|
||||
|
||||
public:
|
||||
BitMatrix(int dimension);
|
||||
BitMatrix(int width, int height);
|
||||
|
||||
~BitMatrix();
|
||||
|
||||
bool get(int x, int y) const {
|
||||
int offset = y * rowSize + (x >> logBits);
|
||||
return ((((unsigned)bits[offset]) >> (x & bitsMask)) & 1) != 0;
|
||||
}
|
||||
|
||||
void set(int x, int y) {
|
||||
int offset = y * rowSize + (x >> logBits);
|
||||
bits[offset] |= 1 << (x & bitsMask);
|
||||
}
|
||||
|
||||
void flip(int x, int y);
|
||||
void clear();
|
||||
void setRegion(int left, int top, int width, int height);
|
||||
Ref<BitArray> getRow(int y, Ref<BitArray> row);
|
||||
|
||||
int getWidth() const;
|
||||
int getHeight() const;
|
||||
|
||||
ArrayRef<int> getTopLeftOnBit() const;
|
||||
ArrayRef<int> getBottomRightOnBit() const;
|
||||
|
||||
friend std::ostream& operator<<(std::ostream &out, const BitMatrix &bm);
|
||||
const char *description();
|
||||
|
||||
private:
|
||||
inline void init(int, int);
|
||||
|
||||
BitMatrix(const BitMatrix&);
|
||||
BitMatrix& operator =(const BitMatrix&);
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif // __BIT_MATRIX_H__
|
|
@ -1,76 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
/*
|
||||
* BitSource.cpp
|
||||
* zxing
|
||||
*
|
||||
* Created by Christian Brunschen on 09/05/2008.
|
||||
* Copyright 2008 Google UK. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/common/BitSource.h>
|
||||
#include <sstream>
|
||||
#include <zxing/common/IllegalArgumentException.h>
|
||||
|
||||
namespace zxing {
|
||||
|
||||
int BitSource::readBits(int numBits) {
|
||||
if (numBits < 0 || numBits > 32 || numBits > available()) {
|
||||
std::ostringstream oss;
|
||||
oss << numBits;
|
||||
throw IllegalArgumentException(oss.str().c_str());
|
||||
}
|
||||
|
||||
int result = 0;
|
||||
|
||||
// First, read remainder from current byte
|
||||
if (bitOffset_ > 0) {
|
||||
int bitsLeft = 8 - bitOffset_;
|
||||
int toRead = numBits < bitsLeft ? numBits : bitsLeft;
|
||||
int bitsToNotRead = bitsLeft - toRead;
|
||||
int mask = (0xFF >> (8 - toRead)) << bitsToNotRead;
|
||||
result = (bytes_[byteOffset_] & mask) >> bitsToNotRead;
|
||||
numBits -= toRead;
|
||||
bitOffset_ += toRead;
|
||||
if (bitOffset_ == 8) {
|
||||
bitOffset_ = 0;
|
||||
byteOffset_++;
|
||||
}
|
||||
}
|
||||
|
||||
// Next read whole bytes
|
||||
if (numBits > 0) {
|
||||
while (numBits >= 8) {
|
||||
result = (result << 8) | (bytes_[byteOffset_] & 0xFF);
|
||||
byteOffset_++;
|
||||
numBits -= 8;
|
||||
}
|
||||
|
||||
|
||||
// Finally read a partial byte
|
||||
if (numBits > 0) {
|
||||
int bitsToNotRead = 8 - numBits;
|
||||
int mask = (0xFF >> bitsToNotRead) << bitsToNotRead;
|
||||
result = (result << numBits) | ((bytes_[byteOffset_] & mask) >> bitsToNotRead);
|
||||
bitOffset_ += numBits;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
int BitSource::available() {
|
||||
return 8 * (bytes_->size() - byteOffset_) - bitOffset_;
|
||||
}
|
||||
}
|
|
@ -1,74 +0,0 @@
|
|||
#ifndef __BIT_SOURCE_H__
|
||||
#define __BIT_SOURCE_H__
|
||||
|
||||
/*
|
||||
* BitSource.h
|
||||
* zxing
|
||||
*
|
||||
* Copyright 2010 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/common/Array.h>
|
||||
|
||||
namespace zxing {
|
||||
/**
|
||||
* <p>This provides an easy abstraction to read bits at a time from a sequence of bytes, where the
|
||||
* number of bits read is not often a multiple of 8.</p>
|
||||
*
|
||||
* <p>This class is not thread-safe.</p>
|
||||
*
|
||||
* @author srowen@google.com (Sean Owen)
|
||||
* @author christian.brunschen@gmail.com (Christian Brunschen)
|
||||
*/
|
||||
class BitSource : public Counted {
|
||||
typedef char byte;
|
||||
private:
|
||||
ArrayRef<byte> bytes_;
|
||||
int byteOffset_;
|
||||
int bitOffset_;
|
||||
public:
|
||||
/**
|
||||
* @param bytes bytes from which this will read bits. Bits will be read from the first byte first.
|
||||
* Bits are read within a byte from most-significant to least-significant bit.
|
||||
*/
|
||||
BitSource(ArrayRef<byte> &bytes) :
|
||||
bytes_(bytes), byteOffset_(0), bitOffset_(0) {
|
||||
}
|
||||
|
||||
int getBitOffset() {
|
||||
return bitOffset_;
|
||||
}
|
||||
|
||||
int getByteOffset() {
|
||||
return byteOffset_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param numBits number of bits to read
|
||||
* @return int representing the bits read. The bits will appear as the least-significant
|
||||
* bits of the int
|
||||
* @throws IllegalArgumentException if numBits isn't in [1,32]
|
||||
*/
|
||||
int readBits(int numBits);
|
||||
|
||||
/**
|
||||
* @return number of bits that can be read successfully
|
||||
*/
|
||||
int available();
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif // __BIT_SOURCE_H__
|
|
@ -1,104 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
/*
|
||||
* Copyright 2008-2011 ZXing authors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/common/CharacterSetECI.h>
|
||||
#include <zxing/common/IllegalArgumentException.h>
|
||||
#include <zxing/FormatException.h>
|
||||
|
||||
using std::string;
|
||||
|
||||
using zxing::common::CharacterSetECI;
|
||||
using zxing::IllegalArgumentException;
|
||||
|
||||
std::map<int, CharacterSetECI*> CharacterSetECI::VALUE_TO_ECI;
|
||||
std::map<std::string, CharacterSetECI*> CharacterSetECI::NAME_TO_ECI;
|
||||
|
||||
const bool CharacterSetECI::inited = CharacterSetECI::init_tables();
|
||||
|
||||
#define ADD_CHARACTER_SET(VALUES, STRINGS) \
|
||||
{ static int values[] = {VALUES, -1}; \
|
||||
static char const* strings[] = {STRINGS, 0}; \
|
||||
addCharacterSet(values, strings); }
|
||||
|
||||
#define XC ,
|
||||
|
||||
bool CharacterSetECI::init_tables() {
|
||||
ADD_CHARACTER_SET(0 XC 2, "Cp437");
|
||||
ADD_CHARACTER_SET(1 XC 3, "ISO8859_1" XC "ISO-8859-1");
|
||||
ADD_CHARACTER_SET(4, "ISO8859_2" XC "ISO-8859-2");
|
||||
ADD_CHARACTER_SET(5, "ISO8859_3" XC "ISO-8859-3");
|
||||
ADD_CHARACTER_SET(6, "ISO8859_4" XC "ISO-8859-4");
|
||||
ADD_CHARACTER_SET(7, "ISO8859_5" XC "ISO-8859-5");
|
||||
ADD_CHARACTER_SET(8, "ISO8859_6" XC "ISO-8859-6");
|
||||
ADD_CHARACTER_SET(9, "ISO8859_7" XC "ISO-8859-7");
|
||||
ADD_CHARACTER_SET(10, "ISO8859_8" XC "ISO-8859-8");
|
||||
ADD_CHARACTER_SET(11, "ISO8859_9" XC "ISO-8859-9");
|
||||
ADD_CHARACTER_SET(12, "ISO8859_10" XC "ISO-8859-10");
|
||||
ADD_CHARACTER_SET(13, "ISO8859_11" XC "ISO-8859-11");
|
||||
ADD_CHARACTER_SET(15, "ISO8859_13" XC "ISO-8859-13");
|
||||
ADD_CHARACTER_SET(16, "ISO8859_14" XC "ISO-8859-14");
|
||||
ADD_CHARACTER_SET(17, "ISO8859_15" XC "ISO-8859-15");
|
||||
ADD_CHARACTER_SET(18, "ISO8859_16" XC "ISO-8859-16");
|
||||
ADD_CHARACTER_SET(20, "SJIS" XC "Shift_JIS");
|
||||
ADD_CHARACTER_SET(21, "Cp1250" XC "windows-1250");
|
||||
ADD_CHARACTER_SET(22, "Cp1251" XC "windows-1251");
|
||||
ADD_CHARACTER_SET(23, "Cp1252" XC "windows-1252");
|
||||
ADD_CHARACTER_SET(24, "Cp1256" XC "windows-1256");
|
||||
ADD_CHARACTER_SET(25, "UnicodeBigUnmarked" XC "UTF-16BE" XC "UnicodeBig");
|
||||
ADD_CHARACTER_SET(26, "UTF8" XC "UTF-8");
|
||||
ADD_CHARACTER_SET(27 XC 170, "ASCII" XC "US-ASCII");
|
||||
ADD_CHARACTER_SET(28, "Big5");
|
||||
ADD_CHARACTER_SET(29, "GB18030" XC "GB2312" XC "EUC_CN" XC "GBK");
|
||||
ADD_CHARACTER_SET(30, "EUC_KR" XC "EUC-KR");
|
||||
return true;
|
||||
}
|
||||
|
||||
#undef XC
|
||||
|
||||
CharacterSetECI::CharacterSetECI(int const* values,
|
||||
char const* const* names)
|
||||
: values_(values), names_(names) {
|
||||
for(int const* values = values_; *values != -1; values++) {
|
||||
VALUE_TO_ECI[*values] = this;
|
||||
}
|
||||
for(char const* const* names = names_; *names; names++) {
|
||||
NAME_TO_ECI[string(*names)] = this;
|
||||
}
|
||||
}
|
||||
|
||||
char const* CharacterSetECI::name() const {
|
||||
return names_[0];
|
||||
}
|
||||
|
||||
int CharacterSetECI::getValue() const {
|
||||
return values_[0];
|
||||
}
|
||||
|
||||
void CharacterSetECI::addCharacterSet(int const* values, char const* const* names) {
|
||||
new CharacterSetECI(values, names);
|
||||
}
|
||||
|
||||
CharacterSetECI* CharacterSetECI::getCharacterSetECIByValue(int value) {
|
||||
if (value < 0 || value >= 900) {
|
||||
throw FormatException();
|
||||
}
|
||||
return VALUE_TO_ECI[value];
|
||||
}
|
||||
|
||||
CharacterSetECI* CharacterSetECI::getCharacterSetECIByName(string const& name) {
|
||||
return NAME_TO_ECI[name];
|
||||
}
|
|
@ -1,53 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
|
||||
#ifndef __CHARACTERSET_ECI__
|
||||
#define __CHARACTERSET_ECI__
|
||||
|
||||
/*
|
||||
* Copyright 2008-2011 ZXing authors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <map>
|
||||
#include <zxing/DecodeHints.h>
|
||||
|
||||
namespace zxing {
|
||||
namespace common {
|
||||
|
||||
class CharacterSetECI {
|
||||
private:
|
||||
static std::map<int, CharacterSetECI*> VALUE_TO_ECI;
|
||||
static std::map<std::string, CharacterSetECI*> NAME_TO_ECI;
|
||||
static const bool inited;
|
||||
static bool init_tables();
|
||||
|
||||
int const* const values_;
|
||||
char const* const* const names_;
|
||||
|
||||
CharacterSetECI(int const* values, char const* const* names);
|
||||
|
||||
static void addCharacterSet(int const* value, char const* const* encodingNames);
|
||||
|
||||
public:
|
||||
char const* name() const;
|
||||
int getValue() const;
|
||||
|
||||
static CharacterSetECI* getCharacterSetECIByValue(int value);
|
||||
static CharacterSetECI* getCharacterSetECIByName(std::string const& name);
|
||||
};
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
|
@ -1,140 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
#ifndef __COUNTED_H__
|
||||
#define __COUNTED_H__
|
||||
|
||||
/*
|
||||
* Copyright 2010 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <iostream>
|
||||
|
||||
namespace zxing {
|
||||
|
||||
/* base class for reference-counted objects */
|
||||
class Counted {
|
||||
private:
|
||||
unsigned int count_;
|
||||
public:
|
||||
Counted() :
|
||||
count_(0) {
|
||||
}
|
||||
virtual ~Counted() {
|
||||
}
|
||||
Counted *retain() {
|
||||
count_++;
|
||||
return this;
|
||||
}
|
||||
void release() {
|
||||
count_--;
|
||||
if (count_ == 0) {
|
||||
count_ = 0xDEADF001;
|
||||
delete this;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* return the current count for denugging purposes or similar */
|
||||
int count() const {
|
||||
return count_;
|
||||
}
|
||||
};
|
||||
|
||||
/* counting reference to reference-counted objects */
|
||||
template<typename T> class Ref {
|
||||
private:
|
||||
public:
|
||||
T *object_;
|
||||
explicit Ref(T *o = 0) :
|
||||
object_(0) {
|
||||
reset(o);
|
||||
}
|
||||
Ref(const Ref &other) :
|
||||
object_(0) {
|
||||
reset(other.object_);
|
||||
}
|
||||
|
||||
template<class Y>
|
||||
Ref(const Ref<Y> &other) :
|
||||
object_(0) {
|
||||
reset(other.object_);
|
||||
}
|
||||
|
||||
~Ref() {
|
||||
if (object_) {
|
||||
object_->release();
|
||||
}
|
||||
}
|
||||
|
||||
void reset(T *o) {
|
||||
if (o) {
|
||||
o->retain();
|
||||
}
|
||||
if (object_ != 0) {
|
||||
object_->release();
|
||||
}
|
||||
object_ = o;
|
||||
}
|
||||
Ref& operator=(const Ref &other) {
|
||||
reset(other.object_);
|
||||
return *this;
|
||||
}
|
||||
template<class Y>
|
||||
Ref& operator=(const Ref<Y> &other) {
|
||||
reset(other.object_);
|
||||
return *this;
|
||||
}
|
||||
Ref& operator=(T* o) {
|
||||
reset(o);
|
||||
return *this;
|
||||
}
|
||||
template<class Y>
|
||||
Ref& operator=(Y* o) {
|
||||
reset(o);
|
||||
return *this;
|
||||
}
|
||||
|
||||
T& operator*() {
|
||||
return *object_;
|
||||
}
|
||||
T* operator->() const {
|
||||
return object_;
|
||||
}
|
||||
operator T*() const {
|
||||
return object_;
|
||||
}
|
||||
|
||||
bool operator==(const T* that) {
|
||||
return object_ == that;
|
||||
}
|
||||
bool operator==(const Ref &other) const {
|
||||
return object_ == other.object_ || *object_ == *(other.object_);
|
||||
}
|
||||
template<class Y>
|
||||
bool operator==(const Ref<Y> &other) const {
|
||||
return object_ == other.object_ || *object_ == *(other.object_);
|
||||
}
|
||||
|
||||
bool operator!=(const T* that) {
|
||||
return !(*this == that);
|
||||
}
|
||||
|
||||
bool empty() const {
|
||||
return object_ == 0;
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif // __COUNTED_H__
|
|
@ -1,46 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
/*
|
||||
* DecoderResult.cpp
|
||||
* zxing
|
||||
*
|
||||
* Created by Christian Brunschen on 20/05/2008.
|
||||
* Copyright 2008-2011 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/common/DecoderResult.h>
|
||||
|
||||
using namespace std;
|
||||
using namespace zxing;
|
||||
|
||||
DecoderResult::DecoderResult(ArrayRef<char> rawBytes,
|
||||
Ref<String> text,
|
||||
ArrayRef< ArrayRef<char> >& byteSegments,
|
||||
string const& ecLevel) :
|
||||
rawBytes_(rawBytes),
|
||||
text_(text),
|
||||
byteSegments_(byteSegments),
|
||||
ecLevel_(ecLevel) {}
|
||||
|
||||
DecoderResult::DecoderResult(ArrayRef<char> rawBytes,
|
||||
Ref<String> text)
|
||||
: rawBytes_(rawBytes), text_(text) {}
|
||||
|
||||
ArrayRef<char> DecoderResult::getRawBytes() {
|
||||
return rawBytes_;
|
||||
}
|
||||
|
||||
Ref<String> DecoderResult::getText() {
|
||||
return text_;
|
||||
}
|
|
@ -1,51 +0,0 @@
|
|||
#ifndef __DECODER_RESULT_H__
|
||||
#define __DECODER_RESULT_H__
|
||||
|
||||
/*
|
||||
* DecoderResult.h
|
||||
* zxing
|
||||
*
|
||||
* Copyright 2010 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/common/Counted.h>
|
||||
#include <zxing/common/Array.h>
|
||||
#include <string>
|
||||
#include <zxing/common/Str.h>
|
||||
|
||||
namespace zxing {
|
||||
|
||||
class DecoderResult : public Counted {
|
||||
private:
|
||||
ArrayRef<char> rawBytes_;
|
||||
Ref<String> text_;
|
||||
ArrayRef< ArrayRef<char> > byteSegments_;
|
||||
std::string ecLevel_;
|
||||
|
||||
public:
|
||||
DecoderResult(ArrayRef<char> rawBytes,
|
||||
Ref<String> text,
|
||||
ArrayRef< ArrayRef<char> >& byteSegments,
|
||||
std::string const& ecLevel);
|
||||
|
||||
DecoderResult(ArrayRef<char> rawBytes, Ref<String> text);
|
||||
|
||||
ArrayRef<char> getRawBytes();
|
||||
Ref<String> getText();
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif // __DECODER_RESULT_H__
|
|
@ -1,39 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
/*
|
||||
* DetectorResult.cpp
|
||||
* zxing
|
||||
*
|
||||
* Created by Christian Brunschen on 14/05/2008.
|
||||
* Copyright 2008 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/common/DetectorResult.h>
|
||||
|
||||
namespace zxing {
|
||||
|
||||
DetectorResult::DetectorResult(Ref<BitMatrix> bits,
|
||||
ArrayRef< Ref<ResultPoint> > points)
|
||||
: bits_(bits), points_(points) {
|
||||
}
|
||||
|
||||
Ref<BitMatrix> DetectorResult::getBits() {
|
||||
return bits_;
|
||||
}
|
||||
|
||||
ArrayRef< Ref<ResultPoint> > DetectorResult::getPoints() {
|
||||
return points_;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,43 +0,0 @@
|
|||
#ifndef __DETECTOR_RESULT_H__
|
||||
#define __DETECTOR_RESULT_H__
|
||||
|
||||
/*
|
||||
* DetectorResult.h
|
||||
* zxing
|
||||
*
|
||||
* Copyright 2010 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/common/Counted.h>
|
||||
#include <zxing/common/Array.h>
|
||||
#include <zxing/common/BitMatrix.h>
|
||||
#include <zxing/ResultPoint.h>
|
||||
|
||||
namespace zxing {
|
||||
|
||||
class DetectorResult : public Counted {
|
||||
private:
|
||||
Ref<BitMatrix> bits_;
|
||||
ArrayRef< Ref<ResultPoint> > points_;
|
||||
|
||||
public:
|
||||
DetectorResult(Ref<BitMatrix> bits, ArrayRef< Ref<ResultPoint> > points);
|
||||
Ref<BitMatrix> getBits();
|
||||
ArrayRef< Ref<ResultPoint> > getPoints();
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif // __DETECTOR_RESULT_H__
|
|
@ -1,212 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
/*
|
||||
* GlobalHistogramBinarizer.cpp
|
||||
* zxing
|
||||
*
|
||||
* Copyright 2010 ZXing authors. All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/common/GlobalHistogramBinarizer.h>
|
||||
#include <zxing/NotFoundException.h>
|
||||
#include <zxing/common/Array.h>
|
||||
|
||||
using zxing::GlobalHistogramBinarizer;
|
||||
using zxing::Binarizer;
|
||||
using zxing::ArrayRef;
|
||||
using zxing::Ref;
|
||||
using zxing::BitArray;
|
||||
using zxing::BitMatrix;
|
||||
|
||||
// VC++
|
||||
using zxing::LuminanceSource;
|
||||
|
||||
namespace {
|
||||
const int LUMINANCE_BITS = 5;
|
||||
const int LUMINANCE_SHIFT = 8 - LUMINANCE_BITS;
|
||||
const int LUMINANCE_BUCKETS = 1 << LUMINANCE_BITS;
|
||||
const ArrayRef<char> EMPTY (0);
|
||||
}
|
||||
|
||||
GlobalHistogramBinarizer::GlobalHistogramBinarizer(Ref<LuminanceSource> source)
|
||||
: Binarizer(source), luminances(EMPTY), buckets(LUMINANCE_BUCKETS) {}
|
||||
|
||||
GlobalHistogramBinarizer::~GlobalHistogramBinarizer() {}
|
||||
|
||||
void GlobalHistogramBinarizer::initArrays(int luminanceSize) {
|
||||
if (luminances->size() < luminanceSize) {
|
||||
luminances = ArrayRef<char>(luminanceSize);
|
||||
}
|
||||
for (int x = 0; x < LUMINANCE_BUCKETS; x++) {
|
||||
buckets[x] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
Ref<BitArray> GlobalHistogramBinarizer::getBlackRow(int y, Ref<BitArray> row) {
|
||||
// std::cerr << "gbr " << y << std::endl;
|
||||
LuminanceSource& source = *getLuminanceSource();
|
||||
int width = source.getWidth();
|
||||
if (row == NULL || static_cast<int>(row->getSize()) < width) {
|
||||
row = new BitArray(width);
|
||||
} else {
|
||||
row->clear();
|
||||
}
|
||||
|
||||
initArrays(width);
|
||||
ArrayRef<char> localLuminances = source.getRow(y, luminances);
|
||||
if (false) {
|
||||
std::cerr << "gbr " << y << " r ";
|
||||
for(int i=0, e=localLuminances->size(); i < e; ++i) {
|
||||
std::cerr << 0+localLuminances[i] << " ";
|
||||
}
|
||||
std::cerr << std::endl;
|
||||
}
|
||||
ArrayRef<int> localBuckets = buckets;
|
||||
for (int x = 0; x < width; x++) {
|
||||
int pixel = localLuminances[x] & 0xff;
|
||||
localBuckets[pixel >> LUMINANCE_SHIFT]++;
|
||||
}
|
||||
int blackPoint = estimateBlackPoint(localBuckets);
|
||||
// std::cerr << "gbr bp " << y << " " << blackPoint << std::endl;
|
||||
|
||||
int left = localLuminances[0] & 0xff;
|
||||
int center = localLuminances[1] & 0xff;
|
||||
for (int x = 1; x < width - 1; x++) {
|
||||
int right = localLuminances[x + 1] & 0xff;
|
||||
// A simple -1 4 -1 box filter with a weight of 2.
|
||||
int luminance = ((center << 2) - left - right) >> 1;
|
||||
if (luminance < blackPoint) {
|
||||
row->set(x);
|
||||
}
|
||||
left = center;
|
||||
center = right;
|
||||
}
|
||||
return row;
|
||||
}
|
||||
|
||||
Ref<BitMatrix> GlobalHistogramBinarizer::getBlackMatrix() {
|
||||
LuminanceSource& source = *getLuminanceSource();
|
||||
int width = source.getWidth();
|
||||
int height = source.getHeight();
|
||||
Ref<BitMatrix> matrix(new BitMatrix(width, height));
|
||||
|
||||
// Quickly calculates the histogram by sampling four rows from the image.
|
||||
// This proved to be more robust on the blackbox tests than sampling a
|
||||
// diagonal as we used to do.
|
||||
initArrays(width);
|
||||
ArrayRef<int> localBuckets = buckets;
|
||||
for (int y = 1; y < 5; y++) {
|
||||
int row = height * y / 5;
|
||||
ArrayRef<char> localLuminances = source.getRow(row, luminances);
|
||||
int right = (width << 2) / 5;
|
||||
for (int x = width / 5; x < right; x++) {
|
||||
int pixel = localLuminances[x] & 0xff;
|
||||
localBuckets[pixel >> LUMINANCE_SHIFT]++;
|
||||
}
|
||||
}
|
||||
|
||||
int blackPoint = estimateBlackPoint(localBuckets);
|
||||
|
||||
ArrayRef<char> localLuminances = source.getMatrix();
|
||||
for (int y = 0; y < height; y++) {
|
||||
int offset = y * width;
|
||||
for (int x = 0; x < width; x++) {
|
||||
int pixel = localLuminances[offset + x] & 0xff;
|
||||
if (pixel < blackPoint) {
|
||||
matrix->set(x, y);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return matrix;
|
||||
}
|
||||
|
||||
using namespace std;
|
||||
|
||||
int GlobalHistogramBinarizer::estimateBlackPoint(ArrayRef<int> const& buckets) {
|
||||
// Find tallest peak in histogram
|
||||
int numBuckets = buckets->size();
|
||||
int maxBucketCount = 0;
|
||||
int firstPeak = 0;
|
||||
int firstPeakSize = 0;
|
||||
if (false) {
|
||||
for (int x = 0; x < numBuckets; x++) {
|
||||
cerr << buckets[x] << " ";
|
||||
}
|
||||
cerr << endl;
|
||||
}
|
||||
for (int x = 0; x < numBuckets; x++) {
|
||||
if (buckets[x] > firstPeakSize) {
|
||||
firstPeak = x;
|
||||
firstPeakSize = buckets[x];
|
||||
}
|
||||
if (buckets[x] > maxBucketCount) {
|
||||
maxBucketCount = buckets[x];
|
||||
}
|
||||
}
|
||||
|
||||
// Find second-tallest peak -- well, another peak that is tall and not
|
||||
// so close to the first one
|
||||
int secondPeak = 0;
|
||||
int secondPeakScore = 0;
|
||||
for (int x = 0; x < numBuckets; x++) {
|
||||
int distanceToBiggest = x - firstPeak;
|
||||
// Encourage more distant second peaks by multiplying by square of distance
|
||||
int score = buckets[x] * distanceToBiggest * distanceToBiggest;
|
||||
if (score > secondPeakScore) {
|
||||
secondPeak = x;
|
||||
secondPeakScore = score;
|
||||
}
|
||||
}
|
||||
|
||||
if (firstPeak > secondPeak) {
|
||||
int temp = firstPeak;
|
||||
firstPeak = secondPeak;
|
||||
secondPeak = temp;
|
||||
}
|
||||
|
||||
// Kind of arbitrary; if the two peaks are very close, then we figure there is
|
||||
// so little dynamic range in the image, that discriminating black and white
|
||||
// is too error-prone.
|
||||
// Decoding the image/line is either pointless, or may in some cases lead to
|
||||
// a false positive for 1D formats, which are relatively lenient.
|
||||
// We arbitrarily say "close" is
|
||||
// "<= 1/16 of the total histogram buckets apart"
|
||||
// std::cerr << "! " << secondPeak << " " << firstPeak << " " << numBuckets << std::endl;
|
||||
if (secondPeak - firstPeak <= numBuckets >> 4) {
|
||||
throw NotFoundException();
|
||||
}
|
||||
|
||||
// Find a valley between them that is low and closer to the white peak
|
||||
int bestValley = secondPeak - 1;
|
||||
int bestValleyScore = -1;
|
||||
for (int x = secondPeak - 1; x > firstPeak; x--) {
|
||||
int fromFirst = x - firstPeak;
|
||||
// Favor a "valley" that is not too close to either peak -- especially not
|
||||
// the black peak -- and that has a low value of course
|
||||
int score = fromFirst * fromFirst * (secondPeak - x) *
|
||||
(maxBucketCount - buckets[x]);
|
||||
if (score > bestValleyScore) {
|
||||
bestValley = x;
|
||||
bestValleyScore = score;
|
||||
}
|
||||
}
|
||||
|
||||
// std::cerr << "bps " << (bestValley << LUMINANCE_SHIFT) << std::endl;
|
||||
return bestValley << LUMINANCE_SHIFT;
|
||||
}
|
||||
|
||||
Ref<Binarizer> GlobalHistogramBinarizer::createBinarizer(Ref<LuminanceSource> source) {
|
||||
return Ref<Binarizer> (new GlobalHistogramBinarizer(source));
|
||||
}
|
|
@ -1,48 +0,0 @@
|
|||
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
|
||||
#ifndef __GLOBALHISTOGRAMBINARIZER_H__
|
||||
#define __GLOBALHISTOGRAMBINARIZER_H__
|
||||
/*
|
||||
* GlobalHistogramBinarizer.h
|
||||
* zxing
|
||||
*
|
||||
* Copyright 2010 ZXing authors All rights reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
#include <zxing/Binarizer.h>
|
||||
#include <zxing/common/BitArray.h>
|
||||
#include <zxing/common/BitMatrix.h>
|
||||
#include <zxing/common/Array.h>
|
||||
|
||||
namespace zxing {
|
||||
|
||||
class GlobalHistogramBinarizer : public Binarizer {
|
||||
private:
|
||||
ArrayRef<char> luminances;
|
||||
ArrayRef<int> buckets;
|
||||
public:
|
||||
GlobalHistogramBinarizer(Ref<LuminanceSource> source);
|
||||
virtual ~GlobalHistogramBinarizer();
|
||||
|
||||
virtual Ref<BitArray> getBlackRow(int y, Ref<BitArray> row);
|
||||
virtual Ref<BitMatrix> getBlackMatrix();
|
||||
static int estimateBlackPoint(ArrayRef<int> const& buckets);
|
||||
Ref<Binarizer> createBinarizer(Ref<LuminanceSource> source);
|
||||
private:
|
||||
void initArrays(int luminanceSize);
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
#endif /* GLOBALHISTOGRAMBINARIZER_H_ */
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue