repo
stringlengths
1
152
file
stringlengths
14
221
code
stringlengths
501
25k
file_length
int64
501
25k
avg_line_length
float64
20
99.5
max_line_length
int64
21
134
extension_type
stringclasses
2 values
openalpr
openalpr-master/src/openalpr/simpleini/ConvertUTF.h
/* * Copyright © 1991-2015 Unicode, Inc. All rights reserved. * Distributed under the Terms of Use in * http://www.unicode.org/copyright.html. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of the Unicode data files and any associated documentation * (the "Data Files") or Unicode software and any associated documentation * (the "Software") to deal in the Data Files or Software * without restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, and/or sell copies of * the Data Files or Software, and to permit persons to whom the Data Files * or Software are furnished to do so, provided that * (a) this copyright and permission notice appear with all copies * of the Data Files or Software, * (b) this copyright and permission notice appear in associated * documentation, and * (c) there is clear notice in each modified Data File or in the Software * as well as in the documentation associated with the Data File(s) or * Software that the data or software has been modified. * * THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF * ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT OF THIRD PARTY RIGHTS. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS * NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL * DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THE DATA FILES OR SOFTWARE. * * Except as contained in this notice, the name of a copyright holder * shall not be used in advertising or otherwise to promote the sale, * use or other dealings in these Data Files or Software without prior * written authorization of the copyright holder. */ /* --------------------------------------------------------------------- Conversions between UTF32, UTF-16, and UTF-8. Header file. Several funtions are included here, forming a complete set of conversions between the three formats. UTF-7 is not included here, but is handled in a separate source file. Each of these routines takes pointers to input buffers and output buffers. The input buffers are const. Each routine converts the text between *sourceStart and sourceEnd, putting the result into the buffer between *targetStart and targetEnd. Note: the end pointers are *after* the last item: e.g. *(sourceEnd - 1) is the last item. The return result indicates whether the conversion was successful, and if not, whether the problem was in the source or target buffers. (Only the first encountered problem is indicated.) After the conversion, *sourceStart and *targetStart are both updated to point to the end of last text successfully converted in the respective buffers. Input parameters: sourceStart - pointer to a pointer to the source buffer. The contents of this are modified on return so that it points at the next thing to be converted. targetStart - similarly, pointer to pointer to the target buffer. sourceEnd, targetEnd - respectively pointers to the ends of the two buffers, for overflow checking only. These conversion functions take a ConversionFlags argument. When this flag is set to strict, both irregular sequences and isolated surrogates will cause an error. When the flag is set to lenient, both irregular sequences and isolated surrogates are converted. Whether the flag is strict or lenient, all illegal sequences will cause an error return. This includes sequences such as: <F4 90 80 80>, <C0 80>, or <A0> in UTF-8, and values above 0x10FFFF in UTF-32. Conformant code must check for illegal sequences. When the flag is set to lenient, characters over 0x10FFFF are converted to the replacement character; otherwise (when the flag is set to strict) they constitute an error. Output parameters: The value "sourceIllegal" is returned from some routines if the input sequence is malformed. When "sourceIllegal" is returned, the source value will point to the illegal value that caused the problem. E.g., in UTF-8 when a sequence is malformed, it points to the start of the malformed sequence. Author: Mark E. Davis, 1994. Rev History: Rick McGowan, fixes & updates May 2001. Fixes & updates, Sept 2001. ------------------------------------------------------------------------ */ /* --------------------------------------------------------------------- The following 4 definitions are compiler-specific. The C standard does not guarantee that wchar_t has at least 16 bits, so wchar_t is no less portable than unsigned short! All should be unsigned values to avoid sign extension during bit mask & shift operations. ------------------------------------------------------------------------ */ typedef unsigned int UTF32; /* at least 32 bits */ typedef unsigned short UTF16; /* at least 16 bits */ typedef unsigned char UTF8; /* typically 8 bits */ typedef unsigned char Boolean; /* 0 or 1 */ /* Some fundamental constants */ #define UNI_REPLACEMENT_CHAR (UTF32)0x0000FFFD #define UNI_MAX_BMP (UTF32)0x0000FFFF #define UNI_MAX_UTF16 (UTF32)0x0010FFFF #define UNI_MAX_UTF32 (UTF32)0x7FFFFFFF #define UNI_MAX_LEGAL_UTF32 (UTF32)0x0010FFFF typedef enum { conversionOK, /* conversion successful */ sourceExhausted, /* partial character in source, but hit end */ targetExhausted, /* insuff. room in target for conversion */ sourceIllegal /* source sequence is illegal/malformed */ } ConversionResult; typedef enum { strictConversion = 0, lenientConversion } ConversionFlags; /* This is for C++ and does no harm in C */ #ifdef __cplusplus extern "C" { #endif ConversionResult ConvertUTF8toUTF16 ( const UTF8** sourceStart, const UTF8* sourceEnd, UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags); ConversionResult ConvertUTF16toUTF8 ( const UTF16** sourceStart, const UTF16* sourceEnd, UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags); ConversionResult ConvertUTF8toUTF32 ( const UTF8** sourceStart, const UTF8* sourceEnd, UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags); ConversionResult ConvertUTF32toUTF8 ( const UTF32** sourceStart, const UTF32* sourceEnd, UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags); ConversionResult ConvertUTF16toUTF32 ( const UTF16** sourceStart, const UTF16* sourceEnd, UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags); ConversionResult ConvertUTF32toUTF16 ( const UTF32** sourceStart, const UTF32* sourceEnd, UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags); Boolean isLegalUTF8Sequence(const UTF8 *source, const UTF8 *sourceEnd); #ifdef __cplusplus } #endif /* --------------------------------------------------------------------- */
7,095
41.238095
77
h
openalpr
openalpr-master/src/openalpr/support/fast_mutex.h
/* -*- mode: c++; tab-width: 2; indent-tabs-mode: nil; -*- Copyright (c) 2010-2012 Marcus Geelnard 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. */ #ifndef _FAST_MUTEX_H_ #define _FAST_MUTEX_H_ /// @file // Which platform are we on? #if !defined(_TTHREAD_PLATFORM_DEFINED_) #if defined(_WIN32) || defined(__WIN32__) || defined(__WINDOWS__) #define _TTHREAD_WIN32_ #else #define _TTHREAD_POSIX_ #endif #define _TTHREAD_PLATFORM_DEFINED_ #endif // Check if we can support the assembly language level implementation (otherwise // revert to the system API) #if (defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))) || \ (defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64))) || \ (defined(__GNUC__) && (defined(__ppc__))) #define _FAST_MUTEX_ASM_ #else #define _FAST_MUTEX_SYS_ #endif #if defined(_TTHREAD_WIN32_) #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #define __UNDEF_LEAN_AND_MEAN #endif #include <windows.h> #ifdef __UNDEF_LEAN_AND_MEAN #undef WIN32_LEAN_AND_MEAN #undef __UNDEF_LEAN_AND_MEAN #endif #else #ifdef _FAST_MUTEX_ASM_ #include <sched.h> #else #include <pthread.h> #endif #endif namespace tthread { /// Fast mutex class. /// This is a mutual exclusion object for synchronizing access to shared /// memory areas for several threads. It is similar to the tthread::mutex class, /// but instead of using system level functions, it is implemented as an atomic /// spin lock with very low CPU overhead. /// /// The \c fast_mutex class is NOT compatible with the \c condition_variable /// class (however, it IS compatible with the \c lock_guard class). It should /// also be noted that the \c fast_mutex class typically does not provide /// as accurate thread scheduling as a the standard \c mutex class does. /// /// Because of the limitations of the class, it should only be used in /// situations where the mutex needs to be locked/unlocked very frequently. /// /// @note The "fast" version of this class relies on inline assembler language, /// which is currently only supported for 32/64-bit Intel x86/AMD64 and /// PowerPC architectures on a limited number of compilers (GNU g++ and MS /// Visual C++). /// For other architectures/compilers, system functions are used instead. class fast_mutex { public: /// Constructor. #if defined(_FAST_MUTEX_ASM_) fast_mutex() : mLock(0) {} #else fast_mutex() { #if defined(_TTHREAD_WIN32_) InitializeCriticalSection(&mHandle); #elif defined(_TTHREAD_POSIX_) pthread_mutex_init(&mHandle, NULL); #endif } #endif #if !defined(_FAST_MUTEX_ASM_) /// Destructor. ~fast_mutex() { #if defined(_TTHREAD_WIN32_) DeleteCriticalSection(&mHandle); #elif defined(_TTHREAD_POSIX_) pthread_mutex_destroy(&mHandle); #endif } #endif /// Lock the mutex. /// The method will block the calling thread until a lock on the mutex can /// be obtained. The mutex remains locked until \c unlock() is called. /// @see lock_guard inline void lock() { #if defined(_FAST_MUTEX_ASM_) bool gotLock; do { gotLock = try_lock(); if(!gotLock) { #if defined(_TTHREAD_WIN32_) Sleep(0); #elif defined(_TTHREAD_POSIX_) sched_yield(); #endif } } while(!gotLock); #else #if defined(_TTHREAD_WIN32_) EnterCriticalSection(&mHandle); #elif defined(_TTHREAD_POSIX_) pthread_mutex_lock(&mHandle); #endif #endif } /// Try to lock the mutex. /// The method will try to lock the mutex. If it fails, the function will /// return immediately (non-blocking). /// @return \c true if the lock was acquired, or \c false if the lock could /// not be acquired. inline bool try_lock() { #if defined(_FAST_MUTEX_ASM_) int oldLock; #if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) asm volatile ( "movl $1,%%eax\n\t" "xchg %%eax,%0\n\t" "movl %%eax,%1\n\t" : "=m" (mLock), "=m" (oldLock) : : "%eax", "memory" ); #elif defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64)) int *ptrLock = &mLock; __asm { mov eax,1 mov ecx,ptrLock xchg eax,[ecx] mov oldLock,eax } #elif defined(__GNUC__) && (defined(__ppc__)) int newLock = 1; asm volatile ( "\n1:\n\t" "lwarx %0,0,%1\n\t" "cmpwi 0,%0,0\n\t" "bne- 2f\n\t" "stwcx. %2,0,%1\n\t" "bne- 1b\n\t" "isync\n" "2:\n\t" : "=&r" (oldLock) : "r" (&mLock), "r" (newLock) : "cr0", "memory" ); #endif return (oldLock == 0); #else #if defined(_TTHREAD_WIN32_) return TryEnterCriticalSection(&mHandle) ? true : false; #elif defined(_TTHREAD_POSIX_) return (pthread_mutex_trylock(&mHandle) == 0) ? true : false; #endif #endif } /// Unlock the mutex. /// If any threads are waiting for the lock on this mutex, one of them will /// be unblocked. inline void unlock() { #if defined(_FAST_MUTEX_ASM_) #if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__)) asm volatile ( "movl $0,%%eax\n\t" "xchg %%eax,%0\n\t" : "=m" (mLock) : : "%eax", "memory" ); #elif defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64)) int *ptrLock = &mLock; __asm { mov eax,0 mov ecx,ptrLock xchg eax,[ecx] } #elif defined(__GNUC__) && (defined(__ppc__)) asm volatile ( "sync\n\t" // Replace with lwsync where possible? : : : "memory" ); mLock = 0; #endif #else #if defined(_TTHREAD_WIN32_) LeaveCriticalSection(&mHandle); #elif defined(_TTHREAD_POSIX_) pthread_mutex_unlock(&mHandle); #endif #endif } private: #if defined(_FAST_MUTEX_ASM_) int mLock; #else #if defined(_TTHREAD_WIN32_) CRITICAL_SECTION mHandle; #elif defined(_TTHREAD_POSIX_) pthread_mutex_t mHandle; #endif #endif }; } #endif // _FAST_MUTEX_H_
6,940
26.875502
80
h
openalpr
openalpr-master/src/openalpr/support/filesystem.h
#ifndef FILESYSTEM_H #define FILESYSTEM_H #ifdef WINDOWS #include <windows.h> #include "windows/dirent.h" #include "windows/utils.h" #include "windows/unistd_partial.h" typedef int mode_t; #else #include <dirent.h> #include <unistd.h> #endif #include <stdint.h> #include <string> #include <sys/stat.h> #include <vector> namespace alpr { struct FileInfo { int64_t size; int64_t creation_time; }; bool startsWith(std::string const &fullString, std::string const &prefix); bool hasEnding (std::string const &fullString, std::string const &ending); bool hasEndingInsensitive(const std::string& fullString, const std::string& ending); std::string filenameWithoutExtension(std::string filename); FileInfo getFileInfo(std::string filename); bool DirectoryExists( const char* pzPath ); bool fileExists( const char* pzPath ); std::vector<std::string> getFilesInDir(const char* dirPath); bool stringCompare( const std::string &left, const std::string &right ); bool makePath(const char* path, mode_t mode); std::string get_directory_from_path(std::string file_path); std::string get_filename_from_path(std::string file_path); } #endif // FILESYSTEM_H
1,196
22.470588
86
h
openalpr
openalpr-master/src/openalpr/support/tinydir.h
/* Copyright (c) 2013, Cong Xu All rights reserved. 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. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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 TINYDIR_H #define TINYDIR_H #include <errno.h> #include <stdlib.h> #include <string.h> #ifdef _MSC_VER #define WIN32_LEAN_AND_MEAN #include <windows.h> #pragma warning (disable : 4996) #else #include <dirent.h> #include <sys/stat.h> #endif /* types */ #define _TINYDIR_PATH_MAX 4096 #ifdef _MSC_VER /* extra chars for the "\\*" mask */ #define _TINYDIR_PATH_EXTRA 2 #else #define _TINYDIR_PATH_EXTRA 0 #endif #define _TINYDIR_FILENAME_MAX 256 #ifdef _MSC_VER #define strncasecmp _strnicmp #endif #ifdef _MSC_VER #define _TINYDIR_FUNC static __inline #else #define _TINYDIR_FUNC static __inline__ #endif typedef struct { char path[_TINYDIR_PATH_MAX]; char name[_TINYDIR_FILENAME_MAX]; int is_dir; int is_reg; #ifdef _MSC_VER #else struct stat _s; #endif } tinydir_file; typedef struct { char path[_TINYDIR_PATH_MAX]; int has_next; int n_files; tinydir_file *_files; #ifdef _MSC_VER HANDLE _h; WIN32_FIND_DATA _f; #else DIR *_d; struct dirent *_e; #endif } tinydir_dir; /* declarations */ _TINYDIR_FUNC int tinydir_open(tinydir_dir *dir, const char *path); _TINYDIR_FUNC int tinydir_open_sorted(tinydir_dir *dir, const char *path); _TINYDIR_FUNC void tinydir_close(tinydir_dir *dir); _TINYDIR_FUNC int tinydir_next(tinydir_dir *dir); _TINYDIR_FUNC int tinydir_readfile(const tinydir_dir *dir, tinydir_file *file); _TINYDIR_FUNC int tinydir_readfile_n(const tinydir_dir *dir, tinydir_file *file, int i); _TINYDIR_FUNC int tinydir_open_subdir_n(tinydir_dir *dir, int i); _TINYDIR_FUNC int _tinydir_file_cmp(const void *a, const void *b); /* definitions*/ _TINYDIR_FUNC int tinydir_open(tinydir_dir *dir, const char *path) { if (dir == NULL || path == NULL || strlen(path) == 0) { errno = EINVAL; return -1; } if (strlen(path) + _TINYDIR_PATH_EXTRA >= _TINYDIR_PATH_MAX) { errno = ENAMETOOLONG; return -1; } /* initialise dir */ dir->_files = NULL; #ifdef _MSC_VER dir->_h = INVALID_HANDLE_VALUE; #else dir->_d = NULL; #endif tinydir_close(dir); strcpy(dir->path, path); #ifdef _MSC_VER strcat(dir->path, "\\*"); dir->_h = FindFirstFile(dir->path, &dir->_f); dir->path[strlen(dir->path) - 2] = '\0'; if (dir->_h == INVALID_HANDLE_VALUE) #else dir->_d = opendir(path); if (dir->_d == NULL) #endif { errno = ENOENT; goto bail; } /* read first file */ dir->has_next = 1; #ifndef _MSC_VER dir->_e = readdir(dir->_d); if (dir->_e == NULL) { dir->has_next = 0; } #endif return 0; bail: tinydir_close(dir); return -1; } _TINYDIR_FUNC int tinydir_open_sorted(tinydir_dir *dir, const char *path) { if (tinydir_open(dir, path) == -1) { return -1; } dir->n_files = 0; while (dir->has_next) { tinydir_file *p_file; dir->n_files++; dir->_files = (tinydir_file *)realloc(dir->_files, sizeof(tinydir_file)*dir->n_files); if (dir->_files == NULL) { errno = ENOMEM; goto bail; } p_file = &dir->_files[dir->n_files - 1]; if (tinydir_readfile(dir, p_file) == -1) { goto bail; } if (tinydir_next(dir) == -1) { goto bail; } } qsort(dir->_files, dir->n_files, sizeof(tinydir_file), _tinydir_file_cmp); return 0; bail: tinydir_close(dir); return -1; } _TINYDIR_FUNC void tinydir_close(tinydir_dir *dir) { if (dir == NULL) { return; } memset(dir->path, 0, sizeof(dir->path)); dir->has_next = 0; dir->n_files = -1; if (dir->_files != NULL) { free(dir->_files); } dir->_files = NULL; #ifdef _MSC_VER if (dir->_h != INVALID_HANDLE_VALUE) { FindClose(dir->_h); } dir->_h = INVALID_HANDLE_VALUE; #else if (dir->_d) { closedir(dir->_d); } dir->_d = NULL; dir->_e = NULL; #endif } _TINYDIR_FUNC int tinydir_next(tinydir_dir *dir) { if (dir == NULL) { errno = EINVAL; return -1; } if (!dir->has_next) { errno = ENOENT; return -1; } #ifdef _MSC_VER if (FindNextFile(dir->_h, &dir->_f) == 0) #else dir->_e = readdir(dir->_d); if (dir->_e == NULL) #endif { dir->has_next = 0; #ifdef _MSC_VER if (GetLastError() != ERROR_SUCCESS && GetLastError() != ERROR_NO_MORE_FILES) { tinydir_close(dir); errno = EIO; return -1; } #endif } return 0; } _TINYDIR_FUNC int tinydir_readfile(const tinydir_dir *dir, tinydir_file *file) { if (dir == NULL || file == NULL) { errno = EINVAL; return -1; } #ifdef _MSC_VER if (dir->_h == INVALID_HANDLE_VALUE) #else if (dir->_e == NULL) #endif { errno = ENOENT; return -1; } if (strlen(dir->path) + strlen( #ifdef _MSC_VER dir->_f.cFileName #else dir->_e->d_name #endif ) + 1 + _TINYDIR_PATH_EXTRA >= _TINYDIR_PATH_MAX) { /* the path for the file will be too long */ errno = ENAMETOOLONG; return -1; } if (strlen( #ifdef _MSC_VER dir->_f.cFileName #else dir->_e->d_name #endif ) >= _TINYDIR_FILENAME_MAX) { errno = ENAMETOOLONG; return -1; } strcpy(file->path, dir->path); strcat(file->path, "/"); strcpy(file->name, #ifdef _MSC_VER dir->_f.cFileName #else dir->_e->d_name #endif ); strcat(file->path, file->name); #ifndef _MSC_VER if (stat(file->path, &file->_s) == -1) { return -1; } #endif file->is_dir = #ifdef _MSC_VER !!(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY); #else S_ISDIR(file->_s.st_mode); #endif file->is_reg = #ifdef _MSC_VER !!(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_NORMAL) || ( !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_DEVICE) && !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_ENCRYPTED) && #ifdef FILE_ATTRIBUTE_INTEGRITY_STREAM !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_INTEGRITY_STREAM) && #endif #ifdef FILE_ATTRIBUTE_NO_SCRUB_DATA !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_NO_SCRUB_DATA) && #endif !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_OFFLINE) && !(dir->_f.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY)); #else S_ISREG(file->_s.st_mode); #endif return 0; } _TINYDIR_FUNC int tinydir_readfile_n(const tinydir_dir *dir, tinydir_file *file, int i) { if (dir == NULL || file == NULL || i < 0) { errno = EINVAL; return -1; } if (i >= dir->n_files) { errno = ENOENT; return -1; } memcpy(file, &dir->_files[i], sizeof(tinydir_file)); return 0; } _TINYDIR_FUNC int tinydir_open_subdir_n(tinydir_dir *dir, int i) { char path[_TINYDIR_PATH_MAX]; if (dir == NULL || i < 0) { errno = EINVAL; return -1; } if (i >= dir->n_files || !dir->_files[i].is_dir) { errno = ENOENT; return -1; } strcpy(path, dir->_files[i].path); tinydir_close(dir); if (tinydir_open_sorted(dir, path) == -1) { return -1; } return 0; } _TINYDIR_FUNC int _tinydir_file_cmp(const void *a, const void *b) { const tinydir_file *fa = (const tinydir_file *)a; const tinydir_file *fb = (const tinydir_file *)b; if (fa->is_dir != fb->is_dir) { return -(fa->is_dir - fb->is_dir); } return strncasecmp(fa->name, fb->name, _TINYDIR_FILENAME_MAX); } #endif
8,501
20.255
90
h
openalpr
openalpr-master/src/openalpr/support/tinythread.h
/* -*- mode: c++; tab-width: 2; indent-tabs-mode: nil; -*- Copyright (c) 2010-2012 Marcus Geelnard 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. */ #ifndef _TINYTHREAD_H_ #define _TINYTHREAD_H_ /// @file /// @mainpage TinyThread++ API Reference /// /// @section intro_sec Introduction /// TinyThread++ is a minimal, portable implementation of basic threading /// classes for C++. /// /// They closely mimic the functionality and naming of the C++11 standard, and /// should be easily replaceable with the corresponding std:: variants. /// /// @section port_sec Portability /// The Win32 variant uses the native Win32 API for implementing the thread /// classes, while for other systems, the POSIX threads API (pthread) is used. /// /// @section class_sec Classes /// In order to mimic the threading API of the C++11 standard, subsets of /// several classes are provided. The fundamental classes are: /// @li tthread::thread /// @li tthread::mutex /// @li tthread::recursive_mutex /// @li tthread::condition_variable /// @li tthread::lock_guard /// @li tthread::fast_mutex /// /// @section misc_sec Miscellaneous /// The following special keywords are available: #thread_local. /// /// For more detailed information (including additional classes), browse the /// different sections of this documentation. A good place to start is: /// tinythread.h. // Which platform are we on? #if !defined(_TTHREAD_PLATFORM_DEFINED_) #if defined(_WIN32) || defined(__WIN32__) || defined(__WINDOWS__) #define _TTHREAD_WIN32_ #else #define _TTHREAD_POSIX_ #endif #define _TTHREAD_PLATFORM_DEFINED_ #endif // Platform specific includes #if defined(_TTHREAD_WIN32_) #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #define __UNDEF_LEAN_AND_MEAN #endif #include <windows.h> #ifdef __UNDEF_LEAN_AND_MEAN #undef WIN32_LEAN_AND_MEAN #undef __UNDEF_LEAN_AND_MEAN #endif #else #include <pthread.h> #include <signal.h> #include <sched.h> #include <unistd.h> #endif // Generic includes #include <ostream> /// TinyThread++ version (major number). #define TINYTHREAD_VERSION_MAJOR 1 /// TinyThread++ version (minor number). #define TINYTHREAD_VERSION_MINOR 1 /// TinyThread++ version (full version). #define TINYTHREAD_VERSION (TINYTHREAD_VERSION_MAJOR * 100 + TINYTHREAD_VERSION_MINOR) // Do we have a fully featured C++11 compiler? #if (__cplusplus > 199711L) || (defined(__STDCXX_VERSION__) && (__STDCXX_VERSION__ >= 201001L)) #define _TTHREAD_CPP11_ #endif // ...at least partial C++11? #if defined(_TTHREAD_CPP11_) || defined(__GXX_EXPERIMENTAL_CXX0X__) || defined(__GXX_EXPERIMENTAL_CPP0X__) #define _TTHREAD_CPP11_PARTIAL_ #endif // Macro for disabling assignments of objects. #ifdef _TTHREAD_CPP11_PARTIAL_ #define _TTHREAD_DISABLE_ASSIGNMENT(name) \ name(const name&) = delete; \ name& operator=(const name&) = delete; #else #define _TTHREAD_DISABLE_ASSIGNMENT(name) \ name(const name&); \ name& operator=(const name&); #endif /// @def thread_local /// Thread local storage keyword. /// A variable that is declared with the @c thread_local keyword makes the /// value of the variable local to each thread (known as thread-local storage, /// or TLS). Example usage: /// @code /// // This variable is local to each thread. /// thread_local int variable; /// @endcode /// @note The @c thread_local keyword is a macro that maps to the corresponding /// compiler directive (e.g. @c __declspec(thread)). While the C++11 standard /// allows for non-trivial types (e.g. classes with constructors and /// destructors) to be declared with the @c thread_local keyword, most pre-C++11 /// compilers only allow for trivial types (e.g. @c int). So, to guarantee /// portable code, only use trivial types for thread local storage. /// @note This directive is currently not supported on Mac OS X (it will give /// a compiler error), since compile-time TLS is not supported in the Mac OS X /// executable format. Also, some older versions of MinGW (before GCC 4.x) do /// not support this directive. /// @hideinitializer #if !defined(_TTHREAD_CPP11_) && !defined(thread_local) #if defined(__GNUC__) || defined(__INTEL_COMPILER) || defined(__SUNPRO_CC) || defined(__IBMCPP__) #define thread_local __thread #else #define thread_local __declspec(thread) #endif #endif /// Main name space for TinyThread++. /// This namespace is more or less equivalent to the @c std namespace for the /// C++11 thread classes. For instance, the tthread::mutex class corresponds to /// the std::mutex class. namespace tthread { /// Mutex class. /// This is a mutual exclusion object for synchronizing access to shared /// memory areas for several threads. The mutex is non-recursive (i.e. a /// program may deadlock if the thread that owns a mutex object calls lock() /// on that object). /// @see recursive_mutex class mutex { public: /// Constructor. mutex() #if defined(_TTHREAD_WIN32_) : mAlreadyLocked(false) #endif { #if defined(_TTHREAD_WIN32_) InitializeCriticalSection(&mHandle); #else pthread_mutex_init(&mHandle, NULL); #endif } /// Destructor. ~mutex() { #if defined(_TTHREAD_WIN32_) DeleteCriticalSection(&mHandle); #else pthread_mutex_destroy(&mHandle); #endif } /// Lock the mutex. /// The method will block the calling thread until a lock on the mutex can /// be obtained. The mutex remains locked until @c unlock() is called. /// @see lock_guard inline void lock() { #if defined(_TTHREAD_WIN32_) EnterCriticalSection(&mHandle); while(mAlreadyLocked) Sleep(1000); // Simulate deadlock... mAlreadyLocked = true; #else pthread_mutex_lock(&mHandle); #endif } /// Try to lock the mutex. /// The method will try to lock the mutex. If it fails, the function will /// return immediately (non-blocking). /// @return @c true if the lock was acquired, or @c false if the lock could /// not be acquired. inline bool try_lock() { #if defined(_TTHREAD_WIN32_) bool ret = (TryEnterCriticalSection(&mHandle) ? true : false); if(ret && mAlreadyLocked) { LeaveCriticalSection(&mHandle); ret = false; } return ret; #else return (pthread_mutex_trylock(&mHandle) == 0) ? true : false; #endif } /// Unlock the mutex. /// If any threads are waiting for the lock on this mutex, one of them will /// be unblocked. inline void unlock() { #if defined(_TTHREAD_WIN32_) mAlreadyLocked = false; LeaveCriticalSection(&mHandle); #else pthread_mutex_unlock(&mHandle); #endif } _TTHREAD_DISABLE_ASSIGNMENT(mutex) private: #if defined(_TTHREAD_WIN32_) CRITICAL_SECTION mHandle; bool mAlreadyLocked; #else pthread_mutex_t mHandle; #endif friend class condition_variable; }; /// Recursive mutex class. /// This is a mutual exclusion object for synchronizing access to shared /// memory areas for several threads. The mutex is recursive (i.e. a thread /// may lock the mutex several times, as long as it unlocks the mutex the same /// number of times). /// @see mutex class recursive_mutex { public: /// Constructor. recursive_mutex() { #if defined(_TTHREAD_WIN32_) InitializeCriticalSection(&mHandle); #else pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&mHandle, &attr); #endif } /// Destructor. ~recursive_mutex() { #if defined(_TTHREAD_WIN32_) DeleteCriticalSection(&mHandle); #else pthread_mutex_destroy(&mHandle); #endif } /// Lock the mutex. /// The method will block the calling thread until a lock on the mutex can /// be obtained. The mutex remains locked until @c unlock() is called. /// @see lock_guard inline void lock() { #if defined(_TTHREAD_WIN32_) EnterCriticalSection(&mHandle); #else pthread_mutex_lock(&mHandle); #endif } /// Try to lock the mutex. /// The method will try to lock the mutex. If it fails, the function will /// return immediately (non-blocking). /// @return @c true if the lock was acquired, or @c false if the lock could /// not be acquired. inline bool try_lock() { #if defined(_TTHREAD_WIN32_) return TryEnterCriticalSection(&mHandle) ? true : false; #else return (pthread_mutex_trylock(&mHandle) == 0) ? true : false; #endif } /// Unlock the mutex. /// If any threads are waiting for the lock on this mutex, one of them will /// be unblocked. inline void unlock() { #if defined(_TTHREAD_WIN32_) LeaveCriticalSection(&mHandle); #else pthread_mutex_unlock(&mHandle); #endif } _TTHREAD_DISABLE_ASSIGNMENT(recursive_mutex) private: #if defined(_TTHREAD_WIN32_) CRITICAL_SECTION mHandle; #else pthread_mutex_t mHandle; #endif friend class condition_variable; }; /// Lock guard class. /// The constructor locks the mutex, and the destructor unlocks the mutex, so /// the mutex will automatically be unlocked when the lock guard goes out of /// scope. Example usage: /// @code /// mutex m; /// int counter; /// /// void increment() /// { /// lock_guard<mutex> guard(m); /// ++ counter; /// } /// @endcode template <class T> class lock_guard { public: typedef T mutex_type; lock_guard() : mMutex(0) {} /// The constructor locks the mutex. explicit lock_guard(mutex_type &aMutex) { mMutex = &aMutex; mMutex->lock(); } /// The destructor unlocks the mutex. ~lock_guard() { if(mMutex) mMutex->unlock(); } private: mutex_type * mMutex; }; /// Condition variable class. /// This is a signalling object for synchronizing the execution flow for /// several threads. Example usage: /// @code /// // Shared data and associated mutex and condition variable objects /// int count; /// mutex m; /// condition_variable cond; /// /// // Wait for the counter to reach a certain number /// void wait_counter(int targetCount) /// { /// lock_guard<mutex> guard(m); /// while(count < targetCount) /// cond.wait(m); /// } /// /// // Increment the counter, and notify waiting threads /// void increment() /// { /// lock_guard<mutex> guard(m); /// ++ count; /// cond.notify_all(); /// } /// @endcode class condition_variable { public: /// Constructor. #if defined(_TTHREAD_WIN32_) condition_variable(); #else condition_variable() { pthread_cond_init(&mHandle, NULL); } #endif /// Destructor. #if defined(_TTHREAD_WIN32_) ~condition_variable(); #else ~condition_variable() { pthread_cond_destroy(&mHandle); } #endif /// Wait for the condition. /// The function will block the calling thread until the condition variable /// is woken by @c notify_one(), @c notify_all() or a spurious wake up. /// @param[in] aMutex A mutex that will be unlocked when the wait operation /// starts, an locked again as soon as the wait operation is finished. template <class _mutexT> inline void wait(_mutexT &aMutex) { #if defined(_TTHREAD_WIN32_) // Increment number of waiters EnterCriticalSection(&mWaitersCountLock); ++ mWaitersCount; LeaveCriticalSection(&mWaitersCountLock); // Release the mutex while waiting for the condition (will decrease // the number of waiters when done)... aMutex.unlock(); _wait(); aMutex.lock(); #else pthread_cond_wait(&mHandle, &aMutex.mHandle); #endif } /// Notify one thread that is waiting for the condition. /// If at least one thread is blocked waiting for this condition variable, /// one will be woken up. /// @note Only threads that started waiting prior to this call will be /// woken up. #if defined(_TTHREAD_WIN32_) void notify_one(); #else inline void notify_one() { pthread_cond_signal(&mHandle); } #endif /// Notify all threads that are waiting for the condition. /// All threads that are blocked waiting for this condition variable will /// be woken up. /// @note Only threads that started waiting prior to this call will be /// woken up. #if defined(_TTHREAD_WIN32_) void notify_all(); #else inline void notify_all() { pthread_cond_broadcast(&mHandle); } #endif _TTHREAD_DISABLE_ASSIGNMENT(condition_variable) private: #if defined(_TTHREAD_WIN32_) void _wait(); HANDLE mEvents[2]; ///< Signal and broadcast event HANDLEs. unsigned int mWaitersCount; ///< Count of the number of waiters. CRITICAL_SECTION mWaitersCountLock; ///< Serialize access to mWaitersCount. #else pthread_cond_t mHandle; #endif }; /// Thread class. class thread { public: #if defined(_TTHREAD_WIN32_) typedef HANDLE native_handle_type; #else typedef pthread_t native_handle_type; #endif class id; /// Default constructor. /// Construct a @c thread object without an associated thread of execution /// (i.e. non-joinable). thread() : mHandle(0), mNotAThread(true) #if defined(_TTHREAD_WIN32_) , mWin32ThreadID(0) #endif {} /// Thread starting constructor. /// Construct a @c thread object with a new thread of execution. /// @param[in] aFunction A function pointer to a function of type: /// <tt>void fun(void * arg)</tt> /// @param[in] aArg Argument to the thread function. /// @note This constructor is not fully compatible with the standard C++ /// thread class. It is more similar to the pthread_create() (POSIX) and /// CreateThread() (Windows) functions. thread(void (*aFunction)(void *), void * aArg); /// Destructor. /// @note If the thread is joinable upon destruction, @c std::terminate() /// will be called, which terminates the process. It is always wise to do /// @c join() before deleting a thread object. ~thread(); /// Wait for the thread to finish (join execution flows). /// After calling @c join(), the thread object is no longer associated with /// a thread of execution (i.e. it is not joinable, and you may not join /// with it nor detach from it). void join(); /// Check if the thread is joinable. /// A thread object is joinable if it has an associated thread of execution. bool joinable() const; /// Detach from the thread. /// After calling @c detach(), the thread object is no longer assicated with /// a thread of execution (i.e. it is not joinable). The thread continues /// execution without the calling thread blocking, and when the thread /// ends execution, any owned resources are released. void detach(); /// Return the thread ID of a thread object. id get_id() const; /// Get the native handle for this thread. /// @note Under Windows, this is a @c HANDLE, and under POSIX systems, this /// is a @c pthread_t. inline native_handle_type native_handle() { return mHandle; } /// Determine the number of threads which can possibly execute concurrently. /// This function is useful for determining the optimal number of threads to /// use for a task. /// @return The number of hardware thread contexts in the system. /// @note If this value is not defined, the function returns zero (0). static unsigned hardware_concurrency(); _TTHREAD_DISABLE_ASSIGNMENT(thread) private: native_handle_type mHandle; ///< Thread handle. mutable mutex mDataMutex; ///< Serializer for access to the thread private data. bool mNotAThread; ///< True if this object is not a thread of execution. #if defined(_TTHREAD_WIN32_) unsigned int mWin32ThreadID; ///< Unique thread ID (filled out by _beginthreadex). #endif // This is the internal thread wrapper function. #if defined(_TTHREAD_WIN32_) static unsigned WINAPI wrapper_function(void * aArg); #else static void * wrapper_function(void * aArg); #endif }; /// Thread ID. /// The thread ID is a unique identifier for each thread. /// @see thread::get_id() class thread::id { public: /// Default constructor. /// The default constructed ID is that of thread without a thread of /// execution. id() : mId(0) {}; id(unsigned long int aId) : mId(aId) {}; id(const id& aId) : mId(aId.mId) {}; inline id & operator=(const id &aId) { mId = aId.mId; return *this; } inline friend bool operator==(const id &aId1, const id &aId2) { return (aId1.mId == aId2.mId); } inline friend bool operator!=(const id &aId1, const id &aId2) { return (aId1.mId != aId2.mId); } inline friend bool operator<=(const id &aId1, const id &aId2) { return (aId1.mId <= aId2.mId); } inline friend bool operator<(const id &aId1, const id &aId2) { return (aId1.mId < aId2.mId); } inline friend bool operator>=(const id &aId1, const id &aId2) { return (aId1.mId >= aId2.mId); } inline friend bool operator>(const id &aId1, const id &aId2) { return (aId1.mId > aId2.mId); } inline friend std::ostream& operator <<(std::ostream &os, const id &obj) { os << obj.mId; return os; } private: unsigned long int mId; }; // Related to <ratio> - minimal to be able to support chrono. typedef long long __intmax_t; /// Minimal implementation of the @c ratio class. This class provides enough /// functionality to implement some basic @c chrono classes. template <__intmax_t N, __intmax_t D = 1> class ratio { public: static double _as_double() { return double(N) / double(D); } }; /// Minimal implementation of the @c chrono namespace. /// The @c chrono namespace provides types for specifying time intervals. namespace chrono { /// Duration template class. This class provides enough functionality to /// implement @c this_thread::sleep_for(). template <class _Rep, class _Period = ratio<1> > class duration { private: _Rep rep_; public: typedef _Rep rep; typedef _Period period; /// Construct a duration object with the given duration. template <class _Rep2> explicit duration(const _Rep2& r) : rep_(r) {}; /// Return the value of the duration object. rep count() const { return rep_; } }; // Standard duration types. typedef duration<__intmax_t, ratio<1, 1000000000> > nanoseconds; ///< Duration with the unit nanoseconds. typedef duration<__intmax_t, ratio<1, 1000000> > microseconds; ///< Duration with the unit microseconds. typedef duration<__intmax_t, ratio<1, 1000> > milliseconds; ///< Duration with the unit milliseconds. typedef duration<__intmax_t> seconds; ///< Duration with the unit seconds. typedef duration<__intmax_t, ratio<60> > minutes; ///< Duration with the unit minutes. typedef duration<__intmax_t, ratio<3600> > hours; ///< Duration with the unit hours. } /// The namespace @c this_thread provides methods for dealing with the /// calling thread. namespace this_thread { /// Return the thread ID of the calling thread. thread::id get_id(); /// Yield execution to another thread. /// Offers the operating system the opportunity to schedule another thread /// that is ready to run on the current processor. inline void yield() { #if defined(_TTHREAD_WIN32_) Sleep(0); #else sched_yield(); #endif } /// Blocks the calling thread for a period of time. /// @param[in] aTime Minimum time to put the thread to sleep. /// Example usage: /// @code /// // Sleep for 100 milliseconds /// this_thread::sleep_for(chrono::milliseconds(100)); /// @endcode /// @note Supported duration types are: nanoseconds, microseconds, /// milliseconds, seconds, minutes and hours. template <class _Rep, class _Period> void sleep_for(const chrono::duration<_Rep, _Period>& aTime) { #if defined(_TTHREAD_WIN32_) Sleep(int(double(aTime.count()) * (1000.0 * _Period::_as_double()) + 0.5)); #else usleep(int(double(aTime.count()) * (1000000.0 * _Period::_as_double()) + 0.5)); #endif } } } // Define/macro cleanup #undef _TTHREAD_DISABLE_ASSIGNMENT #endif // _TINYTHREAD_H_
21,220
28.67972
108
h
openalpr
openalpr-master/src/openalpr/support/utf8.h
// Copyright 2006 Nemanja Trifunovic /* Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following: The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef UTF8_FOR_CPP_2675DCD0_9480_4c0c_B92A_CC14C027B731 #define UTF8_FOR_CPP_2675DCD0_9480_4c0c_B92A_CC14C027B731 #include "utf8/checked.h" #include "utf8/unchecked.h" std::string utf8chr(int cp); int codepoint(const std::string &u); #endif // header guard
1,590
40.868421
75
h
openalpr
openalpr-master/src/openalpr/support/re2/filtered_re2.h
// Copyright 2009 The RE2 Authors. All Rights Reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // The class FilteredRE2 is used as a wrapper to multiple RE2 regexps. // It provides a prefilter mechanism that helps in cutting down the // number of regexps that need to be actually searched. // // By design, it does not include a string matching engine. This is to // allow the user of the class to use their favorite string match // engine. The overall flow is: Add all the regexps using Add, then // Compile the FilteredRE2. The compile returns strings that need to // be matched. Note that all returned strings are lowercase. For // applying regexps to a search text, the caller does the string // matching using the strings returned. When doing the string match, // note that the caller has to do that on lower cased version of the // search text. Then call FirstMatch or AllMatches with a vector of // indices of strings that were found in the text to get the actual // regexp matches. #ifndef RE2_FILTERED_RE2_H_ #define RE2_FILTERED_RE2_H_ #include <vector> #include "re2.h" namespace re2 { using std::vector; class PrefilterTree; class FilteredRE2 { public: FilteredRE2(); ~FilteredRE2(); // Uses RE2 constructor to create a RE2 object (re). Returns // re->error_code(). If error_code is other than NoError, then re is // deleted and not added to re2_vec_. RE2::ErrorCode Add(const StringPiece& pattern, const RE2::Options& options, int *id); // Prepares the regexps added by Add for filtering. Returns a set // of strings that the caller should check for in candidate texts. // The returned strings are lowercased. When doing string matching, // the search text should be lowercased first to find matching // strings from the set of strings returned by Compile. Call after // all Add calls are done. void Compile(vector<string>* strings_to_match); // Returns the index of the first matching regexp. // Returns -1 on no match. Can be called prior to Compile. // Does not do any filtering: simply tries to Match the // regexps in a loop. int SlowFirstMatch(const StringPiece& text) const; // Returns the index of the first matching regexp. // Returns -1 on no match. Compile has to be called before // calling this. int FirstMatch(const StringPiece& text, const vector<int>& atoms) const; // Returns the indices of all matching regexps, after first clearing // matched_regexps. bool AllMatches(const StringPiece& text, const vector<int>& atoms, vector<int>* matching_regexps) const; // Returns the indices of all potentially matching regexps after first // clearing potential_regexps. // A regexp is potentially matching if it passes the filter. // If a regexp passes the filter it may still not match. // A regexp that does not pass the filter is guaranteed to not match. void AllPotentials(const vector<int>& atoms, vector<int>* potential_regexps) const; // The number of regexps added. int NumRegexps() const { return re2_vec_.size(); } private: // Get the individual RE2 objects. Useful for testing. RE2* GetRE2(int regexpid) const { return re2_vec_[regexpid]; } // Print prefilter. void PrintPrefilter(int regexpid); // Useful for testing and debugging. void RegexpsGivenStrings(const vector<int>& matched_atoms, vector<int>* passed_regexps); // All the regexps in the FilteredRE2. vector<RE2*> re2_vec_; // Has the FilteredRE2 been compiled using Compile() bool compiled_; // An AND-OR tree of string atoms used for filtering regexps. PrefilterTree* prefilter_tree_; //DISALLOW_COPY_AND_ASSIGN(FilteredRE2); FilteredRE2(const FilteredRE2&); void operator=(const FilteredRE2&); }; } // namespace re2 #endif // RE2_FILTERED_RE2_H_
3,975
35.145455
72
h
openalpr
openalpr-master/src/openalpr/support/re2/prefilter.h
// Copyright 2009 The RE2 Authors. All Rights Reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Prefilter is the class used to extract string guards from regexps. // Rather than using Prefilter class directly, use FilteredRE2. // See filtered_re2.h #ifndef RE2_PREFILTER_H_ #define RE2_PREFILTER_H_ #include <set> #include <vector> #include "util/util.h" namespace re2 { class RE2; class Regexp; class Prefilter { // Instead of using Prefilter directly, use FilteredRE2; see filtered_re2.h public: enum Op { ALL = 0, // Everything matches NONE, // Nothing matches ATOM, // The string atom() must match AND, // All in subs() must match OR, // One of subs() must match }; explicit Prefilter(Op op); ~Prefilter(); Op op() { return op_; } const std::string& atom() const { return atom_; } void set_unique_id(int id) { unique_id_ = id; } int unique_id() const { return unique_id_; } // The children of the Prefilter node. std::vector<Prefilter*>* subs() { CHECK(op_ == AND || op_ == OR); return subs_; } // Set the children vector. Prefilter takes ownership of subs and // subs_ will be deleted when Prefilter is deleted. void set_subs(std::vector<Prefilter*>* subs) { subs_ = subs; } // Given a RE2, return a Prefilter. The caller takes ownership of // the Prefilter and should deallocate it. Returns NULL if Prefilter // cannot be formed. static Prefilter* FromRE2(const RE2* re2); // Returns a readable debug string of the prefilter. std::string DebugString() const; private: class Info; // Combines two prefilters together to create an AND. The passed // Prefilters will be part of the returned Prefilter or deleted. static Prefilter* And(Prefilter* a, Prefilter* b); // Combines two prefilters together to create an OR. The passed // Prefilters will be part of the returned Prefilter or deleted. static Prefilter* Or(Prefilter* a, Prefilter* b); // Generalized And/Or static Prefilter* AndOr(Op op, Prefilter* a, Prefilter* b); static Prefilter* FromRegexp(Regexp* a); static Prefilter* FromString(const std::string& str); static Prefilter* OrStrings(std::set<std::string>* ss); static Info* BuildInfo(Regexp* re); Prefilter* Simplify(); // Kind of Prefilter. Op op_; // Sub-matches for AND or OR Prefilter. std::vector<Prefilter*>* subs_; // Actual string to match in leaf node. std::string atom_; // If different prefilters have the same string atom, or if they are // structurally the same (e.g., OR of same atom strings) they are // considered the same unique nodes. This is the id for each unique // node. This field is populated with a unique id for every node, // and -1 for duplicate nodes. int unique_id_; // Used for debugging, helps in tracking memory leaks. int alloc_id_; DISALLOW_COPY_AND_ASSIGN(Prefilter); }; } // namespace re2 #endif // RE2_PREFILTER_H_
3,009
26.614679
77
h
openalpr
openalpr-master/src/openalpr/support/re2/prefilter_tree.h
// Copyright 2009 The RE2 Authors. All Rights Reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // The PrefilterTree class is used to form an AND-OR tree of strings // that would trigger each regexp. The 'prefilter' of each regexp is // added tp PrefilterTree, and then PrefilterTree is used to find all // the unique strings across the prefilters. During search, by using // matches from a string matching engine, PrefilterTree deduces the // set of regexps that are to be triggered. The 'string matching // engine' itself is outside of this class, and the caller can use any // favorite engine. PrefilterTree provides a set of strings (called // atoms) that the user of this class should use to do the string // matching. // #ifndef RE2_PREFILTER_TREE_H_ #define RE2_PREFILTER_TREE_H_ #include <map> #include <vector> #include "util/util.h" #include "util/sparse_array.h" namespace re2 { typedef SparseArray<int> IntMap; typedef std::map<int, int> StdIntMap; class Prefilter; class PrefilterTree { public: PrefilterTree(); ~PrefilterTree(); // Adds the prefilter for the next regexp. Note that we assume that // Add called sequentially for all regexps. All Add calls // must precede Compile. void Add(Prefilter* prefilter); // The Compile returns a vector of string in atom_vec. // Call this after all the prefilters are added through Add. // No calls to Add after Compile are allowed. // The caller should use the returned set of strings to do string matching. // Each time a string matches, the corresponding index then has to be // and passed to RegexpsGivenStrings below. void Compile(std::vector<std::string>* atom_vec); // Given the indices of the atoms that matched, returns the indexes // of regexps that should be searched. The matched_atoms should // contain all the ids of string atoms that were found to match the // content. The caller can use any string match engine to perform // this function. This function is thread safe. void RegexpsGivenStrings(const std::vector<int>& matched_atoms, std::vector<int>* regexps) const; // Print debug prefilter. Also prints unique ids associated with // nodes of the prefilter of the regexp. void PrintPrefilter(int regexpid); // Each unique node has a corresponding Entry that helps in // passing the matching trigger information along the tree. struct Entry { public: // How many children should match before this node triggers the // parent. For an atom and an OR node, this is 1 and for an AND // node, it is the number of unique children. int propagate_up_at_count; // When this node is ready to trigger the parent, what are the indices // of the parent nodes to trigger. The reason there may be more than // one is because of sharing. For example (abc | def) and (xyz | def) // are two different nodes, but they share the atom 'def'. So when // 'def' matches, it triggers two parents, corresponding to the two // different OR nodes. StdIntMap* parents; // When this node is ready to trigger the parent, what are the // regexps that are triggered. std::vector<int> regexps; }; private: // This function assigns unique ids to various parts of the // prefilter, by looking at if these nodes are already in the // PrefilterTree. void AssignUniqueIds(std::vector<std::string>* atom_vec); // Given the matching atoms, find the regexps to be triggered. void PropagateMatch(const std::vector<int>& atom_ids, IntMap* regexps) const; // Returns the prefilter node that has the same NodeString as this // node. For the canonical node, returns node. Prefilter* CanonicalNode(Prefilter* node); // A string that uniquely identifies the node. Assumes that the // children of node has already been assigned unique ids. std::string NodeString(Prefilter* node) const; // Recursively constructs a readable prefilter string. std::string DebugNodeString(Prefilter* node) const; // Used for debugging. void PrintDebugInfo(); // These are all the nodes formed by Compile. Essentially, there is // one node for each unique atom and each unique AND/OR node. std::vector<Entry> entries_; // Map node string to canonical Prefilter node. std::map<std::string, Prefilter*> node_map_; // indices of regexps that always pass through the filter (since we // found no required literals in these regexps). std::vector<int> unfiltered_; // vector of Prefilter for all regexps. std::vector<Prefilter*> prefilter_vec_; // Atom index in returned strings to entry id mapping. std::vector<int> atom_index_to_id_; // Has the prefilter tree been compiled. bool compiled_; DISALLOW_COPY_AND_ASSIGN(PrefilterTree); }; } // namespace #endif // RE2_PREFILTER_TREE_H_
4,903
35.325926
77
h
openalpr
openalpr-master/src/openalpr/support/re2/prog.h
// Copyright 2007 The RE2 Authors. All Rights Reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Compiled representation of regular expressions. // See regexp.h for the Regexp class, which represents a regular // expression symbolically. #ifndef RE2_PROG_H__ #define RE2_PROG_H__ #include "re2/util/util.h" #include "re2/util/sparse_array.h" #include "re2.h" #include <vector> namespace re2 { // Simple fixed-size bitmap. template<int Bits> class Bitmap { public: Bitmap() { Reset(); } int Size() { return Bits; } void Reset() { for (int i = 0; i < Words; i++) w_[i] = 0; } bool Get(int k) const { return w_[k >> WordLog] & (1<<(k & 31)); } void Set(int k) { w_[k >> WordLog] |= 1<<(k & 31); } void Clear(int k) { w_[k >> WordLog] &= ~(1<<(k & 31)); } uint32 Word(int i) const { return w_[i]; } private: static const int WordLog = 5; static const int Words = (Bits+31)/32; uint32 w_[Words]; DISALLOW_COPY_AND_ASSIGN(Bitmap); }; // Opcodes for Inst enum InstOp { kInstAlt = 0, // choose between out_ and out1_ kInstAltMatch, // Alt: out_ is [00-FF] and back, out1_ is match; or vice versa. kInstByteRange, // next (possible case-folded) byte must be in [lo_, hi_] kInstCapture, // capturing parenthesis number cap_ kInstEmptyWidth, // empty-width special (^ $ ...); bit(s) set in empty_ kInstMatch, // found a match! kInstNop, // no-op; occasionally unavoidable kInstFail, // never match; occasionally unavoidable }; // Bit flags for empty-width specials enum EmptyOp { kEmptyBeginLine = 1<<0, // ^ - beginning of line kEmptyEndLine = 1<<1, // $ - end of line kEmptyBeginText = 1<<2, // \A - beginning of text kEmptyEndText = 1<<3, // \z - end of text kEmptyWordBoundary = 1<<4, // \b - word boundary kEmptyNonWordBoundary = 1<<5, // \B - not \b kEmptyAllFlags = (1<<6)-1, }; class Regexp; class DFA; struct OneState; // Compiled form of regexp program. class Prog { public: Prog(); ~Prog(); // Single instruction in regexp program. class Inst { public: Inst() : out_opcode_(0), out1_(0) { } // Constructors per opcode void InitAlt(uint32 out, uint32 out1); void InitByteRange(int lo, int hi, int foldcase, uint32 out); void InitCapture(int cap, uint32 out); void InitEmptyWidth(EmptyOp empty, uint32 out); void InitMatch(int id); void InitNop(uint32 out); void InitFail(); // Getters int id(Prog* p) { return this - p->inst_; } InstOp opcode() { return static_cast<InstOp>(out_opcode_&7); } int out() { return out_opcode_>>3; } int out1() { DCHECK(opcode() == kInstAlt || opcode() == kInstAltMatch); return out1_; } int cap() { DCHECK_EQ(opcode(), kInstCapture); return cap_; } int lo() { DCHECK_EQ(opcode(), kInstByteRange); return lo_; } int hi() { DCHECK_EQ(opcode(), kInstByteRange); return hi_; } int foldcase() { DCHECK_EQ(opcode(), kInstByteRange); return foldcase_; } int match_id() { DCHECK_EQ(opcode(), kInstMatch); return match_id_; } EmptyOp empty() { DCHECK_EQ(opcode(), kInstEmptyWidth); return empty_; } bool greedy(Prog *p) { DCHECK_EQ(opcode(), kInstAltMatch); return p->inst(out())->opcode() == kInstByteRange; } // Does this inst (an kInstByteRange) match c? inline bool Matches(int c) { DCHECK_EQ(opcode(), kInstByteRange); if (foldcase_ && 'A' <= c && c <= 'Z') c += 'a' - 'A'; return lo_ <= c && c <= hi_; } // Returns string representation for debugging. string Dump(); // Maximum instruction id. // (Must fit in out_opcode_, and PatchList steals another bit.) static const int kMaxInst = (1<<28) - 1; private: void set_opcode(InstOp opcode) { out_opcode_ = (out()<<3) | opcode; } void set_out(int out) { out_opcode_ = (out<<3) | opcode(); } void set_out_opcode(int out, InstOp opcode) { out_opcode_ = (out<<3) | opcode; } uint32 out_opcode_; // 29 bits of out, 3 (low) bits opcode union { // additional instruction arguments: uint32 out1_; // opcode == kInstAlt // alternate next instruction int32 cap_; // opcode == kInstCapture // Index of capture register (holds text // position recorded by capturing parentheses). // For \n (the submatch for the nth parentheses), // the left parenthesis captures into register 2*n // and the right one captures into register 2*n+1. int32 match_id_; // opcode == kInstMatch // Match ID to identify this match (for re2::Set). struct { // opcode == kInstByteRange uint8 lo_; // byte range is lo_-hi_ inclusive uint8 hi_; // uint8 foldcase_; // convert A-Z to a-z before checking range. }; EmptyOp empty_; // opcode == kInstEmptyWidth // empty_ is bitwise OR of kEmpty* flags above. }; friend class Compiler; friend struct PatchList; friend class Prog; DISALLOW_COPY_AND_ASSIGN(Inst); }; // Whether to anchor the search. enum Anchor { kUnanchored, // match anywhere kAnchored, // match only starting at beginning of text }; // Kind of match to look for (for anchor != kFullMatch) // // kLongestMatch mode finds the overall longest // match but still makes its submatch choices the way // Perl would, not in the way prescribed by POSIX. // The POSIX rules are much more expensive to implement, // and no one has needed them. // // kFullMatch is not strictly necessary -- we could use // kLongestMatch and then check the length of the match -- but // the matching code can run faster if it knows to consider only // full matches. enum MatchKind { kFirstMatch, // like Perl, PCRE kLongestMatch, // like egrep or POSIX kFullMatch, // match only entire text; implies anchor==kAnchored kManyMatch // for SearchDFA, records set of matches }; Inst *inst(int id) { return &inst_[id]; } int start() { return start_; } int start_unanchored() { return start_unanchored_; } void set_start(int start) { start_ = start; } void set_start_unanchored(int start) { start_unanchored_ = start; } int64 size() { return size_; } bool reversed() { return reversed_; } void set_reversed(bool reversed) { reversed_ = reversed; } int64 byte_inst_count() { return byte_inst_count_; } const Bitmap<256>& byterange() { return byterange_; } void set_dfa_mem(int64 dfa_mem) { dfa_mem_ = dfa_mem; } int64 dfa_mem() { return dfa_mem_; } int flags() { return flags_; } void set_flags(int flags) { flags_ = flags; } bool anchor_start() { return anchor_start_; } void set_anchor_start(bool b) { anchor_start_ = b; } bool anchor_end() { return anchor_end_; } void set_anchor_end(bool b) { anchor_end_ = b; } int bytemap_range() { return bytemap_range_; } const uint8* bytemap() { return bytemap_; } // Returns string representation of program for debugging. string Dump(); string DumpUnanchored(); // Record that at some point in the prog, the bytes in the range // lo-hi (inclusive) are treated as different from bytes outside the range. // Tracking this lets the DFA collapse commonly-treated byte ranges // when recording state pointers, greatly reducing its memory footprint. void MarkByteRange(int lo, int hi); // Returns the set of kEmpty flags that are in effect at // position p within context. static uint32 EmptyFlags(const StringPiece& context, const char* p); // Returns whether byte c is a word character: ASCII only. // Used by the implementation of \b and \B. // This is not right for Unicode, but: // - it's hard to get right in a byte-at-a-time matching world // (the DFA has only one-byte lookahead). // - even if the lookahead were possible, the Progs would be huge. // This crude approximation is the same one PCRE uses. static bool IsWordChar(uint8 c) { return ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z') || ('0' <= c && c <= '9') || c == '_'; } // Execution engines. They all search for the regexp (run the prog) // in text, which is in the larger context (used for ^ $ \b etc). // Anchor and kind control the kind of search. // Returns true if match found, false if not. // If match found, fills match[0..nmatch-1] with submatch info. // match[0] is overall match, match[1] is first set of parens, etc. // If a particular submatch is not matched during the regexp match, // it is set to NULL. // // Matching text == StringPiece(NULL, 0) is treated as any other empty // string, but note that on return, it will not be possible to distinguish // submatches that matched that empty string from submatches that didn't // match anything. Either way, match[i] == NULL. // Search using NFA: can find submatches but kind of slow. bool SearchNFA(const StringPiece& text, const StringPiece& context, Anchor anchor, MatchKind kind, StringPiece* match, int nmatch); // Search using DFA: much faster than NFA but only finds // end of match and can use a lot more memory. // Returns whether a match was found. // If the DFA runs out of memory, sets *failed to true and returns false. // If matches != NULL and kind == kManyMatch and there is a match, // SearchDFA fills matches with the match IDs of the final matching state. bool SearchDFA(const StringPiece& text, const StringPiece& context, Anchor anchor, MatchKind kind, StringPiece* match0, bool* failed, std::vector<int>* matches); // Build the entire DFA for the given match kind. FOR TESTING ONLY. // Usually the DFA is built out incrementally, as needed, which // avoids lots of unnecessary work. This function is useful only // for testing purposes. Returns number of states. int BuildEntireDFA(MatchKind kind); // Compute byte map. void ComputeByteMap(); // Run peep-hole optimizer on program. void Optimize(); // One-pass NFA: only correct if IsOnePass() is true, // but much faster than NFA (competitive with PCRE) // for those expressions. bool IsOnePass(); bool SearchOnePass(const StringPiece& text, const StringPiece& context, Anchor anchor, MatchKind kind, StringPiece* match, int nmatch); // Bit-state backtracking. Fast on small cases but uses memory // proportional to the product of the program size and the text size. bool SearchBitState(const StringPiece& text, const StringPiece& context, Anchor anchor, MatchKind kind, StringPiece* match, int nmatch); static const int kMaxOnePassCapture = 5; // $0 through $4 // Backtracking search: the gold standard against which the other // implementations are checked. FOR TESTING ONLY. // It allocates a ton of memory to avoid running forever. // It is also recursive, so can't use in production (will overflow stacks). // The name "Unsafe" here is supposed to be a flag that // you should not be using this function. bool UnsafeSearchBacktrack(const StringPiece& text, const StringPiece& context, Anchor anchor, MatchKind kind, StringPiece* match, int nmatch); // Computes range for any strings matching regexp. The min and max can in // some cases be arbitrarily precise, so the caller gets to specify the // maximum desired length of string returned. // // Assuming PossibleMatchRange(&min, &max, N) returns successfully, any // string s that is an anchored match for this regexp satisfies // min <= s && s <= max. // // Note that PossibleMatchRange() will only consider the first copy of an // infinitely repeated element (i.e., any regexp element followed by a '*' or // '+' operator). Regexps with "{N}" constructions are not affected, as those // do not compile down to infinite repetitions. // // Returns true on success, false on error. bool PossibleMatchRange(string* min, string* max, int maxlen); // EXPERIMENTAL! SUBJECT TO CHANGE! // Outputs the program fanout into the given sparse array. void Fanout(SparseArray<int>* fanout); // Compiles a collection of regexps to Prog. Each regexp will have // its own Match instruction recording the index in the vector. static Prog* CompileSet(const RE2::Options& options, RE2::Anchor anchor, Regexp* re); private: friend class Compiler; DFA* GetDFA(MatchKind kind); bool anchor_start_; // regexp has explicit start anchor bool anchor_end_; // regexp has explicit end anchor bool reversed_; // whether program runs backward over input bool did_onepass_; // has IsOnePass been called? int start_; // entry point for program int start_unanchored_; // unanchored entry point for program int size_; // number of instructions int byte_inst_count_; // number of kInstByteRange instructions int bytemap_range_; // bytemap_[x] < bytemap_range_ int flags_; // regexp parse flags int onepass_statesize_; // byte size of each OneState* node Inst* inst_; // pointer to instruction array Mutex dfa_mutex_; // Protects dfa_first_, dfa_longest_ DFA* volatile dfa_first_; // DFA cached for kFirstMatch DFA* volatile dfa_longest_; // DFA cached for kLongestMatch and kFullMatch int64 dfa_mem_; // Maximum memory for DFAs. void (*delete_dfa_)(DFA* dfa); Bitmap<256> byterange_; // byterange.Get(x) true if x ends a // commonly-treated byte range. uint8 bytemap_[256]; // map from input bytes to byte classes uint8 *unbytemap_; // bytemap_[unbytemap_[x]] == x uint8* onepass_nodes_; // data for OnePass nodes OneState* onepass_start_; // start node for OnePass program DISALLOW_COPY_AND_ASSIGN(Prog); }; } // namespace re2 #endif // RE2_PROG_H__
14,531
36.84375
94
h
openalpr
openalpr-master/src/openalpr/support/re2/regexp.h
// Copyright 2006 The RE2 Authors. All Rights Reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // --- SPONSORED LINK -------------------------------------------------- // If you want to use this library for regular expression matching, // you should use re2/re2.h, which provides a class RE2 that // mimics the PCRE interface provided by PCRE's C++ wrappers. // This header describes the low-level interface used to implement RE2 // and may change in backwards-incompatible ways from time to time. // In contrast, RE2's interface will not. // --------------------------------------------------------------------- // Regular expression library: parsing, execution, and manipulation // of regular expressions. // // Any operation that traverses the Regexp structures should be written // using Regexp::Walker (see walker-inl.h), not recursively, because deeply nested // regular expressions such as x++++++++++++++++++++... might cause recursive // traversals to overflow the stack. // // It is the caller's responsibility to provide appropriate mutual exclusion // around manipulation of the regexps. RE2 does this. // // PARSING // // Regexp::Parse parses regular expressions encoded in UTF-8. // The default syntax is POSIX extended regular expressions, // with the following changes: // // 1. Backreferences (optional in POSIX EREs) are not supported. // (Supporting them precludes the use of DFA-based // matching engines.) // // 2. Collating elements and collation classes are not supported. // (No one has needed or wanted them.) // // The exact syntax accepted can be modified by passing flags to // Regexp::Parse. In particular, many of the basic Perl additions // are available. The flags are documented below (search for LikePerl). // // If parsed with the flag Regexp::Latin1, both the regular expression // and the input to the matching routines are assumed to be encoded in // Latin-1, not UTF-8. // // EXECUTION // // Once Regexp has parsed a regular expression, it provides methods // to search text using that regular expression. These methods are // implemented via calling out to other regular expression libraries. // (Let's call them the sublibraries.) // // To call a sublibrary, Regexp does not simply prepare a // string version of the regular expression and hand it to the // sublibrary. Instead, Regexp prepares, from its own parsed form, the // corresponding internal representation used by the sublibrary. // This has the drawback of needing to know the internal representation // used by the sublibrary, but it has two important benefits: // // 1. The syntax and meaning of regular expressions is guaranteed // to be that used by Regexp's parser, not the syntax expected // by the sublibrary. Regexp might accept a restricted or // expanded syntax for regular expressions as compared with // the sublibrary. As long as Regexp can translate from its // internal form into the sublibrary's, clients need not know // exactly which sublibrary they are using. // // 2. The sublibrary parsers are bypassed. For whatever reason, // sublibrary regular expression parsers often have security // problems. For example, plan9grep's regular expression parser // has a buffer overflow in its handling of large character // classes, and PCRE's parser has had buffer overflow problems // in the past. Security-team requires sandboxing of sublibrary // regular expression parsers. Avoiding the sublibrary parsers // avoids the sandbox. // // The execution methods we use now are provided by the compiled form, // Prog, described in prog.h // // MANIPULATION // // Unlike other regular expression libraries, Regexp makes its parsed // form accessible to clients, so that client code can analyze the // parsed regular expressions. #ifndef RE2_REGEXP_H__ #define RE2_REGEXP_H__ #include <map> #include <set> #include "util/util.h" #include "re2/stringpiece.h" namespace re2 { // Keep in sync with string list kOpcodeNames[] in testing/dump.cc enum RegexpOp { // Matches no strings. kRegexpNoMatch = 1, // Matches empty string. kRegexpEmptyMatch, // Matches rune_. kRegexpLiteral, // Matches runes_. kRegexpLiteralString, // Matches concatenation of sub_[0..nsub-1]. kRegexpConcat, // Matches union of sub_[0..nsub-1]. kRegexpAlternate, // Matches sub_[0] zero or more times. kRegexpStar, // Matches sub_[0] one or more times. kRegexpPlus, // Matches sub_[0] zero or one times. kRegexpQuest, // Matches sub_[0] at least min_ times, at most max_ times. // max_ == -1 means no upper limit. kRegexpRepeat, // Parenthesized (capturing) subexpression. Index is cap_. // Optionally, capturing name is name_. kRegexpCapture, // Matches any character. kRegexpAnyChar, // Matches any byte [sic]. kRegexpAnyByte, // Matches empty string at beginning of line. kRegexpBeginLine, // Matches empty string at end of line. kRegexpEndLine, // Matches word boundary "\b". kRegexpWordBoundary, // Matches not-a-word boundary "\B". kRegexpNoWordBoundary, // Matches empty string at beginning of text. kRegexpBeginText, // Matches empty string at end of text. kRegexpEndText, // Matches character class given by cc_. kRegexpCharClass, // Forces match of entire expression right now, // with match ID match_id_ (used by RE2::Set). kRegexpHaveMatch, kMaxRegexpOp = kRegexpHaveMatch, }; // Keep in sync with string list in regexp.cc enum RegexpStatusCode { // No error kRegexpSuccess = 0, // Unexpected error kRegexpInternalError, // Parse errors kRegexpBadEscape, // bad escape sequence kRegexpBadCharClass, // bad character class kRegexpBadCharRange, // bad character class range kRegexpMissingBracket, // missing closing ] kRegexpMissingParen, // missing closing ) kRegexpTrailingBackslash, // at end of regexp kRegexpRepeatArgument, // repeat argument missing, e.g. "*" kRegexpRepeatSize, // bad repetition argument kRegexpRepeatOp, // bad repetition operator kRegexpBadPerlOp, // bad perl operator kRegexpBadUTF8, // invalid UTF-8 in regexp kRegexpBadNamedCapture, // bad named capture }; // Error status for certain operations. class RegexpStatus { public: RegexpStatus() : code_(kRegexpSuccess), tmp_(NULL) {} ~RegexpStatus() { delete tmp_; } void set_code(enum RegexpStatusCode code) { code_ = code; } void set_error_arg(const StringPiece& error_arg) { error_arg_ = error_arg; } void set_tmp(std::string* tmp) { delete tmp_; tmp_ = tmp; } enum RegexpStatusCode code() const { return code_; } const StringPiece& error_arg() const { return error_arg_; } bool ok() const { return code() == kRegexpSuccess; } // Copies state from status. void Copy(const RegexpStatus& status); // Returns text equivalent of code, e.g.: // "Bad character class" static std::string CodeText(enum RegexpStatusCode code); // Returns text describing error, e.g.: // "Bad character class: [z-a]" std::string Text() const; private: enum RegexpStatusCode code_; // Kind of error StringPiece error_arg_; // Piece of regexp containing syntax error. std::string* tmp_; // Temporary storage, possibly where error_arg_ is. DISALLOW_COPY_AND_ASSIGN(RegexpStatus); }; // Walker to implement Simplify. class SimplifyWalker; // Compiled form; see prog.h class Prog; struct RuneRange { RuneRange() : lo(0), hi(0) { } RuneRange(int l, int h) : lo(l), hi(h) { } Rune lo; Rune hi; }; // Less-than on RuneRanges treats a == b if they overlap at all. // This lets us look in a set to find the range covering a particular Rune. struct RuneRangeLess { bool operator()(const RuneRange& a, const RuneRange& b) const { return a.hi < b.lo; } }; class CharClassBuilder; class CharClass { public: void Delete(); typedef RuneRange* iterator; iterator begin() { return ranges_; } iterator end() { return ranges_ + nranges_; } int size() { return nrunes_; } bool empty() { return nrunes_ == 0; } bool full() { return nrunes_ == Runemax+1; } bool FoldsASCII() { return folds_ascii_; } bool Contains(Rune r); CharClass* Negate(); private: CharClass(); // not implemented ~CharClass(); // not implemented static CharClass* New(int maxranges); friend class CharClassBuilder; bool folds_ascii_; int nrunes_; RuneRange *ranges_; int nranges_; DISALLOW_COPY_AND_ASSIGN(CharClass); }; class Regexp { public: // Flags for parsing. Can be ORed together. enum ParseFlags { NoParseFlags = 0, FoldCase = 1<<0, // Fold case during matching (case-insensitive). Literal = 1<<1, // Treat s as literal string instead of a regexp. ClassNL = 1<<2, // Allow char classes like [^a-z] and \D and \s // and [[:space:]] to match newline. DotNL = 1<<3, // Allow . to match newline. MatchNL = ClassNL | DotNL, OneLine = 1<<4, // Treat ^ and $ as only matching at beginning and // end of text, not around embedded newlines. // (Perl's default) Latin1 = 1<<5, // Regexp and text are in Latin1, not UTF-8. NonGreedy = 1<<6, // Repetition operators are non-greedy by default. PerlClasses = 1<<7, // Allow Perl character classes like \d. PerlB = 1<<8, // Allow Perl's \b and \B. PerlX = 1<<9, // Perl extensions: // non-capturing parens - (?: ) // non-greedy operators - *? +? ?? {}? // flag edits - (?i) (?-i) (?i: ) // i - FoldCase // m - !OneLine // s - DotNL // U - NonGreedy // line ends: \A \z // \Q and \E to disable/enable metacharacters // (?P<name>expr) for named captures // \C to match any single byte UnicodeGroups = 1<<10, // Allow \p{Han} for Unicode Han group // and \P{Han} for its negation. NeverNL = 1<<11, // Never match NL, even if the regexp mentions // it explicitly. NeverCapture = 1<<12, // Parse all parens as non-capturing. // As close to Perl as we can get. LikePerl = ClassNL | OneLine | PerlClasses | PerlB | PerlX | UnicodeGroups, // Internal use only. WasDollar = 1<<15, // on kRegexpEndText: was $ in regexp text }; // Get. No set, Regexps are logically immutable once created. RegexpOp op() { return static_cast<RegexpOp>(op_); } int nsub() { return nsub_; } bool simple() { return simple_; } enum ParseFlags parse_flags() { return static_cast<ParseFlags>(parse_flags_); } int Ref(); // For testing. Regexp** sub() { if(nsub_ <= 1) return &subone_; else return submany_; } int min() { DCHECK_EQ(op_, kRegexpRepeat); return min_; } int max() { DCHECK_EQ(op_, kRegexpRepeat); return max_; } Rune rune() { DCHECK_EQ(op_, kRegexpLiteral); return rune_; } CharClass* cc() { DCHECK_EQ(op_, kRegexpCharClass); return cc_; } int cap() { DCHECK_EQ(op_, kRegexpCapture); return cap_; } const std::string* name() { DCHECK_EQ(op_, kRegexpCapture); return name_; } Rune* runes() { DCHECK_EQ(op_, kRegexpLiteralString); return runes_; } int nrunes() { DCHECK_EQ(op_, kRegexpLiteralString); return nrunes_; } int match_id() { DCHECK_EQ(op_, kRegexpHaveMatch); return match_id_; } // Increments reference count, returns object as convenience. Regexp* Incref(); // Decrements reference count and deletes this object if count reaches 0. void Decref(); // Parses string s to produce regular expression, returned. // Caller must release return value with re->Decref(). // On failure, sets *status (if status != NULL) and returns NULL. static Regexp* Parse(const StringPiece& s, ParseFlags flags, RegexpStatus* status); // Returns a _new_ simplified version of the current regexp. // Does not edit the current regexp. // Caller must release return value with re->Decref(). // Simplified means that counted repetition has been rewritten // into simpler terms and all Perl/POSIX features have been // removed. The result will capture exactly the same // subexpressions the original did, unless formatted with ToString. Regexp* Simplify(); friend class SimplifyWalker; // Parses the regexp src and then simplifies it and sets *dst to the // string representation of the simplified form. Returns true on success. // Returns false and sets *status (if status != NULL) on parse error. static bool SimplifyRegexp(const StringPiece& src, ParseFlags flags, std::string* dst, RegexpStatus* status); // Returns the number of capturing groups in the regexp. int NumCaptures(); friend class NumCapturesWalker; // Returns a map from names to capturing group indices, // or NULL if the regexp contains no named capture groups. // The caller is responsible for deleting the map. std::map<std::string, int>* NamedCaptures(); // Returns a map from capturing group indices to capturing group // names or NULL if the regexp contains no named capture groups. The // caller is responsible for deleting the map. std::map<int, std::string>* CaptureNames(); // Returns a string representation of the current regexp, // using as few parentheses as possible. std::string ToString(); // Convenience functions. They consume the passed reference, // so in many cases you should use, e.g., Plus(re->Incref(), flags). // They do not consume allocated arrays like subs or runes. static Regexp* Plus(Regexp* sub, ParseFlags flags); static Regexp* Star(Regexp* sub, ParseFlags flags); static Regexp* Quest(Regexp* sub, ParseFlags flags); static Regexp* Concat(Regexp** subs, int nsubs, ParseFlags flags); static Regexp* Alternate(Regexp** subs, int nsubs, ParseFlags flags); static Regexp* Capture(Regexp* sub, ParseFlags flags, int cap); static Regexp* Repeat(Regexp* sub, ParseFlags flags, int min, int max); static Regexp* NewLiteral(Rune rune, ParseFlags flags); static Regexp* NewCharClass(CharClass* cc, ParseFlags flags); static Regexp* LiteralString(Rune* runes, int nrunes, ParseFlags flags); static Regexp* HaveMatch(int match_id, ParseFlags flags); // Like Alternate but does not factor out common prefixes. static Regexp* AlternateNoFactor(Regexp** subs, int nsubs, ParseFlags flags); // Debugging function. Returns string format for regexp // that makes structure clear. Does NOT use regexp syntax. std::string Dump(); // Helper traversal class, defined fully in walker-inl.h. template<typename T> class Walker; // Compile to Prog. See prog.h // Reverse prog expects to be run over text backward. // Construction and execution of prog will // stay within approximately max_mem bytes of memory. // If max_mem <= 0, a reasonable default is used. Prog* CompileToProg(int64 max_mem); Prog* CompileToReverseProg(int64 max_mem); // Whether to expect this library to find exactly the same answer as PCRE // when running this regexp. Most regexps do mimic PCRE exactly, but a few // obscure cases behave differently. Technically this is more a property // of the Prog than the Regexp, but the computation is much easier to do // on the Regexp. See mimics_pcre.cc for the exact conditions. bool MimicsPCRE(); // Benchmarking function. void NullWalk(); // Whether every match of this regexp must be anchored and // begin with a non-empty fixed string (perhaps after ASCII // case-folding). If so, returns the prefix and the sub-regexp that // follows it. bool RequiredPrefix(std::string* prefix, bool *foldcase, Regexp** suffix); private: // Constructor allocates vectors as appropriate for operator. explicit Regexp(RegexpOp op, ParseFlags parse_flags); // Use Decref() instead of delete to release Regexps. // This is private to catch deletes at compile time. ~Regexp(); void Destroy(); bool QuickDestroy(); // Helpers for Parse. Listed here so they can edit Regexps. class ParseState; friend class ParseState; friend bool ParseCharClass(StringPiece* s, Regexp** out_re, RegexpStatus* status); // Helper for testing [sic]. friend bool RegexpEqualTestingOnly(Regexp*, Regexp*); // Computes whether Regexp is already simple. bool ComputeSimple(); // Constructor that generates a concatenation or alternation, // enforcing the limit on the number of subexpressions for // a particular Regexp. static Regexp* ConcatOrAlternate(RegexpOp op, Regexp** subs, int nsubs, ParseFlags flags, bool can_factor); // Returns the leading string that re starts with. // The returned Rune* points into a piece of re, // so it must not be used after the caller calls re->Decref(). static Rune* LeadingString(Regexp* re, int* nrune, ParseFlags* flags); // Removes the first n leading runes from the beginning of re. // Edits re in place. static void RemoveLeadingString(Regexp* re, int n); // Returns the leading regexp in re's top-level concatenation. // The returned Regexp* points at re or a sub-expression of re, // so it must not be used after the caller calls re->Decref(). static Regexp* LeadingRegexp(Regexp* re); // Removes LeadingRegexp(re) from re and returns the remainder. // Might edit re in place. static Regexp* RemoveLeadingRegexp(Regexp* re); // Simplifies an alternation of literal strings by factoring out // common prefixes. static int FactorAlternation(Regexp** sub, int nsub, ParseFlags flags); static int FactorAlternationRecursive(Regexp** sub, int nsub, ParseFlags flags, int maxdepth); // Is a == b? Only efficient on regexps that have not been through // Simplify yet - the expansion of a kRegexpRepeat will make this // take a long time. Do not call on such regexps, hence private. static bool Equal(Regexp* a, Regexp* b); // Allocate space for n sub-regexps. void AllocSub(int n) { if (n < 0 || static_cast<uint16>(n) != n) LOG(FATAL) << "Cannot AllocSub " << n; if (n > 1) submany_ = new Regexp*[n]; nsub_ = n; } // Add Rune to LiteralString void AddRuneToString(Rune r); // Swaps this with that, in place. void Swap(Regexp *that); // Operator. See description of operators above. // uint8 instead of RegexpOp to control space usage. uint8 op_; // Is this regexp structure already simple // (has it been returned by Simplify)? // uint8 instead of bool to control space usage. uint8 simple_; // Flags saved from parsing and used during execution. // (Only FoldCase is used.) // uint16 instead of ParseFlags to control space usage. uint16 parse_flags_; // Reference count. Exists so that SimplifyRegexp can build // regexp structures that are dags rather than trees to avoid // exponential blowup in space requirements. // uint16 to control space usage. // The standard regexp routines will never generate a // ref greater than the maximum repeat count (100), // but even so, Incref and Decref consult an overflow map // when ref_ reaches kMaxRef. uint16 ref_; static const uint16 kMaxRef = 0xffff; // Subexpressions. // uint16 to control space usage. // Concat and Alternate handle larger numbers of subexpressions // by building concatenation or alternation trees. // Other routines should call Concat or Alternate instead of // filling in sub() by hand. uint16 nsub_; static const uint16 kMaxNsub = 0xffff; union { Regexp** submany_; // if nsub_ > 1 Regexp* subone_; // if nsub_ == 1 }; // Extra space for parse and teardown stacks. Regexp* down_; // Arguments to operator. See description of operators above. union { struct { // Repeat int max_; int min_; }; struct { // Capture int cap_; std::string* name_; }; struct { // LiteralString int nrunes_; Rune* runes_; }; struct { // CharClass // These two could be in separate union members, // but it wouldn't save any space (there are other two-word structs) // and keeping them separate avoids confusion during parsing. CharClass* cc_; CharClassBuilder* ccb_; }; Rune rune_; // Literal int match_id_; // HaveMatch void *the_union_[2]; // as big as any other element, for memset }; DISALLOW_COPY_AND_ASSIGN(Regexp); }; // Character class set: contains non-overlapping, non-abutting RuneRanges. typedef std::set<RuneRange, RuneRangeLess> RuneRangeSet; class CharClassBuilder { public: CharClassBuilder(); typedef RuneRangeSet::iterator iterator; iterator begin() { return ranges_.begin(); } iterator end() { return ranges_.end(); } int size() { return nrunes_; } bool empty() { return nrunes_ == 0; } bool full() { return nrunes_ == Runemax+1; } bool Contains(Rune r); bool FoldsASCII(); bool AddRange(Rune lo, Rune hi); // returns whether class changed CharClassBuilder* Copy(); void AddCharClass(CharClassBuilder* cc); void Negate(); void RemoveAbove(Rune r); CharClass* GetCharClass(); void AddRangeFlags(Rune lo, Rune hi, Regexp::ParseFlags parse_flags); private: static const uint32 AlphaMask = (1<<26) - 1; uint32 upper_; // bitmap of A-Z uint32 lower_; // bitmap of a-z int nrunes_; RuneRangeSet ranges_; DISALLOW_COPY_AND_ASSIGN(CharClassBuilder); }; // Tell g++ that bitwise ops on ParseFlags produce ParseFlags. inline Regexp::ParseFlags operator|(Regexp::ParseFlags a, Regexp::ParseFlags b) { return static_cast<Regexp::ParseFlags>(static_cast<int>(a) | static_cast<int>(b)); } inline Regexp::ParseFlags operator^(Regexp::ParseFlags a, Regexp::ParseFlags b) { return static_cast<Regexp::ParseFlags>(static_cast<int>(a) ^ static_cast<int>(b)); } inline Regexp::ParseFlags operator&(Regexp::ParseFlags a, Regexp::ParseFlags b) { return static_cast<Regexp::ParseFlags>(static_cast<int>(a) & static_cast<int>(b)); } inline Regexp::ParseFlags operator~(Regexp::ParseFlags a) { return static_cast<Regexp::ParseFlags>(~static_cast<int>(a)); } } // namespace re2 #endif // RE2_REGEXP_H__
22,800
34.794349
88
h
openalpr
openalpr-master/src/openalpr/support/re2/set.h
// Copyright 2010 The RE2 Authors. All Rights Reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #ifndef RE2_SET_H #define RE2_SET_H #include <utility> #include <vector> #include "re2.h" namespace re2 { using std::vector; // An RE2::Set represents a collection of regexps that can // be searched for simultaneously. class RE2::Set { public: Set(const RE2::Options& options, RE2::Anchor anchor); ~Set(); // Add adds regexp pattern to the set, interpreted using the RE2 options. // (The RE2 constructor's default options parameter is RE2::UTF8.) // Add returns the regexp index that will be used to identify // it in the result of Match, or -1 if the regexp cannot be parsed. // Indices are assigned in sequential order starting from 0. // Error returns do not increment the index. // If an error occurs and error != NULL, *error will hold an error message. int Add(const StringPiece& pattern, string* error); // Compile prepares the Set for matching. // Add must not be called again after Compile. // Compile must be called before FullMatch or PartialMatch. // Compile may return false if it runs out of memory. bool Compile(); // Match returns true if text matches any of the regexps in the set. // If so, it fills v with the indices of the matching regexps. bool Match(const StringPiece& text, vector<int>* v) const; private: RE2::Options options_; RE2::Anchor anchor_; vector<re2::Regexp*> re_; re2::Prog* prog_; bool compiled_; //DISALLOW_COPY_AND_ASSIGN(Set); Set(const Set&); void operator=(const Set&); }; } // namespace re2 #endif // RE2_SET_H
1,682
29.053571
77
h
openalpr
openalpr-master/src/openalpr/support/re2/stringpiece.h
// Copyright 2001-2010 The RE2 Authors. All Rights Reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // A string-like object that points to a sized piece of memory. // // Functions or methods may use const StringPiece& parameters to accept either // a "const char*" or a "string" value that will be implicitly converted to // a StringPiece. The implicit conversion means that it is often appropriate // to include this .h file in other files rather than forward-declaring // StringPiece as would be appropriate for most other Google classes. // // Systematic usage of StringPiece is encouraged as it will reduce unnecessary // conversions from "const char*" to "string" and back again. // // // Arghh! I wish C++ literals were "string". #ifndef STRINGS_STRINGPIECE_H__ #define STRINGS_STRINGPIECE_H__ #include <string.h> #include <algorithm> #include <cstddef> #include <iosfwd> #include <string> namespace re2 { class StringPiece { private: const char* ptr_; int length_; public: // We provide non-explicit singleton constructors so users can pass // in a "const char*" or a "string" wherever a "StringPiece" is // expected. StringPiece() : ptr_(NULL), length_(0) { } StringPiece(const char* str) : ptr_(str), length_((str == NULL) ? 0 : static_cast<int>(strlen(str))) { } StringPiece(const std::string& str) : ptr_(str.data()), length_(static_cast<int>(str.size())) { } StringPiece(const char* offset, int len) : ptr_(offset), length_(len) { } // data() may return a pointer to a buffer with embedded NULs, and the // returned buffer may or may not be null terminated. Therefore it is // typically a mistake to pass data() to a routine that expects a NUL // terminated string. const char* data() const { return ptr_; } int size() const { return length_; } int length() const { return length_; } bool empty() const { return length_ == 0; } void clear() { ptr_ = NULL; length_ = 0; } void set(const char* data, int len) { ptr_ = data; length_ = len; } void set(const char* str) { ptr_ = str; if (str != NULL) length_ = static_cast<int>(strlen(str)); else length_ = 0; } void set(const void* data, int len) { ptr_ = reinterpret_cast<const char*>(data); length_ = len; } char operator[](int i) const { return ptr_[i]; } void remove_prefix(int n) { ptr_ += n; length_ -= n; } void remove_suffix(int n) { length_ -= n; } int compare(const StringPiece& x) const { int r = memcmp(ptr_, x.ptr_, std::min(length_, x.length_)); if (r == 0) { if (length_ < x.length_) r = -1; else if (length_ > x.length_) r = +1; } return r; } std::string as_string() const { return std::string(data(), size()); } // We also define ToString() here, since many other string-like // interfaces name the routine that converts to a C++ string // "ToString", and it's confusing to have the method that does that // for a StringPiece be called "as_string()". We also leave the // "as_string()" method defined here for existing code. std::string ToString() const { return std::string(data(), size()); } void CopyToString(std::string* target) const; void AppendToString(std::string* target) const; // Does "this" start with "x" bool starts_with(const StringPiece& x) const { return ((length_ >= x.length_) && (memcmp(ptr_, x.ptr_, x.length_) == 0)); } // Does "this" end with "x" bool ends_with(const StringPiece& x) const { return ((length_ >= x.length_) && (memcmp(ptr_ + (length_-x.length_), x.ptr_, x.length_) == 0)); } // standard STL container boilerplate typedef char value_type; typedef const char* pointer; typedef const char& reference; typedef const char& const_reference; typedef size_t size_type; typedef ptrdiff_t difference_type; static const size_type npos; typedef const char* const_iterator; typedef const char* iterator; typedef std::reverse_iterator<const_iterator> const_reverse_iterator; typedef std::reverse_iterator<iterator> reverse_iterator; iterator begin() const { return ptr_; } iterator end() const { return ptr_ + length_; } const_reverse_iterator rbegin() const { return const_reverse_iterator(ptr_ + length_); } const_reverse_iterator rend() const { return const_reverse_iterator(ptr_); } // STLS says return size_type, but Google says return int int max_size() const { return length_; } int capacity() const { return length_; } int copy(char* buf, size_type n, size_type pos = 0) const; bool contains(StringPiece s) const; int find(const StringPiece& s, size_type pos = 0) const; int find(char c, size_type pos = 0) const; int rfind(const StringPiece& s, size_type pos = npos) const; int rfind(char c, size_type pos = npos) const; StringPiece substr(size_type pos, size_type n = npos) const; static bool _equal(const StringPiece&, const StringPiece&); }; inline bool operator==(const StringPiece& x, const StringPiece& y) { return StringPiece::_equal(x, y); } inline bool operator!=(const StringPiece& x, const StringPiece& y) { return !(x == y); } inline bool operator<(const StringPiece& x, const StringPiece& y) { const int r = memcmp(x.data(), y.data(), std::min(x.size(), y.size())); return ((r < 0) || ((r == 0) && (x.size() < y.size()))); } inline bool operator>(const StringPiece& x, const StringPiece& y) { return y < x; } inline bool operator<=(const StringPiece& x, const StringPiece& y) { return !(x > y); } inline bool operator>=(const StringPiece& x, const StringPiece& y) { return !(x < y); } } // namespace re2 // allow StringPiece to be logged extern std::ostream& operator<<(std::ostream& o, const re2::StringPiece& piece); #endif // STRINGS_STRINGPIECE_H__
5,911
30.784946
80
h
openalpr
openalpr-master/src/openalpr/support/re2/unicode_casefold.h
// Copyright 2008 The RE2 Authors. All Rights Reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Unicode case folding tables. // The Unicode case folding tables encode the mapping from one Unicode point // to the next largest Unicode point with equivalent folding. The largest // point wraps back to the first. For example, the tables map: // // 'A' -> 'a' // 'a' -> 'A' // // 'K' -> 'k' // 'k' -> 'K' (Kelvin symbol) // 'K' -> 'K' // // Like everything Unicode, these tables are big. If we represent the table // as a sorted list of uint32 pairs, it has 2049 entries and is 16 kB. // Most table entries look like the ones around them: // 'A' maps to 'A'+32, 'B' maps to 'B'+32, etc. // Instead of listing all the pairs explicitly, we make a list of ranges // and deltas, so that the table entries for 'A' through 'Z' can be represented // as a single entry { 'A', 'Z', +32 }. // // In addition to blocks that map to each other (A-Z mapping to a-z) // there are blocks of pairs that individually map to each other // (for example, 0100<->0101, 0102<->0103, 0104<->0105, ...). // For those, the special delta value EvenOdd marks even/odd pairs // (if even, add 1; if odd, subtract 1), and OddEven marks odd/even pairs. // // In this form, the table has 274 entries, about 3kB. If we were to split // the table into one for 16-bit codes and an overflow table for larger ones, // we could get it down to about 1.5kB, but that's not worth the complexity. // // The grouped form also allows for efficient fold range calculations // rather than looping one character at a time. #ifndef RE2_UNICODE_CASEFOLD_H__ #define RE2_UNICODE_CASEFOLD_H__ #include "util/util.h" namespace re2 { enum { EvenOdd = 1, OddEven = -1, EvenOddSkip = 1<<30, OddEvenSkip, }; struct CaseFold { Rune lo; Rune hi; int32 delta; }; extern const CaseFold unicode_casefold[]; extern const int num_unicode_casefold; extern const CaseFold unicode_tolower[]; extern const int num_unicode_tolower; // Returns the CaseFold* in the tables that contains rune. // If rune is not in the tables, returns the first CaseFold* after rune. // If rune is larger than any value in the tables, returns NULL. extern const CaseFold* LookupCaseFold(const CaseFold*, int, Rune rune); // Returns the result of applying the fold f to the rune r. extern Rune ApplyFold(const CaseFold *f, Rune r); } // namespace re2 #endif // RE2_UNICODE_CASEFOLD_H__
2,514
32.092105
79
h
openalpr
openalpr-master/src/openalpr/support/re2/unicode_groups.h
// Copyright 2008 The RE2 Authors. All Rights Reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Unicode character groups. // The codes get split into ranges of 16-bit codes // and ranges of 32-bit codes. It would be simpler // to use only 32-bit ranges, but these tables are large // enough to warrant extra care. // // Using just 32-bit ranges gives 27 kB of data. // Adding 16-bit ranges gives 18 kB of data. // Adding an extra table of 16-bit singletons would reduce // to 16.5 kB of data but make the data harder to use; // we don't bother. #ifndef RE2_UNICODE_GROUPS_H__ #define RE2_UNICODE_GROUPS_H__ #include "util/util.h" namespace re2 { struct URange16 { uint16 lo; uint16 hi; }; struct URange32 { Rune lo; Rune hi; }; struct UGroup { const char *name; int sign; // +1 for [abc], -1 for [^abc] const URange16 *r16; int nr16; const URange32 *r32; int nr32; }; // Named by property or script name (e.g., "Nd", "N", "Han"). // Negated groups are not included. extern const UGroup unicode_groups[]; extern const int num_unicode_groups; // Named by POSIX name (e.g., "[:alpha:]", "[:^lower:]"). // Negated groups are included. extern const UGroup posix_groups[]; extern const int num_posix_groups; // Named by Perl name (e.g., "\\d", "\\D"). // Negated groups are included. extern const UGroup perl_groups[]; extern const int num_perl_groups; } // namespace re2 #endif // RE2_UNICODE_GROUPS_H__
1,504
22.153846
61
h
openalpr
openalpr-master/src/openalpr/support/re2/variadic_function.h
// Copyright 2010 The RE2 Authors. All Rights Reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #ifndef RE2_VARIADIC_FUNCTION_H_ #define RE2_VARIADIC_FUNCTION_H_ namespace re2 { template <typename Result, typename Param0, typename Param1, typename Arg, Result (*Func)(Param0, Param1, const Arg* const [], int count)> class VariadicFunction2 { public: Result operator()(Param0 p0, Param1 p1) const { return Func(p0, p1, 0, 0); } Result operator()(Param0 p0, Param1 p1, const Arg& a0) const { const Arg* const args[] = { &a0 }; return Func(p0, p1, args, 1); } Result operator()(Param0 p0, Param1 p1, const Arg& a0, const Arg& a1) const { const Arg* const args[] = { &a0, &a1 }; return Func(p0, p1, args, 2); } Result operator()(Param0 p0, Param1 p1, const Arg& a0, const Arg& a1, const Arg& a2) const { const Arg* const args[] = { &a0, &a1, &a2 }; return Func(p0, p1, args, 3); } Result operator()(Param0 p0, Param1 p1, const Arg& a0, const Arg& a1, const Arg& a2, const Arg& a3) const { const Arg* const args[] = { &a0, &a1, &a2, &a3 }; return Func(p0, p1, args, 4); } Result operator()(Param0 p0, Param1 p1, const Arg& a0, const Arg& a1, const Arg& a2, const Arg& a3, const Arg& a4) const { const Arg* const args[] = { &a0, &a1, &a2, &a3, &a4 }; return Func(p0, p1, args, 5); } Result operator()(Param0 p0, Param1 p1, const Arg& a0, const Arg& a1, const Arg& a2, const Arg& a3, const Arg& a4, const Arg& a5) const { const Arg* const args[] = { &a0, &a1, &a2, &a3, &a4, &a5 }; return Func(p0, p1, args, 6); } Result operator()(Param0 p0, Param1 p1, const Arg& a0, const Arg& a1, const Arg& a2, const Arg& a3, const Arg& a4, const Arg& a5, const Arg& a6) const { const Arg* const args[] = { &a0, &a1, &a2, &a3, &a4, &a5, &a6 }; return Func(p0, p1, args, 7); } Result operator()(Param0 p0, Param1 p1, const Arg& a0, const Arg& a1, const Arg& a2, const Arg& a3, const Arg& a4, const Arg& a5, const Arg& a6, const Arg& a7) const { const Arg* const args[] = { &a0, &a1, &a2, &a3, &a4, &a5, &a6, &a7 }; return Func(p0, p1, args, 8); } Result operator()(Param0 p0, Param1 p1, const Arg& a0, const Arg& a1, const Arg& a2, const Arg& a3, const Arg& a4, const Arg& a5, const Arg& a6, const Arg& a7, const Arg& a8) const { const Arg* const args[] = { &a0, &a1, &a2, &a3, &a4, &a5, &a6, &a7, &a8 }; return Func(p0, p1, args, 9); } Result operator()(Param0 p0, Param1 p1, const Arg& a0, const Arg& a1, const Arg& a2, const Arg& a3, const Arg& a4, const Arg& a5, const Arg& a6, const Arg& a7, const Arg& a8, const Arg& a9) const { const Arg* const args[] = { &a0, &a1, &a2, &a3, &a4, &a5, &a6, &a7, &a8, &a9 }; return Func(p0, p1, args, 10); } Result operator()(Param0 p0, Param1 p1, const Arg& a0, const Arg& a1, const Arg& a2, const Arg& a3, const Arg& a4, const Arg& a5, const Arg& a6, const Arg& a7, const Arg& a8, const Arg& a9, const Arg& a10) const { const Arg* const args[] = { &a0, &a1, &a2, &a3, &a4, &a5, &a6, &a7, &a8, &a9, &a10 }; return Func(p0, p1, args, 11); } Result operator()(Param0 p0, Param1 p1, const Arg& a0, const Arg& a1, const Arg& a2, const Arg& a3, const Arg& a4, const Arg& a5, const Arg& a6, const Arg& a7, const Arg& a8, const Arg& a9, const Arg& a10, const Arg& a11) const { const Arg* const args[] = { &a0, &a1, &a2, &a3, &a4, &a5, &a6, &a7, &a8, &a9, &a10, &a11 }; return Func(p0, p1, args, 12); } Result operator()(Param0 p0, Param1 p1, const Arg& a0, const Arg& a1, const Arg& a2, const Arg& a3, const Arg& a4, const Arg& a5, const Arg& a6, const Arg& a7, const Arg& a8, const Arg& a9, const Arg& a10, const Arg& a11, const Arg& a12) const { const Arg* const args[] = { &a0, &a1, &a2, &a3, &a4, &a5, &a6, &a7, &a8, &a9, &a10, &a11, &a12 }; return Func(p0, p1, args, 13); } Result operator()(Param0 p0, Param1 p1, const Arg& a0, const Arg& a1, const Arg& a2, const Arg& a3, const Arg& a4, const Arg& a5, const Arg& a6, const Arg& a7, const Arg& a8, const Arg& a9, const Arg& a10, const Arg& a11, const Arg& a12, const Arg& a13) const { const Arg* const args[] = { &a0, &a1, &a2, &a3, &a4, &a5, &a6, &a7, &a8, &a9, &a10, &a11, &a12, &a13 }; return Func(p0, p1, args, 14); } Result operator()(Param0 p0, Param1 p1, const Arg& a0, const Arg& a1, const Arg& a2, const Arg& a3, const Arg& a4, const Arg& a5, const Arg& a6, const Arg& a7, const Arg& a8, const Arg& a9, const Arg& a10, const Arg& a11, const Arg& a12, const Arg& a13, const Arg& a14) const { const Arg* const args[] = { &a0, &a1, &a2, &a3, &a4, &a5, &a6, &a7, &a8, &a9, &a10, &a11, &a12, &a13, &a14 }; return Func(p0, p1, args, 15); } Result operator()(Param0 p0, Param1 p1, const Arg& a0, const Arg& a1, const Arg& a2, const Arg& a3, const Arg& a4, const Arg& a5, const Arg& a6, const Arg& a7, const Arg& a8, const Arg& a9, const Arg& a10, const Arg& a11, const Arg& a12, const Arg& a13, const Arg& a14, const Arg& a15) const { const Arg* const args[] = { &a0, &a1, &a2, &a3, &a4, &a5, &a6, &a7, &a8, &a9, &a10, &a11, &a12, &a13, &a14, &a15 }; return Func(p0, p1, args, 16); } Result operator()(Param0 p0, Param1 p1, const Arg& a0, const Arg& a1, const Arg& a2, const Arg& a3, const Arg& a4, const Arg& a5, const Arg& a6, const Arg& a7, const Arg& a8, const Arg& a9, const Arg& a10, const Arg& a11, const Arg& a12, const Arg& a13, const Arg& a14, const Arg& a15, const Arg& a16) const { const Arg* const args[] = { &a0, &a1, &a2, &a3, &a4, &a5, &a6, &a7, &a8, &a9, &a10, &a11, &a12, &a13, &a14, &a15, &a16 }; return Func(p0, p1, args, 17); } Result operator()(Param0 p0, Param1 p1, const Arg& a0, const Arg& a1, const Arg& a2, const Arg& a3, const Arg& a4, const Arg& a5, const Arg& a6, const Arg& a7, const Arg& a8, const Arg& a9, const Arg& a10, const Arg& a11, const Arg& a12, const Arg& a13, const Arg& a14, const Arg& a15, const Arg& a16, const Arg& a17) const { const Arg* const args[] = { &a0, &a1, &a2, &a3, &a4, &a5, &a6, &a7, &a8, &a9, &a10, &a11, &a12, &a13, &a14, &a15, &a16, &a17 }; return Func(p0, p1, args, 18); } Result operator()(Param0 p0, Param1 p1, const Arg& a0, const Arg& a1, const Arg& a2, const Arg& a3, const Arg& a4, const Arg& a5, const Arg& a6, const Arg& a7, const Arg& a8, const Arg& a9, const Arg& a10, const Arg& a11, const Arg& a12, const Arg& a13, const Arg& a14, const Arg& a15, const Arg& a16, const Arg& a17, const Arg& a18) const { const Arg* const args[] = { &a0, &a1, &a2, &a3, &a4, &a5, &a6, &a7, &a8, &a9, &a10, &a11, &a12, &a13, &a14, &a15, &a16, &a17, &a18 }; return Func(p0, p1, args, 19); } Result operator()(Param0 p0, Param1 p1, const Arg& a0, const Arg& a1, const Arg& a2, const Arg& a3, const Arg& a4, const Arg& a5, const Arg& a6, const Arg& a7, const Arg& a8, const Arg& a9, const Arg& a10, const Arg& a11, const Arg& a12, const Arg& a13, const Arg& a14, const Arg& a15, const Arg& a16, const Arg& a17, const Arg& a18, const Arg& a19) const { const Arg* const args[] = { &a0, &a1, &a2, &a3, &a4, &a5, &a6, &a7, &a8, &a9, &a10, &a11, &a12, &a13, &a14, &a15, &a16, &a17, &a18, &a19 }; return Func(p0, p1, args, 20); } Result operator()(Param0 p0, Param1 p1, const Arg& a0, const Arg& a1, const Arg& a2, const Arg& a3, const Arg& a4, const Arg& a5, const Arg& a6, const Arg& a7, const Arg& a8, const Arg& a9, const Arg& a10, const Arg& a11, const Arg& a12, const Arg& a13, const Arg& a14, const Arg& a15, const Arg& a16, const Arg& a17, const Arg& a18, const Arg& a19, const Arg& a20) const { const Arg* const args[] = { &a0, &a1, &a2, &a3, &a4, &a5, &a6, &a7, &a8, &a9, &a10, &a11, &a12, &a13, &a14, &a15, &a16, &a17, &a18, &a19, &a20 }; return Func(p0, p1, args, 21); } Result operator()(Param0 p0, Param1 p1, const Arg& a0, const Arg& a1, const Arg& a2, const Arg& a3, const Arg& a4, const Arg& a5, const Arg& a6, const Arg& a7, const Arg& a8, const Arg& a9, const Arg& a10, const Arg& a11, const Arg& a12, const Arg& a13, const Arg& a14, const Arg& a15, const Arg& a16, const Arg& a17, const Arg& a18, const Arg& a19, const Arg& a20, const Arg& a21) const { const Arg* const args[] = { &a0, &a1, &a2, &a3, &a4, &a5, &a6, &a7, &a8, &a9, &a10, &a11, &a12, &a13, &a14, &a15, &a16, &a17, &a18, &a19, &a20, &a21 }; return Func(p0, p1, args, 22); } Result operator()(Param0 p0, Param1 p1, const Arg& a0, const Arg& a1, const Arg& a2, const Arg& a3, const Arg& a4, const Arg& a5, const Arg& a6, const Arg& a7, const Arg& a8, const Arg& a9, const Arg& a10, const Arg& a11, const Arg& a12, const Arg& a13, const Arg& a14, const Arg& a15, const Arg& a16, const Arg& a17, const Arg& a18, const Arg& a19, const Arg& a20, const Arg& a21, const Arg& a22) const { const Arg* const args[] = { &a0, &a1, &a2, &a3, &a4, &a5, &a6, &a7, &a8, &a9, &a10, &a11, &a12, &a13, &a14, &a15, &a16, &a17, &a18, &a19, &a20, &a21, &a22 }; return Func(p0, p1, args, 23); } Result operator()(Param0 p0, Param1 p1, const Arg& a0, const Arg& a1, const Arg& a2, const Arg& a3, const Arg& a4, const Arg& a5, const Arg& a6, const Arg& a7, const Arg& a8, const Arg& a9, const Arg& a10, const Arg& a11, const Arg& a12, const Arg& a13, const Arg& a14, const Arg& a15, const Arg& a16, const Arg& a17, const Arg& a18, const Arg& a19, const Arg& a20, const Arg& a21, const Arg& a22, const Arg& a23) const { const Arg* const args[] = { &a0, &a1, &a2, &a3, &a4, &a5, &a6, &a7, &a8, &a9, &a10, &a11, &a12, &a13, &a14, &a15, &a16, &a17, &a18, &a19, &a20, &a21, &a22, &a23 }; return Func(p0, p1, args, 24); } Result operator()(Param0 p0, Param1 p1, const Arg& a0, const Arg& a1, const Arg& a2, const Arg& a3, const Arg& a4, const Arg& a5, const Arg& a6, const Arg& a7, const Arg& a8, const Arg& a9, const Arg& a10, const Arg& a11, const Arg& a12, const Arg& a13, const Arg& a14, const Arg& a15, const Arg& a16, const Arg& a17, const Arg& a18, const Arg& a19, const Arg& a20, const Arg& a21, const Arg& a22, const Arg& a23, const Arg& a24) const { const Arg* const args[] = { &a0, &a1, &a2, &a3, &a4, &a5, &a6, &a7, &a8, &a9, &a10, &a11, &a12, &a13, &a14, &a15, &a16, &a17, &a18, &a19, &a20, &a21, &a22, &a23, &a24 }; return Func(p0, p1, args, 25); } Result operator()(Param0 p0, Param1 p1, const Arg& a0, const Arg& a1, const Arg& a2, const Arg& a3, const Arg& a4, const Arg& a5, const Arg& a6, const Arg& a7, const Arg& a8, const Arg& a9, const Arg& a10, const Arg& a11, const Arg& a12, const Arg& a13, const Arg& a14, const Arg& a15, const Arg& a16, const Arg& a17, const Arg& a18, const Arg& a19, const Arg& a20, const Arg& a21, const Arg& a22, const Arg& a23, const Arg& a24, const Arg& a25) const { const Arg* const args[] = { &a0, &a1, &a2, &a3, &a4, &a5, &a6, &a7, &a8, &a9, &a10, &a11, &a12, &a13, &a14, &a15, &a16, &a17, &a18, &a19, &a20, &a21, &a22, &a23, &a24, &a25 }; return Func(p0, p1, args, 26); } Result operator()(Param0 p0, Param1 p1, const Arg& a0, const Arg& a1, const Arg& a2, const Arg& a3, const Arg& a4, const Arg& a5, const Arg& a6, const Arg& a7, const Arg& a8, const Arg& a9, const Arg& a10, const Arg& a11, const Arg& a12, const Arg& a13, const Arg& a14, const Arg& a15, const Arg& a16, const Arg& a17, const Arg& a18, const Arg& a19, const Arg& a20, const Arg& a21, const Arg& a22, const Arg& a23, const Arg& a24, const Arg& a25, const Arg& a26) const { const Arg* const args[] = { &a0, &a1, &a2, &a3, &a4, &a5, &a6, &a7, &a8, &a9, &a10, &a11, &a12, &a13, &a14, &a15, &a16, &a17, &a18, &a19, &a20, &a21, &a22, &a23, &a24, &a25, &a26 }; return Func(p0, p1, args, 27); } Result operator()(Param0 p0, Param1 p1, const Arg& a0, const Arg& a1, const Arg& a2, const Arg& a3, const Arg& a4, const Arg& a5, const Arg& a6, const Arg& a7, const Arg& a8, const Arg& a9, const Arg& a10, const Arg& a11, const Arg& a12, const Arg& a13, const Arg& a14, const Arg& a15, const Arg& a16, const Arg& a17, const Arg& a18, const Arg& a19, const Arg& a20, const Arg& a21, const Arg& a22, const Arg& a23, const Arg& a24, const Arg& a25, const Arg& a26, const Arg& a27) const { const Arg* const args[] = { &a0, &a1, &a2, &a3, &a4, &a5, &a6, &a7, &a8, &a9, &a10, &a11, &a12, &a13, &a14, &a15, &a16, &a17, &a18, &a19, &a20, &a21, &a22, &a23, &a24, &a25, &a26, &a27 }; return Func(p0, p1, args, 28); } Result operator()(Param0 p0, Param1 p1, const Arg& a0, const Arg& a1, const Arg& a2, const Arg& a3, const Arg& a4, const Arg& a5, const Arg& a6, const Arg& a7, const Arg& a8, const Arg& a9, const Arg& a10, const Arg& a11, const Arg& a12, const Arg& a13, const Arg& a14, const Arg& a15, const Arg& a16, const Arg& a17, const Arg& a18, const Arg& a19, const Arg& a20, const Arg& a21, const Arg& a22, const Arg& a23, const Arg& a24, const Arg& a25, const Arg& a26, const Arg& a27, const Arg& a28) const { const Arg* const args[] = { &a0, &a1, &a2, &a3, &a4, &a5, &a6, &a7, &a8, &a9, &a10, &a11, &a12, &a13, &a14, &a15, &a16, &a17, &a18, &a19, &a20, &a21, &a22, &a23, &a24, &a25, &a26, &a27, &a28 }; return Func(p0, p1, args, 29); } Result operator()(Param0 p0, Param1 p1, const Arg& a0, const Arg& a1, const Arg& a2, const Arg& a3, const Arg& a4, const Arg& a5, const Arg& a6, const Arg& a7, const Arg& a8, const Arg& a9, const Arg& a10, const Arg& a11, const Arg& a12, const Arg& a13, const Arg& a14, const Arg& a15, const Arg& a16, const Arg& a17, const Arg& a18, const Arg& a19, const Arg& a20, const Arg& a21, const Arg& a22, const Arg& a23, const Arg& a24, const Arg& a25, const Arg& a26, const Arg& a27, const Arg& a28, const Arg& a29) const { const Arg* const args[] = { &a0, &a1, &a2, &a3, &a4, &a5, &a6, &a7, &a8, &a9, &a10, &a11, &a12, &a13, &a14, &a15, &a16, &a17, &a18, &a19, &a20, &a21, &a22, &a23, &a24, &a25, &a26, &a27, &a28, &a29 }; return Func(p0, p1, args, 30); } Result operator()(Param0 p0, Param1 p1, const Arg& a0, const Arg& a1, const Arg& a2, const Arg& a3, const Arg& a4, const Arg& a5, const Arg& a6, const Arg& a7, const Arg& a8, const Arg& a9, const Arg& a10, const Arg& a11, const Arg& a12, const Arg& a13, const Arg& a14, const Arg& a15, const Arg& a16, const Arg& a17, const Arg& a18, const Arg& a19, const Arg& a20, const Arg& a21, const Arg& a22, const Arg& a23, const Arg& a24, const Arg& a25, const Arg& a26, const Arg& a27, const Arg& a28, const Arg& a29, const Arg& a30) const { const Arg* const args[] = { &a0, &a1, &a2, &a3, &a4, &a5, &a6, &a7, &a8, &a9, &a10, &a11, &a12, &a13, &a14, &a15, &a16, &a17, &a18, &a19, &a20, &a21, &a22, &a23, &a24, &a25, &a26, &a27, &a28, &a29, &a30 }; return Func(p0, p1, args, 31); } Result operator()(Param0 p0, Param1 p1, const Arg& a0, const Arg& a1, const Arg& a2, const Arg& a3, const Arg& a4, const Arg& a5, const Arg& a6, const Arg& a7, const Arg& a8, const Arg& a9, const Arg& a10, const Arg& a11, const Arg& a12, const Arg& a13, const Arg& a14, const Arg& a15, const Arg& a16, const Arg& a17, const Arg& a18, const Arg& a19, const Arg& a20, const Arg& a21, const Arg& a22, const Arg& a23, const Arg& a24, const Arg& a25, const Arg& a26, const Arg& a27, const Arg& a28, const Arg& a29, const Arg& a30, const Arg& a31) const { const Arg* const args[] = { &a0, &a1, &a2, &a3, &a4, &a5, &a6, &a7, &a8, &a9, &a10, &a11, &a12, &a13, &a14, &a15, &a16, &a17, &a18, &a19, &a20, &a21, &a22, &a23, &a24, &a25, &a26, &a27, &a28, &a29, &a30, &a31 }; return Func(p0, p1, args, 32); } }; } // namespace re2 #endif // RE2_VARIADIC_FUNCTION_H_
16,649
47.26087
79
h
openalpr
openalpr-master/src/openalpr/support/re2/walker-inl.h
// Copyright 2006 The RE2 Authors. All Rights Reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Helper class for traversing Regexps without recursion. // Clients should declare their own subclasses that override // the PreVisit and PostVisit methods, which are called before // and after visiting the subexpressions. // Not quite the Visitor pattern, because (among other things) // the Visitor pattern is recursive. #ifndef RE2_WALKER_INL_H__ #define RE2_WALKER_INL_H__ #include <stack> #include "re2/regexp.h" namespace re2 { template<typename T> struct WalkState; template<typename T> class Regexp::Walker { public: Walker(); virtual ~Walker(); // Virtual method called before visiting re's children. // PreVisit passes ownership of its return value to its caller. // The Arg* that PreVisit returns will be passed to PostVisit as pre_arg // and passed to the child PreVisits and PostVisits as parent_arg. // At the top-most Regexp, parent_arg is arg passed to walk. // If PreVisit sets *stop to true, the walk does not recurse // into the children. Instead it behaves as though the return // value from PreVisit is the return value from PostVisit. // The default PreVisit returns parent_arg. virtual T PreVisit(Regexp* re, T parent_arg, bool* stop); // Virtual method called after visiting re's children. // The pre_arg is the T that PreVisit returned. // The child_args is a vector of the T that the child PostVisits returned. // PostVisit takes ownership of pre_arg. // PostVisit takes ownership of the Ts // in *child_args, but not the vector itself. // PostVisit passes ownership of its return value // to its caller. // The default PostVisit simply returns pre_arg. virtual T PostVisit(Regexp* re, T parent_arg, T pre_arg, T* child_args, int nchild_args); // Virtual method called to copy a T, // when Walk notices that more than one child is the same re. virtual T Copy(T arg); // Virtual method called to do a "quick visit" of the re, // but not its children. Only called once the visit budget // has been used up and we're trying to abort the walk // as quickly as possible. Should return a value that // makes sense for the parent PostVisits still to be run. // This function is (hopefully) only called by // WalkExponential, but must be implemented by all clients, // just in case. virtual T ShortVisit(Regexp* re, T parent_arg) = 0; // Walks over a regular expression. // Top_arg is passed as parent_arg to PreVisit and PostVisit of re. // Returns the T returned by PostVisit on re. T Walk(Regexp* re, T top_arg); // Like Walk, but doesn't use Copy. This can lead to // exponential runtimes on cross-linked Regexps like the // ones generated by Simplify. To help limit this, // at most max_visits nodes will be visited and then // the walk will be cut off early. // If the walk *is* cut off early, ShortVisit(re) // will be called on regexps that cannot be fully // visited rather than calling PreVisit/PostVisit. T WalkExponential(Regexp* re, T top_arg, int max_visits); // Clears the stack. Should never be necessary, since // Walk always enters and exits with an empty stack. // Logs DFATAL if stack is not already clear. void Reset(); // Returns whether walk was cut off. bool stopped_early() { return stopped_early_; } private: // Walk state for the entire traversal. std::stack<WalkState<T> >* stack_; bool stopped_early_; int max_visits_; T WalkInternal(Regexp* re, T top_arg, bool use_copy); DISALLOW_COPY_AND_ASSIGN(Walker); }; template<typename T> T Regexp::Walker<T>::PreVisit(Regexp* re, T parent_arg, bool* stop) { return parent_arg; } template<typename T> T Regexp::Walker<T>::PostVisit(Regexp* re, T parent_arg, T pre_arg, T* child_args, int nchild_args) { return pre_arg; } template<typename T> T Regexp::Walker<T>::Copy(T arg) { return arg; } // State about a single level in the traversal. template<typename T> struct WalkState { WalkState<T>(Regexp* re, T parent) : re(re), n(-1), parent_arg(parent), child_args(NULL) { } Regexp* re; // The regexp int n; // The index of the next child to process; -1 means need to PreVisit T parent_arg; // Accumulated arguments. T pre_arg; T child_arg; // One-element buffer for child_args. T* child_args; }; template<typename T> Regexp::Walker<T>::Walker() { stack_ = new std::stack<WalkState<T> >; stopped_early_ = false; } template<typename T> Regexp::Walker<T>::~Walker() { Reset(); delete stack_; } // Clears the stack. Should never be necessary, since // Walk always enters and exits with an empty stack. // Logs DFATAL if stack is not already clear. template<typename T> void Regexp::Walker<T>::Reset() { if (stack_ && stack_->size() > 0) { LOG(DFATAL) << "Stack not empty."; while (stack_->size() > 0) { delete stack_->top().child_args; stack_->pop(); } } } template<typename T> T Regexp::Walker<T>::WalkInternal(Regexp* re, T top_arg, bool use_copy) { Reset(); if (re == NULL) { LOG(DFATAL) << "Walk NULL"; return top_arg; } stack_->push(WalkState<T>(re, top_arg)); WalkState<T>* s; for (;;) { T t; s = &stack_->top(); Regexp* re = s->re; switch (s->n) { case -1: { if (--max_visits_ < 0) { stopped_early_ = true; t = ShortVisit(re, s->parent_arg); break; } bool stop = false; s->pre_arg = PreVisit(re, s->parent_arg, &stop); if (stop) { t = s->pre_arg; break; } s->n = 0; s->child_args = NULL; if (re->nsub_ == 1) s->child_args = &s->child_arg; else if (re->nsub_ > 1) s->child_args = new T[re->nsub_]; // Fall through. } default: { if (re->nsub_ > 0) { Regexp** sub = re->sub(); if (s->n < re->nsub_) { if (use_copy && s->n > 0 && sub[s->n - 1] == sub[s->n]) { s->child_args[s->n] = Copy(s->child_args[s->n - 1]); s->n++; } else { stack_->push(WalkState<T>(sub[s->n], s->pre_arg)); } continue; } } t = PostVisit(re, s->parent_arg, s->pre_arg, s->child_args, s->n); if (re->nsub_ > 1) delete[] s->child_args; break; } } // We've finished stack_->top(). // Update next guy down. stack_->pop(); if (stack_->size() == 0) return t; s = &stack_->top(); if (s->child_args != NULL) s->child_args[s->n] = t; else s->child_arg = t; s->n++; } } template<typename T> T Regexp::Walker<T>::Walk(Regexp* re, T top_arg) { // Without the exponential walking behavior, // this budget should be more than enough for any // regexp, and yet not enough to get us in trouble // as far as CPU time. max_visits_ = 1000000; return WalkInternal(re, top_arg, true); } template<typename T> T Regexp::Walker<T>::WalkExponential(Regexp* re, T top_arg, int max_visits) { max_visits_ = max_visits; return WalkInternal(re, top_arg, false); } } // namespace re2 #endif // RE2_WALKER_INL_H__
7,756
30.404858
80
h
openalpr
openalpr-master/src/openalpr/support/re2/util/atomicops.h
// Copyright 2006-2008 The RE2 Authors. All Rights Reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #ifndef RE2_UTIL_ATOMICOPS_H__ #define RE2_UTIL_ATOMICOPS_H__ // The memory ordering constraints resemble the ones in C11. // RELAXED - no memory ordering, just an atomic operation. // CONSUME - data-dependent ordering. // ACQUIRE - prevents memory accesses from hoisting above the operation. // RELEASE - prevents memory accesses from sinking below the operation. #ifndef __has_builtin #define __has_builtin(x) 0 #endif #if !defined(OS_NACL) && (__has_builtin(__atomic_load_n) || (__GNUC__*10000 + __GNUC_MINOR__*100 + __GNUC_PATCHLEVEL__ >= 40801)) #define ATOMIC_LOAD_RELAXED(x, p) do { (x) = __atomic_load_n((p), __ATOMIC_RELAXED); } while (0) #define ATOMIC_LOAD_CONSUME(x, p) do { (x) = __atomic_load_n((p), __ATOMIC_CONSUME); } while (0) #define ATOMIC_LOAD_ACQUIRE(x, p) do { (x) = __atomic_load_n((p), __ATOMIC_ACQUIRE); } while (0) #define ATOMIC_STORE_RELAXED(p, v) __atomic_store_n((p), (v), __ATOMIC_RELAXED) #define ATOMIC_STORE_RELEASE(p, v) __atomic_store_n((p), (v), __ATOMIC_RELEASE) #else // old compiler #define ATOMIC_LOAD_RELAXED(x, p) do { (x) = *(p); } while (0) #define ATOMIC_LOAD_CONSUME(x, p) do { (x) = *(p); MaybeReadMemoryBarrier(); } while (0) #define ATOMIC_LOAD_ACQUIRE(x, p) do { (x) = *(p); ReadMemoryBarrier(); } while (0) #define ATOMIC_STORE_RELAXED(p, v) do { *(p) = (v); } while (0) #define ATOMIC_STORE_RELEASE(p, v) do { WriteMemoryBarrier(); *(p) = (v); } while (0) // WriteMemoryBarrier(), ReadMemoryBarrier() and MaybeReadMemoryBarrier() // are an implementation detail and must not be used in the rest of the code. #if defined(__i386__) static inline void WriteMemoryBarrier() { int x; __asm__ __volatile__("xchgl (%0),%0" // The lock prefix is implicit for xchg. :: "r" (&x)); } #elif defined(__x86_64__) // 64-bit implementations of memory barrier can be simpler, because // "sfence" is guaranteed to exist. static inline void WriteMemoryBarrier() { __asm__ __volatile__("sfence" : : : "memory"); } #elif defined(__ppc__) || defined(__powerpc64__) static inline void WriteMemoryBarrier() { __asm__ __volatile__("eieio" : : : "memory"); } #elif defined(__alpha__) static inline void WriteMemoryBarrier() { __asm__ __volatile__("wmb" : : : "memory"); } #elif defined(__aarch64__) static inline void WriteMemoryBarrier() { __asm__ __volatile__("dmb st" : : : "memory"); } #elif defined(__arm__) && defined(__linux__) // Linux on ARM puts a suitable memory barrier at a magic address for us to call. static inline void WriteMemoryBarrier() { ((void(*)(void))0xffff0fa0)(); } #elif defined(__windows__) // Windows inline void WriteMemoryBarrier() { LONG x; ::InterlockedExchange(&x, 0); } #elif defined(OS_NACL) // Native Client inline void WriteMemoryBarrier() { __sync_synchronize(); } #elif defined(__mips__) inline void WriteMemoryBarrier() { __asm__ __volatile__("sync" : : : "memory"); } #else #include "util/mutex.h" static inline void WriteMemoryBarrier() { // Slight overkill, but good enough: // any mutex implementation must have // a read barrier after the lock operation and // a write barrier before the unlock operation. // // It may be worthwhile to write architecture-specific // barriers for the common platforms, as above, but // this is a correct fallback. re2::Mutex mu; re2::MutexLock l(&mu); } #endif // Alpha has very weak memory ordering. If relying on WriteBarriers, one must // use read barriers for the readers too. #if defined(__alpha__) static inline void MaybeReadMemoryBarrier() { __asm__ __volatile__("mb" : : : "memory"); } #else static inline void MaybeReadMemoryBarrier() {} #endif // __alpha__ // Read barrier for various targets. #if defined(__aarch64__) static inline void ReadMemoryBarrier() { __asm__ __volatile__("dmb ld" : : : "memory"); } #elif defined(__alpha__) static inline void ReadMemoryBarrier() { __asm__ __volatile__("mb" : : : "memory"); } #elif defined(__mips__) inline void ReadMemoryBarrier() { __asm__ __volatile__("sync" : : : "memory"); } #else static inline void ReadMemoryBarrier() {} #endif #endif // old compiler #ifndef NO_THREAD_SAFETY_ANALYSIS #define NO_THREAD_SAFETY_ANALYSIS #endif #endif // RE2_UTIL_ATOMICOPS_H__
4,421
25.8
129
h
openalpr
openalpr-master/src/openalpr/support/re2/util/benchmark.h
// Copyright 2009 The RE2 Authors. All Rights Reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #ifndef RE2_UTIL_BENCHMARK_H__ #define RE2_UTIL_BENCHMARK_H__ namespace testing { struct Benchmark { const char* name; void (*fn)(int); void (*fnr)(int, int); int lo; int hi; int threadlo; int threadhi; void Register(); Benchmark(const char* name, void (*f)(int)) { Clear(name); fn = f; Register(); } Benchmark(const char* name, void (*f)(int, int), int l, int h) { Clear(name); fnr = f; lo = l; hi = h; Register(); } void Clear(const char* n) { name = n; fn = 0; fnr = 0; lo = 0; hi = 0; threadlo = 0; threadhi = 0; } Benchmark* ThreadRange(int lo, int hi) { threadlo = lo; threadhi = hi; return this; } }; } // namespace testing void SetBenchmarkBytesProcessed(long long); void StopBenchmarkTiming(); void StartBenchmarkTiming(); void BenchmarkMemoryUsage(); void SetBenchmarkItemsProcessed(int); int NumCPUs(); #define BENCHMARK(f) \ ::testing::Benchmark* _benchmark_##f = (new ::testing::Benchmark(#f, f)) #define BENCHMARK_RANGE(f, lo, hi) \ ::testing::Benchmark* _benchmark_##f = \ (new ::testing::Benchmark(#f, f, lo, hi)) #endif // RE2_UTIL_BENCHMARK_H__
1,263
29.095238
118
h
openalpr
openalpr-master/src/openalpr/support/re2/util/flags.h
// Copyright 2009 The RE2 Authors. All Rights Reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Simplified version of Google's command line flags. // Does not support parsing the command line. // If you want to do that, see // https://gflags.github.io/gflags/ #ifndef RE2_UTIL_FLAGS_H__ #define RE2_UTIL_FLAGS_H__ #define DEFINE_flag(type, name, deflt, desc) \ namespace re2 { type FLAGS_##name = deflt; } #define DECLARE_flag(type, name) \ namespace re2 { extern type FLAGS_##name; } #define DEFINE_bool(name, deflt, desc) DEFINE_flag(bool, name, deflt, desc) #define DEFINE_int32(name, deflt, desc) DEFINE_flag(int32, name, deflt, desc) #define DEFINE_string(name, deflt, desc) DEFINE_flag(string, name, deflt, desc) #define DECLARE_bool(name) DECLARE_flag(bool, name) #define DECLARE_int32(name) DECLARE_flag(int32, name) #define DECLARE_string(name) DECLARE_flag(string, name) #endif // RE2_UTIL_FLAGS_H__
988
34.321429
79
h
openalpr
openalpr-master/src/openalpr/support/re2/util/logging.h
// Copyright 2009 The RE2 Authors. All Rights Reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Simplified version of Google's logging. #ifndef RE2_UTIL_LOGGING_H__ #define RE2_UTIL_LOGGING_H__ #include <assert.h> #include <ostream> #include <stdio.h> /* for fwrite */ #include <stdlib.h> #include <string> #include <sstream> // Debug-only checking. #define DCHECK(condition) assert(condition) #define DCHECK_EQ(val1, val2) assert((val1) == (val2)) #define DCHECK_NE(val1, val2) assert((val1) != (val2)) #define DCHECK_LE(val1, val2) assert((val1) <= (val2)) #define DCHECK_LT(val1, val2) assert((val1) < (val2)) #define DCHECK_GE(val1, val2) assert((val1) >= (val2)) #define DCHECK_GT(val1, val2) assert((val1) > (val2)) // Always-on checking #define CHECK(x) if(x){}else LogMessageFatal(__FILE__, __LINE__).stream() << "Check failed: " #x #define CHECK_LT(x, y) CHECK((x) < (y)) #define CHECK_GT(x, y) CHECK((x) > (y)) #define CHECK_LE(x, y) CHECK((x) <= (y)) #define CHECK_GE(x, y) CHECK((x) >= (y)) #define CHECK_EQ(x, y) CHECK((x) == (y)) #define CHECK_NE(x, y) CHECK((x) != (y)) #define LOG_INFO LogMessage(__FILE__, __LINE__) #define LOG_ERROR LOG_INFO #define LOG_WARNING LOG_INFO #define LOG_FATAL LogMessageFatal(__FILE__, __LINE__) #define LOG_QFATAL LOG_FATAL #define VLOG(x) if((x)>0){}else LOG_INFO.stream() #ifdef NDEBUG #define DEBUG_MODE 0 #define LOG_DFATAL LOG_ERROR #else #define DEBUG_MODE 1 #define LOG_DFATAL LOG_FATAL #endif #define LOG(severity) LOG_ ## severity.stream() class LogMessage { public: LogMessage(const char* file, int line) : flushed_(false) { stream() << file << ":" << line << ": "; } void Flush() { stream() << "\n"; std::string s = str_.str(); size_t n = s.size(); if (fwrite(s.data(), 1, n, stderr) < n) {} // shut up gcc flushed_ = true; } ~LogMessage() { if (!flushed_) { Flush(); } } std::ostream& stream() { return str_; } private: bool flushed_; std::ostringstream str_; DISALLOW_COPY_AND_ASSIGN(LogMessage); }; class LogMessageFatal : public LogMessage { public: LogMessageFatal(const char* file, int line) : LogMessage(file, line) { } ~LogMessageFatal() { Flush(); abort(); } private: DISALLOW_COPY_AND_ASSIGN(LogMessageFatal); }; #endif // RE2_UTIL_LOGGING_H__
2,379
25.153846
96
h
openalpr
openalpr-master/src/openalpr/support/re2/util/mutex.h
// Copyright 2007 The RE2 Authors. All Rights Reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. /* * A simple mutex wrapper, supporting locks and read-write locks. * You should assume the locks are *not* re-entrant. */ #ifndef RE2_UTIL_MUTEX_H_ #define RE2_UTIL_MUTEX_H_ #include <stdlib.h> namespace re2 { #ifndef WIN32 #define HAVE_PTHREAD 1 #define HAVE_RWLOCK 1 #endif #if defined(NO_THREADS) typedef int MutexType; // to keep a lock-count #elif defined(HAVE_PTHREAD) && defined(HAVE_RWLOCK) // Needed for pthread_rwlock_*. If it causes problems, you could take it // out, but then you'd have to unset HAVE_RWLOCK (at least on linux -- it // *does* cause problems for FreeBSD, or MacOSX, but isn't needed // for locking there.) # ifdef __linux__ # undef _XOPEN_SOURCE # define _XOPEN_SOURCE 500 // may be needed to get the rwlock calls # endif # include <pthread.h> typedef pthread_rwlock_t MutexType; #elif defined(HAVE_PTHREAD) # include <pthread.h> typedef pthread_mutex_t MutexType; #elif defined(_WIN32) # define WIN32_LEAN_AND_MEAN // We only need minimal includes # ifdef GMUTEX_TRYLOCK // We need Windows NT or later for TryEnterCriticalSection(). If you // don't need that functionality, you can remove these _WIN32_WINNT // lines, and change TryLock() to assert(0) or something. # ifndef _WIN32_WINNT # define _WIN32_WINNT 0x0400 # endif # endif # include <windows.h> typedef CRITICAL_SECTION MutexType; #else # error Need to implement mutex.h for your architecture, or #define NO_THREADS #endif class Mutex { public: // Create a Mutex that is not held by anybody. inline Mutex(); // Destructor inline ~Mutex(); inline void Lock(); // Block if needed until free then acquire exclusively inline void Unlock(); // Release a lock acquired via Lock() inline bool TryLock(); // If free, Lock() and return true, else return false // Note that on systems that don't support read-write locks, these may // be implemented as synonyms to Lock() and Unlock(). So you can use // these for efficiency, but don't use them anyplace where being able // to do shared reads is necessary to avoid deadlock. inline void ReaderLock(); // Block until free or shared then acquire a share inline void ReaderUnlock(); // Release a read share of this Mutex inline void WriterLock() { Lock(); } // Acquire an exclusive lock inline void WriterUnlock() { Unlock(); } // Release a lock from WriterLock() inline void AssertHeld() { } private: MutexType mutex_; // Catch the error of writing Mutex when intending MutexLock. Mutex(Mutex *ignored); // Disallow "evil" constructors Mutex(const Mutex&); void operator=(const Mutex&); }; // Now the implementation of Mutex for various systems #if defined(NO_THREADS) // When we don't have threads, we can be either reading or writing, // but not both. We can have lots of readers at once (in no-threads // mode, that's most likely to happen in recursive function calls), // but only one writer. We represent this by having mutex_ be -1 when // writing and a number > 0 when reading (and 0 when no lock is held). // // In debug mode, we assert these invariants, while in non-debug mode // we do nothing, for efficiency. That's why everything is in an // assert. #include <assert.h> Mutex::Mutex() : mutex_(0) { } Mutex::~Mutex() { assert(mutex_ == 0); } void Mutex::Lock() { assert(--mutex_ == -1); } void Mutex::Unlock() { assert(mutex_++ == -1); } bool Mutex::TryLock() { if (mutex_) return false; Lock(); return true; } void Mutex::ReaderLock() { assert(++mutex_ > 0); } void Mutex::ReaderUnlock() { assert(mutex_-- > 0); } #elif defined(HAVE_PTHREAD) && defined(HAVE_RWLOCK) #define SAFE_PTHREAD(fncall) do { if ((fncall) != 0) abort(); } while (0) Mutex::Mutex() { SAFE_PTHREAD(pthread_rwlock_init(&mutex_, NULL)); } Mutex::~Mutex() { SAFE_PTHREAD(pthread_rwlock_destroy(&mutex_)); } void Mutex::Lock() { SAFE_PTHREAD(pthread_rwlock_wrlock(&mutex_)); } void Mutex::Unlock() { SAFE_PTHREAD(pthread_rwlock_unlock(&mutex_)); } bool Mutex::TryLock() { return pthread_rwlock_trywrlock(&mutex_) == 0; } void Mutex::ReaderLock() { SAFE_PTHREAD(pthread_rwlock_rdlock(&mutex_)); } void Mutex::ReaderUnlock() { SAFE_PTHREAD(pthread_rwlock_unlock(&mutex_)); } #undef SAFE_PTHREAD #elif defined(HAVE_PTHREAD) #define SAFE_PTHREAD(fncall) do { if ((fncall) != 0) abort(); } while (0) Mutex::Mutex() { SAFE_PTHREAD(pthread_mutex_init(&mutex_, NULL)); } Mutex::~Mutex() { SAFE_PTHREAD(pthread_mutex_destroy(&mutex_)); } void Mutex::Lock() { SAFE_PTHREAD(pthread_mutex_lock(&mutex_)); } void Mutex::Unlock() { SAFE_PTHREAD(pthread_mutex_unlock(&mutex_)); } bool Mutex::TryLock() { return pthread_mutex_trylock(&mutex_) == 0; } void Mutex::ReaderLock() { Lock(); } // we don't have read-write locks void Mutex::ReaderUnlock() { Unlock(); } #undef SAFE_PTHREAD #elif defined(_WIN32) Mutex::Mutex() { InitializeCriticalSection(&mutex_); } Mutex::~Mutex() { DeleteCriticalSection(&mutex_); } void Mutex::Lock() { EnterCriticalSection(&mutex_); } void Mutex::Unlock() { LeaveCriticalSection(&mutex_); } bool Mutex::TryLock() { return TryEnterCriticalSection(&mutex_) != 0; } void Mutex::ReaderLock() { Lock(); } // we don't have read-write locks void Mutex::ReaderUnlock() { Unlock(); } #endif // -------------------------------------------------------------------------- // Some helper classes // MutexLock(mu) acquires mu when constructed and releases it when destroyed. class MutexLock { public: explicit MutexLock(Mutex *mu) : mu_(mu) { mu_->Lock(); } ~MutexLock() { mu_->Unlock(); } private: Mutex * const mu_; // Disallow "evil" constructors MutexLock(const MutexLock&); void operator=(const MutexLock&); }; // ReaderMutexLock and WriterMutexLock do the same, for rwlocks class ReaderMutexLock { public: explicit ReaderMutexLock(Mutex *mu) : mu_(mu) { mu_->ReaderLock(); } ~ReaderMutexLock() { mu_->ReaderUnlock(); } private: Mutex * const mu_; // Disallow "evil" constructors ReaderMutexLock(const ReaderMutexLock&); void operator=(const ReaderMutexLock&); }; class WriterMutexLock { public: explicit WriterMutexLock(Mutex *mu) : mu_(mu) { mu_->WriterLock(); } ~WriterMutexLock() { mu_->WriterUnlock(); } private: Mutex * const mu_; // Disallow "evil" constructors WriterMutexLock(const WriterMutexLock&); void operator=(const WriterMutexLock&); }; // Catch bug where variable name is omitted, e.g. MutexLock (&mu); #define MutexLock(x) COMPILE_ASSERT(0, mutex_lock_decl_missing_var_name) #define ReaderMutexLock(x) COMPILE_ASSERT(0, rmutex_lock_decl_missing_var_name) #define WriterMutexLock(x) COMPILE_ASSERT(0, wmutex_lock_decl_missing_var_name) // Provide safe way to declare and use global, linker-initialized mutex. Sigh. #ifdef HAVE_PTHREAD #define GLOBAL_MUTEX(name) \ static pthread_mutex_t (name) = PTHREAD_MUTEX_INITIALIZER #define GLOBAL_MUTEX_LOCK(name) \ pthread_mutex_lock(&(name)) #define GLOBAL_MUTEX_UNLOCK(name) \ pthread_mutex_unlock(&(name)) #else #define GLOBAL_MUTEX(name) \ static Mutex name #define GLOBAL_MUTEX_LOCK(name) \ name.Lock() #define GLOBAL_MUTEX_UNLOCK(name) \ name.Unlock() #endif } // namespace re2 #endif /* #define RE2_UTIL_MUTEX_H_ */
7,530
34.191589
80
h
openalpr
openalpr-master/src/openalpr/support/re2/util/sparse_array.h
// Copyright 2006 The RE2 Authors. All Rights Reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // DESCRIPTION // // SparseArray<T>(m) is a map from integers in [0, m) to T values. // It requires (sizeof(T)+sizeof(int))*m memory, but it provides // fast iteration through the elements in the array and fast clearing // of the array. The array has a concept of certain elements being // uninitialized (having no value). // // Insertion and deletion are constant time operations. // // Allocating the array is a constant time operation // when memory allocation is a constant time operation. // // Clearing the array is a constant time operation (unusual!). // // Iterating through the array is an O(n) operation, where n // is the number of items in the array (not O(m)). // // The array iterator visits entries in the order they were first // inserted into the array. It is safe to add items to the array while // using an iterator: the iterator will visit indices added to the array // during the iteration, but will not re-visit indices whose values // change after visiting. Thus SparseArray can be a convenient // implementation of a work queue. // // The SparseArray implementation is NOT thread-safe. It is up to the // caller to make sure only one thread is accessing the array. (Typically // these arrays are temporary values and used in situations where speed is // important.) // // The SparseArray interface does not present all the usual STL bells and // whistles. // // Implemented with reference to Briggs & Torczon, An Efficient // Representation for Sparse Sets, ACM Letters on Programming Languages // and Systems, Volume 2, Issue 1-4 (March-Dec. 1993), pp. 59-69. // // Briggs & Torczon popularized this technique, but it had been known // long before their paper. They point out that Aho, Hopcroft, and // Ullman's 1974 Design and Analysis of Computer Algorithms and Bentley's // 1986 Programming Pearls both hint at the technique in exercises to the // reader (in Aho & Hopcroft, exercise 2.12; in Bentley, column 1 // exercise 8). // // Briggs & Torczon describe a sparse set implementation. I have // trivially generalized it to create a sparse array (actually the original // target of the AHU and Bentley exercises). // IMPLEMENTATION // // SparseArray uses a vector dense_ and an array sparse_to_dense_, both of // size max_size_. At any point, the number of elements in the sparse array is // size_. // // The vector dense_ contains the size_ elements in the sparse array (with // their indices), // in the order that the elements were first inserted. This array is dense: // the size_ pairs are dense_[0] through dense_[size_-1]. // // The array sparse_to_dense_ maps from indices in [0,m) to indices in // [0,size_). // For indices present in the array, dense_[sparse_to_dense_[i]].index_ == i. // For indices not present in the array, sparse_to_dense_ can contain // any value at all, perhaps outside the range [0, size_) but perhaps not. // // The lax requirement on sparse_to_dense_ values makes clearing // the array very easy: set size_ to 0. Lookups are slightly more // complicated. An index i has a value in the array if and only if: // sparse_to_dense_[i] is in [0, size_) AND // dense_[sparse_to_dense_[i]].index_ == i. // If both these properties hold, only then it is safe to refer to // dense_[sparse_to_dense_[i]].value_ // as the value associated with index i. // // To insert a new entry, set sparse_to_dense_[i] to size_, // initialize dense_[size_], and then increment size_. // // Deletion of specific values from the array is implemented by // swapping dense_[size_-1] and the dense_ being deleted and then // updating the appropriate sparse_to_dense_ entries. // // To make the sparse array as efficient as possible for non-primitive types, // elements may or may not be destroyed when they are deleted from the sparse // array through a call to erase(), erase_existing() or resize(). They // immediately become inaccessible, but they are only guaranteed to be // destroyed when the SparseArray destructor is called. #ifndef RE2_UTIL_SPARSE_ARRAY_H__ #define RE2_UTIL_SPARSE_ARRAY_H__ #include "re2/util/util.h" #include <string.h> #include <vector> #include <utility> namespace re2 { template<typename Value> class SparseArray { public: SparseArray(); SparseArray(int max_size); ~SparseArray(); // IndexValue pairs: exposed in SparseArray::iterator. class IndexValue; typedef IndexValue value_type; typedef typename std::vector<IndexValue>::iterator iterator; typedef typename std::vector<IndexValue>::const_iterator const_iterator; inline const IndexValue& iv(int i) const; // Return the number of entries in the array. int size() const { return size_; } // Iterate over the array. iterator begin() { return dense_.begin(); } iterator end() { return dense_.begin() + size_; } const_iterator begin() const { return dense_.begin(); } const_iterator end() const { return dense_.begin() + size_; } // Change the maximum size of the array. // Invalidates all iterators. void resize(int max_size); // Return the maximum size of the array. // Indices can be in the range [0, max_size). int max_size() const { return max_size_; } // Clear the array. void clear() { size_ = 0; } // Check whether index i is in the array. inline bool has_index(int i) const; // Comparison function for sorting. // Can sort the sparse array so that future iterations // will visit indices in increasing order using // sort(arr.begin(), arr.end(), arr.less); static bool less(const IndexValue& a, const IndexValue& b); public: // Set the value at index i to v. inline iterator set(int i, Value v); std::pair<iterator, bool> insert(const value_type& new_value); // Returns the value at index i // or defaultv if index i is not initialized in the array. inline Value get(int i, Value defaultv) const; iterator find(int i); const_iterator find(int i) const; // Change the value at index i to v. // Fast but unsafe: only use if has_index(i) is true. inline iterator set_existing(int i, Value v); // Set the value at the new index i to v. // Fast but unsafe: only use if has_index(i) is false. inline iterator set_new(int i, Value v); // Get the value at index i from the array.. // Fast but unsafe: only use if has_index(i) is true. inline Value get_existing(int i) const; // Erasing items from the array during iteration is in general // NOT safe. There is one special case, which is that the current // index-value pair can be erased as long as the iterator is then // checked for being at the end before being incremented. // For example: // // for (i = m.begin(); i != m.end(); ++i) { // if (ShouldErase(i->index(), i->value())) { // m.erase(i->index()); // --i; // } // } // // Except in the specific case just described, elements must // not be erased from the array (including clearing the array) // while iterators are walking over the array. Otherwise, // the iterators could walk past the end of the array. // Erases the element at index i from the array. inline void erase(int i); // Erases the element at index i from the array. // Fast but unsafe: only use if has_index(i) is true. inline void erase_existing(int i); private: // Add the index i to the array. // Only use if has_index(i) is known to be false. // Since it doesn't set the value associated with i, // this function is private, only intended as a helper // for other methods. inline void create_index(int i); // In debug mode, verify that some invariant properties of the class // are being maintained. This is called at the end of the constructor // and at the beginning and end of all public non-const member functions. inline void DebugCheckInvariants() const; int size_; int max_size_; int* sparse_to_dense_; std::vector<IndexValue> dense_; bool valgrind_; DISALLOW_COPY_AND_ASSIGN(SparseArray); }; template<typename Value> SparseArray<Value>::SparseArray() : size_(0), max_size_(0), sparse_to_dense_(NULL), dense_(), valgrind_(RunningOnValgrind()) {} // IndexValue pairs: exposed in SparseArray::iterator. template<typename Value> class SparseArray<Value>::IndexValue { friend class SparseArray; public: typedef int first_type; typedef Value second_type; IndexValue() {} IndexValue(int index, const Value& value) : second(value), index_(index) {} int index() const { return index_; } Value value() const { return second; } // Provide the data in the 'second' member so that the utilities // in map-util work. Value second; private: int index_; }; template<typename Value> const typename SparseArray<Value>::IndexValue& SparseArray<Value>::iv(int i) const { DCHECK_GE(i, 0); DCHECK_LT(i, size_); return dense_[i]; } // Change the maximum size of the array. // Invalidates all iterators. template<typename Value> void SparseArray<Value>::resize(int new_max_size) { DebugCheckInvariants(); if (new_max_size > max_size_) { int* a = new int[new_max_size]; if (sparse_to_dense_) { memmove(a, sparse_to_dense_, max_size_*sizeof a[0]); // Don't need to zero the memory but appease Valgrind. if (valgrind_) { for (int i = max_size_; i < new_max_size; i++) a[i] = 0xababababU; } delete[] sparse_to_dense_; } sparse_to_dense_ = a; dense_.resize(new_max_size); } max_size_ = new_max_size; if (size_ > max_size_) size_ = max_size_; DebugCheckInvariants(); } // Check whether index i is in the array. template<typename Value> bool SparseArray<Value>::has_index(int i) const { DCHECK_GE(i, 0); DCHECK_LT(i, max_size_); if (static_cast<uint>(i) >= static_cast<uint>(max_size_)) { return false; } // Unsigned comparison avoids checking sparse_to_dense_[i] < 0. return (uint)sparse_to_dense_[i] < (uint)size_ && dense_[sparse_to_dense_[i]].index_ == i; } // Set the value at index i to v. template<typename Value> typename SparseArray<Value>::iterator SparseArray<Value>::set(int i, Value v) { DebugCheckInvariants(); if (static_cast<uint>(i) >= static_cast<uint>(max_size_)) { // Semantically, end() would be better here, but we already know // the user did something stupid, so begin() insulates them from // dereferencing an invalid pointer. return begin(); } if (!has_index(i)) create_index(i); return set_existing(i, v); } template<typename Value> std::pair<typename SparseArray<Value>::iterator, bool> SparseArray<Value>::insert( const value_type& new_value) { DebugCheckInvariants(); std::pair<typename SparseArray<Value>::iterator, bool> p; if (has_index(new_value.index_)) { p = std::make_pair(dense_.begin() + sparse_to_dense_[new_value.index_], false); } else { p = std::make_pair(set_new(new_value.index_, new_value.second), true); } DebugCheckInvariants(); return p; } template<typename Value> Value SparseArray<Value>::get(int i, Value defaultv) const { if (!has_index(i)) return defaultv; return get_existing(i); } template<typename Value> typename SparseArray<Value>::iterator SparseArray<Value>::find(int i) { if (has_index(i)) return dense_.begin() + sparse_to_dense_[i]; return end(); } template<typename Value> typename SparseArray<Value>::const_iterator SparseArray<Value>::find(int i) const { if (has_index(i)) { return dense_.begin() + sparse_to_dense_[i]; } return end(); } template<typename Value> typename SparseArray<Value>::iterator SparseArray<Value>::set_existing(int i, Value v) { DebugCheckInvariants(); DCHECK(has_index(i)); dense_[sparse_to_dense_[i]].second = v; DebugCheckInvariants(); return dense_.begin() + sparse_to_dense_[i]; } template<typename Value> typename SparseArray<Value>::iterator SparseArray<Value>::set_new(int i, Value v) { DebugCheckInvariants(); if (static_cast<uint>(i) >= static_cast<uint>(max_size_)) { // Semantically, end() would be better here, but we already know // the user did something stupid, so begin() insulates them from // dereferencing an invalid pointer. return begin(); } DCHECK(!has_index(i)); create_index(i); return set_existing(i, v); } template<typename Value> Value SparseArray<Value>::get_existing(int i) const { DCHECK(has_index(i)); return dense_[sparse_to_dense_[i]].second; } template<typename Value> void SparseArray<Value>::erase(int i) { DebugCheckInvariants(); if (has_index(i)) erase_existing(i); DebugCheckInvariants(); } template<typename Value> void SparseArray<Value>::erase_existing(int i) { DebugCheckInvariants(); DCHECK(has_index(i)); int di = sparse_to_dense_[i]; if (di < size_ - 1) { dense_[di] = dense_[size_ - 1]; sparse_to_dense_[dense_[di].index_] = di; } size_--; DebugCheckInvariants(); } template<typename Value> void SparseArray<Value>::create_index(int i) { DCHECK(!has_index(i)); DCHECK_LT(size_, max_size_); sparse_to_dense_[i] = size_; dense_[size_].index_ = i; size_++; } template<typename Value> SparseArray<Value>::SparseArray(int max_size) { max_size_ = max_size; sparse_to_dense_ = new int[max_size]; valgrind_ = RunningOnValgrind(); dense_.resize(max_size); // Don't need to zero the new memory, but appease Valgrind. if (valgrind_) { for (int i = 0; i < max_size; i++) { sparse_to_dense_[i] = 0xababababU; dense_[i].index_ = 0xababababU; } } size_ = 0; DebugCheckInvariants(); } template<typename Value> SparseArray<Value>::~SparseArray() { DebugCheckInvariants(); delete[] sparse_to_dense_; } template<typename Value> void SparseArray<Value>::DebugCheckInvariants() const { DCHECK_LE(0, size_); DCHECK_LE(size_, max_size_); DCHECK(size_ == 0 || sparse_to_dense_ != NULL); } // Comparison function for sorting. template<typename Value> bool SparseArray<Value>::less(const IndexValue& a, const IndexValue& b) { return a.index_ < b.index_; } } // namespace re2 #endif // RE2_UTIL_SPARSE_ARRAY_H__
14,312
30.251092
97
h
openalpr
openalpr-master/src/openalpr/support/re2/util/sparse_set.h
// Copyright 2006 The RE2 Authors. All Rights Reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // DESCRIPTION // // SparseSet<T>(m) is a set of integers in [0, m). // It requires sizeof(int)*m memory, but it provides // fast iteration through the elements in the set and fast clearing // of the set. // // Insertion and deletion are constant time operations. // // Allocating the set is a constant time operation // when memory allocation is a constant time operation. // // Clearing the set is a constant time operation (unusual!). // // Iterating through the set is an O(n) operation, where n // is the number of items in the set (not O(m)). // // The set iterator visits entries in the order they were first // inserted into the array. It is safe to add items to the set while // using an iterator: the iterator will visit indices added to the set // during the iteration, but will not re-visit indices whose values // change after visiting. Thus SparseSet can be a convenient // implementation of a work queue. // // The SparseSet implementation is NOT thread-safe. It is up to the // caller to make sure only one thread is accessing the set. (Typically // these sets are temporary values and used in situations where speed is // important.) // // The SparseSet interface does not present all the usual STL bells and // whistles. // // Implemented with reference to Briggs & Torczon, An Efficient // Representation for Sparse Sets, ACM Letters on Programming Languages // and Systems, Volume 2, Issue 1-4 (March-Dec. 1993), pp. 59-69. // // For a generalization to sparse array, see sparse_array.h. // IMPLEMENTATION // // See sparse_array.h for implementation details #ifndef RE2_UTIL_SPARSE_SET_H__ #define RE2_UTIL_SPARSE_SET_H__ #include "re2/util/util.h" #include <string.h> namespace re2 { static bool InitMemory() { #ifdef MEMORY_SANITIZER return true; #else return RunningOnValgrind(); #endif } class SparseSet { public: SparseSet() : size_(0), max_size_(0), sparse_to_dense_(NULL), dense_(NULL), init_memory_(InitMemory()) {} SparseSet(int max_size) { max_size_ = max_size; sparse_to_dense_ = new int[max_size]; dense_ = new int[max_size]; init_memory_ = InitMemory(); // Don't need to zero the memory, but do so anyway // to appease Valgrind. if (init_memory_) { for (int i = 0; i < max_size; i++) { dense_[i] = 0xababababU; sparse_to_dense_[i] = 0xababababU; } } size_ = 0; } ~SparseSet() { delete[] sparse_to_dense_; delete[] dense_; } typedef int* iterator; typedef const int* const_iterator; int size() const { return size_; } iterator begin() { return dense_; } iterator end() { return dense_ + size_; } const_iterator begin() const { return dense_; } const_iterator end() const { return dense_ + size_; } // Change the maximum size of the array. // Invalidates all iterators. void resize(int new_max_size) { if (size_ > new_max_size) size_ = new_max_size; if (new_max_size > max_size_) { int* a = new int[new_max_size]; if (sparse_to_dense_) { memmove(a, sparse_to_dense_, max_size_*sizeof a[0]); if (init_memory_) { for (int i = max_size_; i < new_max_size; i++) a[i] = 0xababababU; } delete[] sparse_to_dense_; } sparse_to_dense_ = a; a = new int[new_max_size]; if (dense_) { memmove(a, dense_, size_*sizeof a[0]); if (init_memory_) { for (int i = size_; i < new_max_size; i++) a[i] = 0xababababU; } delete[] dense_; } dense_ = a; } max_size_ = new_max_size; } // Return the maximum size of the array. // Indices can be in the range [0, max_size). int max_size() const { return max_size_; } // Clear the array. void clear() { size_ = 0; } // Check whether i is in the array. bool contains(int i) const { DCHECK_GE(i, 0); DCHECK_LT(i, max_size_); if (static_cast<uint>(i) >= static_cast<uint>(max_size_)) { return false; } // Unsigned comparison avoids checking sparse_to_dense_[i] < 0. return (uint)sparse_to_dense_[i] < (uint)size_ && dense_[sparse_to_dense_[i]] == i; } // Adds i to the set. void insert(int i) { if (!contains(i)) insert_new(i); } // Set the value at the new index i to v. // Fast but unsafe: only use if contains(i) is false. void insert_new(int i) { if (static_cast<uint>(i) >= static_cast<uint>(max_size_)) { // Semantically, end() would be better here, but we already know // the user did something stupid, so begin() insulates them from // dereferencing an invalid pointer. return; } DCHECK(!contains(i)); DCHECK_LT(size_, max_size_); sparse_to_dense_[i] = size_; dense_[size_] = i; size_++; } // Comparison function for sorting. // Can sort the sparse array so that future iterations // will visit indices in increasing order using // sort(arr.begin(), arr.end(), arr.less); static bool less(int a, int b) { return a < b; } private: int size_; int max_size_; int* sparse_to_dense_; int* dense_; bool init_memory_; DISALLOW_COPY_AND_ASSIGN(SparseSet); }; } // namespace re2 #endif // RE2_UTIL_SPARSE_SET_H__
5,412
27.340314
72
h
openalpr
openalpr-master/src/openalpr/support/re2/util/test.h
// Copyright 2009 The RE2 Authors. All Rights Reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #ifndef RE2_UTIL_TEST_H__ #define RE2_UTIL_TEST_H__ #include "util/util.h" #include "util/flags.h" #define TEST(x, y) \ void x##y(void); \ TestRegisterer r##x##y(x##y, # x "." # y); \ void x##y(void) void RegisterTest(void (*)(void), const char*); class TestRegisterer { public: TestRegisterer(void (*fn)(void), const char *s) { RegisterTest(fn, s); } }; // TODO(rsc): Do a better job. #define EXPECT_EQ CHECK_EQ #define EXPECT_TRUE CHECK #define EXPECT_LT CHECK_LT #define EXPECT_GT CHECK_GT #define EXPECT_LE CHECK_LE #define EXPECT_GE CHECK_GE #define EXPECT_FALSE(x) CHECK(!(x)) const bool UsingMallocCounter = false; namespace testing { class MallocCounter { public: MallocCounter(int x) { } static const int THIS_THREAD_ONLY = 0; long long HeapGrowth() { return 0; } long long PeakHeapGrowth() { return 0; } void Reset() { } }; } // namespace testing namespace re2 { int64 VirtualProcessSize(); } // namespace re2 #endif // RE2_UTIL_TEST_H__
1,144
21.45098
56
h
openalpr
openalpr-master/src/openalpr/support/re2/util/utf.h
/* * The authors of this software are Rob Pike and Ken Thompson. * Copyright (c) 2002 by Lucent Technologies. * Permission to use, copy, modify, and distribute this software for any * purpose without fee is hereby granted, provided that this entire notice * is included in all copies of any software which is or includes a copy * or modification of this software and in all copies of the supporting * documentation for such software. * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED * WARRANTY. IN PARTICULAR, NEITHER THE AUTHORS NOR LUCENT TECHNOLOGIES MAKE ANY * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE. * * This file and rune.cc have been converted to compile as C++ code * in name space re2. */ #ifndef RE2_UTIL_UTF_H__ #define RE2_UTIL_UTF_H__ namespace re2 { typedef signed int Rune; /* Code-point values in Unicode 4.0 are 21 bits wide.*/ enum { UTFmax = 4, /* maximum bytes per rune */ Runesync = 0x80, /* cannot represent part of a UTF sequence (<) */ Runeself = 0x80, /* rune and UTF sequences are the same (<) */ Runeerror = 0xFFFD, /* decoding error in UTF */ Runemax = 0x10FFFF, /* maximum rune value */ }; int runetochar(char* s, const Rune* r); int chartorune(Rune* r, const char* s); int fullrune(const char* s, int n); int utflen(const char* s); char* utfrune(const char*, Rune); } // namespace re2 #endif // RE2_UTIL_UTF_H__
1,510
34.139535
81
h
openalpr
openalpr-master/src/openalpr/support/re2/util/util.h
// Copyright 2009 The RE2 Authors. All Rights Reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #ifndef RE2_UTIL_UTIL_H__ #define RE2_UTIL_UTIL_H__ // C #include <stdint.h> #include <stddef.h> // For size_t #if !defined(_WIN32) #include <sys/time.h> // For gettimeofday #endif // C++ #include <string> #ifdef _WIN32 #define snprintf _snprintf_s #define sprintf sprintf_s #define stricmp _stricmp #define strtof strtod /* not really correct but best we can do */ #define strtoll _strtoi64 #define strtoull _strtoui64 #define vsnprintf vsnprintf_s #pragma warning(disable: 4018) // signed/unsigned mismatch #pragma warning(disable: 4244) // possible data loss in int conversion #pragma warning(disable: 4800) // conversion from int to bool #endif namespace re2 { typedef int8_t int8; typedef uint8_t uint8; typedef int16_t int16; typedef uint16_t uint16; typedef int32_t int32; typedef uint32_t uint32; typedef int64_t int64; typedef uint64_t uint64; typedef unsigned long ulong; typedef unsigned int uint; typedef unsigned short ushort; // Prevent the compiler from complaining about or optimizing away variables // that appear unused. #undef ATTRIBUTE_UNUSED #if defined(__GNUC__) #define ATTRIBUTE_UNUSED __attribute__ ((unused)) #else #define ATTRIBUTE_UNUSED #endif // COMPILE_ASSERT causes a compile error about msg if expr is not true. #if __cplusplus >= 201103L #define COMPILE_ASSERT(expr, msg) static_assert(expr, #msg) #else template<bool> struct CompileAssert {}; #define COMPILE_ASSERT(expr, msg) \ typedef CompileAssert<(bool(expr))> msg[bool(expr) ? 1 : -1] ATTRIBUTE_UNUSED #endif // DISALLOW_COPY_AND_ASSIGN disallows the copy and operator= functions. // It goes in the private: declarations in a class. #define DISALLOW_COPY_AND_ASSIGN(TypeName) \ TypeName(const TypeName&); \ void operator=(const TypeName&) #define arraysize(array) (int)(sizeof(array)/sizeof((array)[0])) class StringPiece; std::string CEscape(const StringPiece& src); int CEscapeString(const char* src, int src_len, char* dest, int dest_len); extern std::string StringPrintf(const char* format, ...); extern void SStringPrintf(std::string* dst, const char* format, ...); extern void StringAppendF(std::string* dst, const char* format, ...); extern std::string PrefixSuccessor(const StringPiece& prefix); uint32 hashword(const uint32*, size_t, uint32); void hashword2(const uint32*, size_t, uint32*, uint32*); static inline uint32 Hash32StringWithSeed(const char* s, int len, uint32 seed) { return hashword((uint32*)s, len/4, seed); } static inline uint64 Hash64StringWithSeed(const char* s, int len, uint32 seed) { uint32 x, y; x = seed; y = 0; hashword2((uint32*)s, len/4, &x, &y); return ((uint64)x << 32) | y; } int RunningOnValgrind(); } // namespace re2 #include "re2/util/logging.h" #include "re2/util/mutex.h" #include "re2/util/utf.h" #endif // RE2_UTIL_UTIL_H__
2,988
26.172727
80
h
openalpr
openalpr-master/src/openalpr/support/utf8/checked.h
// Copyright 2006 Nemanja Trifunovic /* Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following: The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef UTF8_FOR_CPP_CHECKED_H_2675DCD0_9480_4c0c_B92A_CC14C027B731 #define UTF8_FOR_CPP_CHECKED_H_2675DCD0_9480_4c0c_B92A_CC14C027B731 #include "core.h" #include <stdexcept> namespace utf8 { // Base for the exceptions that may be thrown from the library class exception : public ::std::exception { }; // Exceptions that may be thrown from the library functions. class invalid_code_point : public exception { uint32_t cp; public: invalid_code_point(uint32_t cp) : cp(cp) {} virtual const char* what() const throw() { return "Invalid code point"; } uint32_t code_point() const {return cp;} }; class invalid_utf8 : public exception { uint8_t u8; public: invalid_utf8 (uint8_t u) : u8(u) {} virtual const char* what() const throw() { return "Invalid UTF-8"; } uint8_t utf8_octet() const {return u8;} }; class invalid_utf16 : public exception { uint16_t u16; public: invalid_utf16 (uint16_t u) : u16(u) {} virtual const char* what() const throw() { return "Invalid UTF-16"; } uint16_t utf16_word() const {return u16;} }; class not_enough_room : public exception { public: virtual const char* what() const throw() { return "Not enough space"; } }; /// The library API - functions intended to be called by the users template <typename octet_iterator> octet_iterator append(uint32_t cp, octet_iterator result) { if (!utf8::internal::is_code_point_valid(cp)) throw invalid_code_point(cp); if (cp < 0x80) // one octet *(result++) = static_cast<uint8_t>(cp); else if (cp < 0x800) { // two octets *(result++) = static_cast<uint8_t>((cp >> 6) | 0xc0); *(result++) = static_cast<uint8_t>((cp & 0x3f) | 0x80); } else if (cp < 0x10000) { // three octets *(result++) = static_cast<uint8_t>((cp >> 12) | 0xe0); *(result++) = static_cast<uint8_t>(((cp >> 6) & 0x3f) | 0x80); *(result++) = static_cast<uint8_t>((cp & 0x3f) | 0x80); } else { // four octets *(result++) = static_cast<uint8_t>((cp >> 18) | 0xf0); *(result++) = static_cast<uint8_t>(((cp >> 12) & 0x3f) | 0x80); *(result++) = static_cast<uint8_t>(((cp >> 6) & 0x3f) | 0x80); *(result++) = static_cast<uint8_t>((cp & 0x3f) | 0x80); } return result; } template <typename octet_iterator, typename output_iterator> output_iterator replace_invalid(octet_iterator start, octet_iterator end, output_iterator out, uint32_t replacement) { while (start != end) { octet_iterator sequence_start = start; internal::utf_error err_code = utf8::internal::validate_next(start, end); switch (err_code) { case internal::UTF8_OK : for (octet_iterator it = sequence_start; it != start; ++it) *out++ = *it; break; case internal::NOT_ENOUGH_ROOM: throw not_enough_room(); case internal::INVALID_LEAD: out = utf8::append (replacement, out); ++start; break; case internal::INCOMPLETE_SEQUENCE: case internal::OVERLONG_SEQUENCE: case internal::INVALID_CODE_POINT: out = utf8::append (replacement, out); ++start; // just one replacement mark for the sequence while (start != end && utf8::internal::is_trail(*start)) ++start; break; } } return out; } template <typename octet_iterator, typename output_iterator> inline output_iterator replace_invalid(octet_iterator start, octet_iterator end, output_iterator out) { static const uint32_t replacement_marker = utf8::internal::mask16(0xfffd); return utf8::replace_invalid(start, end, out, replacement_marker); } template <typename octet_iterator> uint32_t next(octet_iterator& it, octet_iterator end) { uint32_t cp = 0; internal::utf_error err_code = utf8::internal::validate_next(it, end, cp); switch (err_code) { case internal::UTF8_OK : break; case internal::NOT_ENOUGH_ROOM : throw not_enough_room(); case internal::INVALID_LEAD : case internal::INCOMPLETE_SEQUENCE : case internal::OVERLONG_SEQUENCE : throw invalid_utf8(*it); case internal::INVALID_CODE_POINT : throw invalid_code_point(cp); } return cp; } template <typename octet_iterator> uint32_t peek_next(octet_iterator it, octet_iterator end) { return utf8::next(it, end); } template <typename octet_iterator> uint32_t prior(octet_iterator& it, octet_iterator start) { // can't do much if it == start if (it == start) throw not_enough_room(); octet_iterator end = it; // Go back until we hit either a lead octet or start while (utf8::internal::is_trail(*(--it))) if (it == start) throw invalid_utf8(*it); // error - no lead byte in the sequence return utf8::peek_next(it, end); } /// Deprecated in versions that include "prior" template <typename octet_iterator> uint32_t previous(octet_iterator& it, octet_iterator pass_start) { octet_iterator end = it; while (utf8::internal::is_trail(*(--it))) if (it == pass_start) throw invalid_utf8(*it); // error - no lead byte in the sequence octet_iterator temp = it; return utf8::next(temp, end); } template <typename octet_iterator, typename distance_type> void advance (octet_iterator& it, distance_type n, octet_iterator end) { for (distance_type i = 0; i < n; ++i) utf8::next(it, end); } template <typename octet_iterator> typename std::iterator_traits<octet_iterator>::difference_type distance (octet_iterator first, octet_iterator last) { typename std::iterator_traits<octet_iterator>::difference_type dist; for (dist = 0; first < last; ++dist) utf8::next(first, last); return dist; } template <typename u16bit_iterator, typename octet_iterator> octet_iterator utf16to8 (u16bit_iterator start, u16bit_iterator end, octet_iterator result) { while (start != end) { uint32_t cp = utf8::internal::mask16(*start++); // Take care of surrogate pairs first if (utf8::internal::is_lead_surrogate(cp)) { if (start != end) { uint32_t trail_surrogate = utf8::internal::mask16(*start++); if (utf8::internal::is_trail_surrogate(trail_surrogate)) cp = (cp << 10) + trail_surrogate + internal::SURROGATE_OFFSET; else throw invalid_utf16(static_cast<uint16_t>(trail_surrogate)); } else throw invalid_utf16(static_cast<uint16_t>(cp)); } // Lone trail surrogate else if (utf8::internal::is_trail_surrogate(cp)) throw invalid_utf16(static_cast<uint16_t>(cp)); result = utf8::append(cp, result); } return result; } template <typename u16bit_iterator, typename octet_iterator> u16bit_iterator utf8to16 (octet_iterator start, octet_iterator end, u16bit_iterator result) { while (start != end) { uint32_t cp = utf8::next(start, end); if (cp > 0xffff) { //make a surrogate pair *result++ = static_cast<uint16_t>((cp >> 10) + internal::LEAD_OFFSET); *result++ = static_cast<uint16_t>((cp & 0x3ff) + internal::TRAIL_SURROGATE_MIN); } else *result++ = static_cast<uint16_t>(cp); } return result; } template <typename octet_iterator, typename u32bit_iterator> octet_iterator utf32to8 (u32bit_iterator start, u32bit_iterator end, octet_iterator result) { while (start != end) result = utf8::append(*(start++), result); return result; } template <typename octet_iterator, typename u32bit_iterator> u32bit_iterator utf8to32 (octet_iterator start, octet_iterator end, u32bit_iterator result) { while (start != end) (*result++) = utf8::next(start, end); return result; } // The iterator class template <typename octet_iterator> class iterator : public std::iterator <std::bidirectional_iterator_tag, uint32_t> { octet_iterator it; octet_iterator range_start; octet_iterator range_end; public: iterator () {} explicit iterator (const octet_iterator& octet_it, const octet_iterator& range_start, const octet_iterator& range_end) : it(octet_it), range_start(range_start), range_end(range_end) { if (it < range_start || it > range_end) throw std::out_of_range("Invalid utf-8 iterator position"); } // the default "big three" are OK octet_iterator base () const { return it; } uint32_t operator * () const { octet_iterator temp = it; return utf8::next(temp, range_end); } bool operator == (const iterator& rhs) const { if (range_start != rhs.range_start || range_end != rhs.range_end) throw std::logic_error("Comparing utf-8 iterators defined with different ranges"); return (it == rhs.it); } bool operator != (const iterator& rhs) const { return !(operator == (rhs)); } iterator& operator ++ () { utf8::next(it, range_end); return *this; } iterator operator ++ (int) { iterator temp = *this; utf8::next(it, range_end); return temp; } iterator& operator -- () { utf8::prior(it, range_start); return *this; } iterator operator -- (int) { iterator temp = *this; utf8::prior(it, range_start); return temp; } }; // class iterator } // namespace utf8 #endif //header guard
12,172
36.112805
120
h
openalpr
openalpr-master/src/openalpr/support/utf8/unchecked.h
// Copyright 2006 Nemanja Trifunovic /* Permission is hereby granted, free of charge, to any person or organization obtaining a copy of the software and accompanying documentation covered by this license (the "Software") to use, reproduce, display, distribute, execute, and transmit the Software, and to prepare derivative works of the Software, and to permit third-parties to whom the Software is furnished to do so, all subject to the following: The copyright notices in the Software and this entire statement, including the above license grant, this restriction and the following disclaimer, must be included in all copies of the Software, in whole or in part, and all derivative works of the Software, unless such copies or derivative works are solely in the form of machine-executable object code generated by a source language processor. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef UTF8_FOR_CPP_UNCHECKED_H_2675DCD0_9480_4c0c_B92A_CC14C027B731 #define UTF8_FOR_CPP_UNCHECKED_H_2675DCD0_9480_4c0c_B92A_CC14C027B731 #include "core.h" namespace utf8 { namespace unchecked { template <typename octet_iterator> octet_iterator append(uint32_t cp, octet_iterator result) { if (cp < 0x80) // one octet *(result++) = static_cast<uint8_t>(cp); else if (cp < 0x800) { // two octets *(result++) = static_cast<uint8_t>((cp >> 6) | 0xc0); *(result++) = static_cast<uint8_t>((cp & 0x3f) | 0x80); } else if (cp < 0x10000) { // three octets *(result++) = static_cast<uint8_t>((cp >> 12) | 0xe0); *(result++) = static_cast<uint8_t>(((cp >> 6) & 0x3f) | 0x80); *(result++) = static_cast<uint8_t>((cp & 0x3f) | 0x80); } else { // four octets *(result++) = static_cast<uint8_t>((cp >> 18) | 0xf0); *(result++) = static_cast<uint8_t>(((cp >> 12) & 0x3f)| 0x80); *(result++) = static_cast<uint8_t>(((cp >> 6) & 0x3f) | 0x80); *(result++) = static_cast<uint8_t>((cp & 0x3f) | 0x80); } return result; } template <typename octet_iterator> uint32_t next(octet_iterator& it) { uint32_t cp = utf8::internal::mask8(*it); typename std::iterator_traits<octet_iterator>::difference_type length = utf8::internal::sequence_length(it); switch (length) { case 1: break; case 2: it++; cp = ((cp << 6) & 0x7ff) + ((*it) & 0x3f); break; case 3: ++it; cp = ((cp << 12) & 0xffff) + ((utf8::internal::mask8(*it) << 6) & 0xfff); ++it; cp += (*it) & 0x3f; break; case 4: ++it; cp = ((cp << 18) & 0x1fffff) + ((utf8::internal::mask8(*it) << 12) & 0x3ffff); ++it; cp += (utf8::internal::mask8(*it) << 6) & 0xfff; ++it; cp += (*it) & 0x3f; break; } ++it; return cp; } template <typename octet_iterator> uint32_t peek_next(octet_iterator it) { return utf8::unchecked::next(it); } template <typename octet_iterator> uint32_t prior(octet_iterator& it) { while (utf8::internal::is_trail(*(--it))) ; octet_iterator temp = it; return utf8::unchecked::next(temp); } // Deprecated in versions that include prior, but only for the sake of consistency (see utf8::previous) template <typename octet_iterator> inline uint32_t previous(octet_iterator& it) { return utf8::unchecked::prior(it); } template <typename octet_iterator, typename distance_type> void advance (octet_iterator& it, distance_type n) { for (distance_type i = 0; i < n; ++i) utf8::unchecked::next(it); } template <typename octet_iterator> typename std::iterator_traits<octet_iterator>::difference_type distance (octet_iterator first, octet_iterator last) { typename std::iterator_traits<octet_iterator>::difference_type dist; for (dist = 0; first < last; ++dist) utf8::unchecked::next(first); return dist; } template <typename u16bit_iterator, typename octet_iterator> octet_iterator utf16to8 (u16bit_iterator start, u16bit_iterator end, octet_iterator result) { while (start != end) { uint32_t cp = utf8::internal::mask16(*start++); // Take care of surrogate pairs first if (utf8::internal::is_lead_surrogate(cp)) { uint32_t trail_surrogate = utf8::internal::mask16(*start++); cp = (cp << 10) + trail_surrogate + internal::SURROGATE_OFFSET; } result = utf8::unchecked::append(cp, result); } return result; } template <typename u16bit_iterator, typename octet_iterator> u16bit_iterator utf8to16 (octet_iterator start, octet_iterator end, u16bit_iterator result) { while (start < end) { uint32_t cp = utf8::unchecked::next(start); if (cp > 0xffff) { //make a surrogate pair *result++ = static_cast<uint16_t>((cp >> 10) + internal::LEAD_OFFSET); *result++ = static_cast<uint16_t>((cp & 0x3ff) + internal::TRAIL_SURROGATE_MIN); } else *result++ = static_cast<uint16_t>(cp); } return result; } template <typename octet_iterator, typename u32bit_iterator> octet_iterator utf32to8 (u32bit_iterator start, u32bit_iterator end, octet_iterator result) { while (start != end) result = utf8::unchecked::append(*(start++), result); return result; } template <typename octet_iterator, typename u32bit_iterator> u32bit_iterator utf8to32 (octet_iterator start, octet_iterator end, u32bit_iterator result) { while (start < end) (*result++) = utf8::unchecked::next(start); return result; } // The iterator class template <typename octet_iterator> class iterator : public std::iterator <std::bidirectional_iterator_tag, uint32_t> { octet_iterator it; public: iterator () {} explicit iterator (const octet_iterator& octet_it): it(octet_it) {} // the default "big three" are OK octet_iterator base () const { return it; } uint32_t operator * () const { octet_iterator temp = it; return utf8::unchecked::next(temp); } bool operator == (const iterator& rhs) const { return (it == rhs.it); } bool operator != (const iterator& rhs) const { return !(operator == (rhs)); } iterator& operator ++ () { ::std::advance(it, utf8::internal::sequence_length(it)); return *this; } iterator operator ++ (int) { iterator temp = *this; ::std::advance(it, utf8::internal::sequence_length(it)); return temp; } iterator& operator -- () { utf8::unchecked::prior(it); return *this; } iterator operator -- (int) { iterator temp = *this; utf8::unchecked::prior(it); return temp; } }; // class iterator } // namespace utf8::unchecked } // namespace utf8 #endif // header guard
8,907
37.899563
120
h
openalpr
openalpr-master/src/openalpr/support/windows/dirent.h
/* * dirent.h - dirent API for Microsoft Visual Studio * * Copyright (C) 2006-2012 Toni Ronkko * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * ``Software''), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL TONI RONKKO BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * * Version 1.13, Dec 12 2012, Toni Ronkko * Use traditional 8+3 file name if the name cannot be represented in the * default ANSI code page. Now compiles again with MSVC 6.0. Thanks to * Konstantin Khomoutov for testing. * * Version 1.12.1, Oct 1 2012, Toni Ronkko * Bug fix: renamed wide-character DIR structure _wDIR to _WDIR (with * capital W) in order to maintain compatibility with MingW. * * Version 1.12, Sep 30 2012, Toni Ronkko * Define PATH_MAX and NAME_MAX. Added wide-character variants _wDIR, * _wdirent, _wopendir(), _wreaddir(), _wclosedir() and _wrewinddir(). * Thanks to Edgar Buerkle and Jan Nijtmans for ideas and code. * * Do not include windows.h. This allows dirent.h to be integrated more * easily into programs using winsock. Thanks to Fernando Azaldegui. * * Version 1.11, Mar 15, 2011, Toni Ronkko * Defined FILE_ATTRIBUTE_DEVICE for MSVC 6.0. * * Version 1.10, Aug 11, 2010, Toni Ronkko * Added d_type and d_namlen fields to dirent structure. The former is * especially useful for determining whether directory entry represents a * file or a directory. For more information, see * http://www.delorie.com/gnu/docs/glibc/libc_270.html * * Improved conformance to the standards. For example, errno is now set * properly on failure and assert() is never used. Thanks to Peter Brockam * for suggestions. * * Fixed a bug in rewinddir(): when using relative directory names, change * of working directory no longer causes rewinddir() to fail. * * Version 1.9, Dec 15, 2009, John Cunningham * Added rewinddir member function * * Version 1.8, Jan 18, 2008, Toni Ronkko * Using FindFirstFileA and WIN32_FIND_DATAA to avoid converting string * between multi-byte and unicode representations. This makes the * code simpler and also allows the code to be compiled under MingW. Thanks * to Azriel Fasten for the suggestion. * * Mar 4, 2007, Toni Ronkko * Bug fix: due to the strncpy_s() function this file only compiled in * Visual Studio 2005. Using the new string functions only when the * compiler version allows. * * Nov 2, 2006, Toni Ronkko * Major update: removed support for Watcom C, MS-DOS and Turbo C to * simplify the file, updated the code to compile cleanly on Visual * Studio 2005 with both unicode and multi-byte character strings, * removed rewinddir() as it had a bug. * * Aug 20, 2006, Toni Ronkko * Removed all remarks about MSVC 1.0, which is antiqued now. Simplified * comments by removing SGML tags. * * May 14 2002, Toni Ronkko * Embedded the function definitions directly to the header so that no * source modules need to be included in the Visual Studio project. Removed * all the dependencies to other projects so that this header file can be * used independently. * * May 28 1998, Toni Ronkko * First version. *****************************************************************************/ #ifndef DIRENT_H #define DIRENT_H #if !defined(_68K_) && !defined(_MPPC_) && !defined(_X86_) && !defined(_IA64_) && !defined(_AMD64_) && defined(_M_IX86) # define _X86_ #endif #include <stdio.h> #include <stdarg.h> #include <windef.h> #include <winbase.h> #include <wchar.h> #include <string.h> #include <stdlib.h> #include <malloc.h> #include <sys/types.h> #include <sys/stat.h> #include <errno.h> /* Indicates that d_type field is available in dirent structure */ #define _DIRENT_HAVE_D_TYPE /* Indicates that d_namlen field is available in dirent structure */ #define _DIRENT_HAVE_D_NAMLEN /* Entries missing from MSVC 6.0 */ #if !defined(FILE_ATTRIBUTE_DEVICE) # define FILE_ATTRIBUTE_DEVICE 0x40 #endif /* File type and permission flags for stat() */ #if !defined(S_IFMT) # define S_IFMT _S_IFMT /* File type mask */ #endif #if !defined(S_IFDIR) # define S_IFDIR _S_IFDIR /* Directory */ #endif #if !defined(S_IFCHR) # define S_IFCHR _S_IFCHR /* Character device */ #endif #if !defined(S_IFFIFO) # define S_IFFIFO _S_IFFIFO /* Pipe */ #endif #if !defined(S_IFREG) # define S_IFREG _S_IFREG /* Regular file */ #endif #if !defined(S_IREAD) # define S_IREAD _S_IREAD /* Read permission */ #endif #if !defined(S_IWRITE) # define S_IWRITE _S_IWRITE /* Write permission */ #endif #if !defined(S_IEXEC) # define S_IEXEC _S_IEXEC /* Execute permission */ #endif #if !defined(S_IFIFO) # define S_IFIFO _S_IFIFO /* Pipe */ #endif #if !defined(S_IFBLK) # define S_IFBLK 0 /* Block device */ #endif #if !defined(S_IFLNK) # define S_IFLNK 0 /* Link */ #endif #if !defined(S_IFSOCK) # define S_IFSOCK 0 /* Socket */ #endif #if defined(_MSC_VER) # define S_IRUSR S_IREAD /* Read user */ # define S_IWUSR S_IWRITE /* Write user */ # define S_IXUSR 0 /* Execute user */ # define S_IRGRP 0 /* Read group */ # define S_IWGRP 0 /* Write group */ # define S_IXGRP 0 /* Execute group */ # define S_IROTH 0 /* Read others */ # define S_IWOTH 0 /* Write others */ # define S_IXOTH 0 /* Execute others */ #endif /* Maximum length of file name */ #if !defined(PATH_MAX) # define PATH_MAX MAX_PATH #endif #if !defined(FILENAME_MAX) # define FILENAME_MAX MAX_PATH #endif #if !defined(NAME_MAX) # define NAME_MAX FILENAME_MAX #endif /* File type flags for d_type */ #define DT_UNKNOWN 0 #define DT_REG S_IFREG #define DT_DIR S_IFDIR #define DT_FIFO S_IFIFO #define DT_SOCK S_IFSOCK #define DT_CHR S_IFCHR #define DT_BLK S_IFBLK /* Macros for converting between st_mode and d_type */ #define IFTODT(mode) ((mode) & S_IFMT) #define DTTOIF(type) (type) /* * File type macros. Note that block devices, sockets and links cannot be * distinguished on Windows and the macros S_ISBLK, S_ISSOCK and S_ISLNK are * only defined for compatibility. These macros should always return false * on Windows. */ #define S_ISFIFO(mode) (((mode) & S_IFMT) == S_IFIFO) #define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR) #define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG) #define S_ISLNK(mode) (((mode) & S_IFMT) == S_IFLNK) #define S_ISSOCK(mode) (((mode) & S_IFMT) == S_IFSOCK) #define S_ISCHR(mode) (((mode) & S_IFMT) == S_IFCHR) #define S_ISBLK(mode) (((mode) & S_IFMT) == S_IFBLK) /* Return the exact length of d_namlen without zero terminator */ #define _D_EXACT_NAMLEN(p) ((p)->d_namlen) /* Return number of bytes needed to store d_namlen */ #define _D_ALLOC_NAMLEN(p) (PATH_MAX + 1) #ifdef __cplusplus extern "C" { #endif /* Wide-character version */ struct _wdirent { long d_ino; /* Always zero */ unsigned short d_reclen; /* Structure size */ size_t d_namlen; /* Length of name without \0 */ int d_type; /* File type */ wchar_t d_name[PATH_MAX + 1]; /* File name */ }; typedef struct _wdirent _wdirent; struct _WDIR { struct _wdirent ent; /* Current directory entry */ WIN32_FIND_DATAW data; /* Private file data */ int cached; /* True if data is valid */ HANDLE handle; /* Win32 search handle */ wchar_t *patt; /* Initial directory name */ }; typedef struct _WDIR _WDIR; static _WDIR *_wopendir (const wchar_t *dirname); static struct _wdirent *_wreaddir (_WDIR *dirp); static int _wclosedir (_WDIR *dirp); static void _wrewinddir (_WDIR* dirp); /* For compatibility with Symbian */ #define wdirent _wdirent #define WDIR _WDIR #define wopendir _wopendir #define wreaddir _wreaddir #define wclosedir _wclosedir #define wrewinddir _wrewinddir /* Multi-byte character versions */ struct dirent { long d_ino; /* Always zero */ unsigned short d_reclen; /* Structure size */ size_t d_namlen; /* Length of name without \0 */ int d_type; /* File type */ char d_name[PATH_MAX + 1]; /* File name */ }; typedef struct dirent dirent; struct DIR { struct dirent ent; struct _WDIR *wdirp; }; typedef struct DIR DIR; static DIR *opendir (const char *dirname); static struct dirent *readdir (DIR *dirp); static int closedir (DIR *dirp); static void rewinddir (DIR* dirp); /* Internal utility functions */ static WIN32_FIND_DATAW *dirent_first (_WDIR *dirp); static WIN32_FIND_DATAW *dirent_next (_WDIR *dirp); static int dirent_mbstowcs_s( size_t *pReturnValue, wchar_t *wcstr, size_t sizeInWords, const char *mbstr, size_t count); static int dirent_wcstombs_s( size_t *pReturnValue, char *mbstr, size_t sizeInBytes, const wchar_t *wcstr, size_t count); static void dirent_set_errno (int error); /* * Open directory stream DIRNAME for read and return a pointer to the * internal working area that is used to retrieve individual directory * entries. */ static _WDIR* _wopendir( const wchar_t *dirname) { _WDIR *dirp = NULL; int error; /* Must have directory name */ if (dirname == NULL || dirname[0] == '\0') { dirent_set_errno (ENOENT); return NULL; } /* Allocate new _WDIR structure */ dirp = (_WDIR*) malloc (sizeof (struct _WDIR)); if (dirp != NULL) { DWORD n; /* Reset _WDIR structure */ dirp->handle = INVALID_HANDLE_VALUE; dirp->patt = NULL; dirp->cached = 0; /* Compute the length of full path plus zero terminator */ n = GetFullPathNameW (dirname, 0, NULL, NULL); /* Allocate room for absolute directory name and search pattern */ dirp->patt = (wchar_t*) malloc (sizeof (wchar_t) * n + 16); if (dirp->patt) { /* * Convert relative directory name to an absolute one. This * allows rewinddir() to function correctly even when current * working directory is changed between opendir() and rewinddir(). */ n = GetFullPathNameW (dirname, n, dirp->patt, NULL); if (n > 0) { wchar_t *p; /* Append search pattern \* to the directory name */ p = dirp->patt + n; if (dirp->patt < p) { switch (p[-1]) { case '\\': case '/': case ':': /* Directory ends in path separator, e.g. c:\temp\ */ /*NOP*/ ; break; default: /* Directory name doesn't end in path separator */ *p++ = '\\'; } } *p++ = '*'; *p = '\0'; /* Open directory stream and retrieve the first entry */ if (dirent_first (dirp)) { /* Directory stream opened successfully */ error = 0; } else { /* Cannot retrieve first entry */ error = 1; dirent_set_errno (ENOENT); } } else { /* Cannot retrieve full path name */ dirent_set_errno (ENOENT); error = 1; } } else { /* Cannot allocate memory for search pattern */ error = 1; } } else { /* Cannot allocate _WDIR structure */ error = 1; } /* Clean up in case of error */ if (error && dirp) { _wclosedir (dirp); dirp = NULL; } return dirp; } /* * Read next directory entry. The directory entry is returned in dirent * structure in the d_name field. Individual directory entries returned by * this function include regular files, sub-directories, pseudo-directories * "." and ".." as well as volume labels, hidden files and system files. */ static struct _wdirent* _wreaddir( _WDIR *dirp) { WIN32_FIND_DATAW *datap; struct _wdirent *entp; /* Read next directory entry */ datap = dirent_next (dirp); if (datap) { size_t n; DWORD attr; /* Pointer to directory entry to return */ entp = &dirp->ent; /* * Copy file name as wide-character string. If the file name is too * long to fit in to the destination buffer, then truncate file name * to PATH_MAX characters and zero-terminate the buffer. */ n = 0; while (n < PATH_MAX && datap->cFileName[n] != 0) { entp->d_name[n] = datap->cFileName[n]; n++; } dirp->ent.d_name[n] = 0; /* Length of file name excluding zero terminator */ entp->d_namlen = n; /* File type */ attr = datap->dwFileAttributes; if ((attr & FILE_ATTRIBUTE_DEVICE) != 0) { entp->d_type = DT_CHR; } else if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) { entp->d_type = DT_DIR; } else { entp->d_type = DT_REG; } /* Reset dummy fields */ entp->d_ino = 0; entp->d_reclen = sizeof (struct _wdirent); } else { /* Last directory entry read */ entp = NULL; } return entp; } /* * Close directory stream opened by opendir() function. This invalidates the * DIR structure as well as any directory entry read previously by * _wreaddir(). */ static int _wclosedir( _WDIR *dirp) { int ok; if (dirp) { /* Release search handle */ if (dirp->handle != INVALID_HANDLE_VALUE) { FindClose (dirp->handle); dirp->handle = INVALID_HANDLE_VALUE; } /* Release search pattern */ if (dirp->patt) { free (dirp->patt); dirp->patt = NULL; } /* Release directory structure */ free (dirp); ok = /*success*/0; } else { /* Invalid directory stream */ dirent_set_errno (EBADF); ok = /*failure*/-1; } return ok; } /* * Rewind directory stream such that _wreaddir() returns the very first * file name again. */ static void _wrewinddir( _WDIR* dirp) { if (dirp) { /* Release existing search handle */ if (dirp->handle != INVALID_HANDLE_VALUE) { FindClose (dirp->handle); } /* Open new search handle */ dirent_first (dirp); } } /* Get first directory entry (internal) */ static WIN32_FIND_DATAW* dirent_first( _WDIR *dirp) { WIN32_FIND_DATAW *datap; /* Open directory and retrieve the first entry */ dirp->handle = FindFirstFileW (dirp->patt, &dirp->data); if (dirp->handle != INVALID_HANDLE_VALUE) { /* a directory entry is now waiting in memory */ datap = &dirp->data; dirp->cached = 1; } else { /* Failed to re-open directory: no directory entry in memory */ dirp->cached = 0; datap = NULL; } return datap; } /* Get next directory entry (internal) */ static WIN32_FIND_DATAW* dirent_next( _WDIR *dirp) { WIN32_FIND_DATAW *p; /* Get next directory entry */ if (dirp->cached != 0) { /* A valid directory entry already in memory */ p = &dirp->data; dirp->cached = 0; } else if (dirp->handle != INVALID_HANDLE_VALUE) { /* Get the next directory entry from stream */ if (FindNextFileW (dirp->handle, &dirp->data) != FALSE) { /* Got a file */ p = &dirp->data; } else { /* The very last entry has been processed or an error occurred */ FindClose (dirp->handle); dirp->handle = INVALID_HANDLE_VALUE; p = NULL; } } else { /* End of directory stream reached */ p = NULL; } return p; } /* * Open directory stream using plain old C-string. */ static DIR* opendir( const char *dirname) { struct DIR *dirp; int error; /* Must have directory name */ if (dirname == NULL || dirname[0] == '\0') { dirent_set_errno (ENOENT); return NULL; } /* Allocate memory for DIR structure */ dirp = (DIR*) malloc (sizeof (struct DIR)); if (dirp) { wchar_t wname[PATH_MAX + 1]; size_t n; /* Convert directory name to wide-character string */ error = dirent_mbstowcs_s( &n, wname, PATH_MAX + 1, dirname, PATH_MAX); if (!error) { /* Open directory stream using wide-character name */ dirp->wdirp = _wopendir (wname); if (dirp->wdirp) { /* Directory stream opened */ error = 0; } else { /* Failed to open directory stream */ error = 1; } } else { /* * Cannot convert file name to wide-character string. This * occurs if the string contains invalid multi-byte sequences or * the output buffer is too small to contain the resulting * string. */ error = 1; } } else { /* Cannot allocate DIR structure */ error = 1; } /* Clean up in case of error */ if (error && dirp) { free (dirp); dirp = NULL; } return dirp; } /* * Read next directory entry. * * When working with text consoles, please note that file names returned by * readdir() are represented in the default ANSI code page while any output to * console is typically formatted on another code page. Thus, non-ASCII * characters in file names will not usually display correctly on console. The * problem can be fixed in two ways: (1) change the character set of console * to 1252 using chcp utility and use Lucida Console font, or (2) use * _cprintf function when writing to console. The _cprinf() will re-encode * ANSI strings to the console code page so many non-ASCII characters will * display correcly. */ static struct dirent* readdir( DIR *dirp) { WIN32_FIND_DATAW *datap; struct dirent *entp; /* Read next directory entry */ datap = dirent_next (dirp->wdirp); if (datap) { size_t n; int error; /* Attempt to convert file name to multi-byte string */ error = dirent_wcstombs_s( &n, dirp->ent.d_name, MAX_PATH + 1, datap->cFileName, MAX_PATH); /* * If the file name cannot be represented by a multi-byte string, * then attempt to use old 8+3 file name. This allows traditional * Unix-code to access some file names despite of unicode * characters, although file names may seem unfamiliar to the user. * * Be ware that the code below cannot come up with a short file * name unless the file system provides one. At least * VirtualBox shared folders fail to do this. */ if (error && datap->cAlternateFileName[0] != '\0') { error = dirent_wcstombs_s( &n, dirp->ent.d_name, MAX_PATH + 1, datap->cAlternateFileName, sizeof (datap->cAlternateFileName) / sizeof (datap->cAlternateFileName[0])); } if (!error) { DWORD attr; /* Initialize directory entry for return */ entp = &dirp->ent; /* Length of file name excluding zero terminator */ entp->d_namlen = n - 1; /* File attributes */ attr = datap->dwFileAttributes; if ((attr & FILE_ATTRIBUTE_DEVICE) != 0) { entp->d_type = DT_CHR; } else if ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) { entp->d_type = DT_DIR; } else { entp->d_type = DT_REG; } /* Reset dummy fields */ entp->d_ino = 0; entp->d_reclen = sizeof (struct dirent); } else { /* * Cannot convert file name to multi-byte string so construct * an errornous directory entry and return that. Note that * we cannot return NULL as that would stop the processing * of directory entries completely. */ entp = &dirp->ent; entp->d_name[0] = '?'; entp->d_name[1] = '\0'; entp->d_namlen = 1; entp->d_type = DT_UNKNOWN; entp->d_ino = 0; entp->d_reclen = 0; } } else { /* No more directory entries */ entp = NULL; } return entp; } /* * Close directory stream. */ static int closedir( DIR *dirp) { int ok; if (dirp) { /* Close wide-character directory stream */ ok = _wclosedir (dirp->wdirp); dirp->wdirp = NULL; /* Release multi-byte character version */ free (dirp); } else { /* Invalid directory stream */ dirent_set_errno (EBADF); ok = /*failure*/-1; } return ok; } /* * Rewind directory stream to beginning. */ static void rewinddir( DIR* dirp) { /* Rewind wide-character string directory stream */ _wrewinddir (dirp->wdirp); } /* Convert multi-byte string to wide character string */ static int dirent_mbstowcs_s( size_t *pReturnValue, wchar_t *wcstr, size_t sizeInWords, const char *mbstr, size_t count) { int error; #if defined(_MSC_VER) && _MSC_VER >= 1400 /* Microsoft Visual Studio 2005 or later */ error = mbstowcs_s (pReturnValue, wcstr, sizeInWords, mbstr, count); #else /* Older Visual Studio or non-Microsoft compiler */ size_t n; /* Convert to wide-character string */ n = mbstowcs (wcstr, mbstr, count); if (n < sizeInWords) { /* Zero-terminate output buffer */ if (wcstr) { wcstr[n] = 0; } /* Length of resuting multi-byte string WITH zero terminator */ if (pReturnValue) { *pReturnValue = n + 1; } /* Success */ error = 0; } else { /* Could not convert string */ error = 1; } #endif return error; } /* Convert wide-character string to multi-byte string */ static int dirent_wcstombs_s( size_t *pReturnValue, char *mbstr, size_t sizeInBytes, const wchar_t *wcstr, size_t count) { int error; #if defined(_MSC_VER) && _MSC_VER >= 1400 /* Microsoft Visual Studio 2005 or later */ error = wcstombs_s (pReturnValue, mbstr, sizeInBytes, wcstr, count); #else /* Older Visual Studio or non-Microsoft compiler */ size_t n; /* Convert to multi-byte string */ n = wcstombs (mbstr, wcstr, count); if (n < sizeInBytes) { /* Zero-terminate output buffer */ if (mbstr) { mbstr[n] = '\0'; } /* Length of resulting multi-bytes string WITH zero-terminator */ if (pReturnValue) { *pReturnValue = n + 1; } /* Success */ error = 0; } else { /* Cannot convert string */ error = 1; } #endif return error; } /* Set errno variable */ static void dirent_set_errno( int error) { #if defined(_MSC_VER) /* Microsoft Visual Studio */ _set_errno (error); #else /* Non-Microsoft compiler */ errno = error; #endif } #ifdef __cplusplus } #endif #endif /*DIRENT_H*/
23,732
26.123429
119
h
openalpr
openalpr-master/src/openalpr/support/windows/unistd_partial.h
#ifndef _UNISTD_H #define _UNISTD_H 1 /* This file intended to serve as a drop-in replacement for * unistd.h on Windows * Please add functionality as neeeded */ #include <stdlib.h> #include <io.h> //#include <getopt.h> /* getopt from: http://www.pwilson.net/sample.html. */ #include <process.h> /* for getpid() and the exec..() family */ #define srandom srand #define random rand /* Values for the second argument to access. These may be OR'd together. */ #define R_OK 4 /* Test for read permission. */ #define W_OK 2 /* Test for write permission. */ //#define X_OK 1 /* execute permission - unsupported in windows*/ #define F_OK 0 /* Test for existence. */ #define access _access #define ftruncate _chsize #define ssize_t int #define STDIN_FILENO 0 #define STDOUT_FILENO 1 #define STDERR_FILENO 2 /* should be in some equivalent to <sys/types.h> */ //typedef __int8 int8_t; typedef __int16 int16_t; typedef __int32 int32_t; typedef __int64 int64_t; typedef unsigned __int8 uint8_t; typedef unsigned __int16 uint16_t; typedef unsigned __int32 uint32_t; typedef unsigned __int64 uint64_t; #endif /* unistd.h */
1,218
27.348837
76
h
openalpr
openalpr-master/src/openalpr/textdetection/characteranalysis.h
/* * Copyright (c) 2015 OpenALPR Technology, Inc. * Open source Automated License Plate Recognition [http://www.openalpr.com] * * This file is part of OpenALPR. * * OpenALPR is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License * version 3 as published by the Free Software Foundation * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef OPENALPR_CHARACTERANALYSIS_H #define OPENALPR_CHARACTERANALYSIS_H #include <algorithm> #include "opencv2/imgproc/imgproc.hpp" #include "utility.h" #include "config.h" #include "pipeline_data.h" #include "textcontours.h" #include "platemask.h" #include "linefinder.h" namespace alpr { class CharacterAnalysis { public: CharacterAnalysis(PipelineData* pipeline_data); virtual ~CharacterAnalysis(); cv::Mat bestThreshold; TextContours bestContours; std::vector<TextContours> allTextContours; void analyze(); cv::Mat getCharacterMask(); private: PipelineData* pipeline_data; Config* config; bool isPlateInverted(); void filter(cv::Mat img, TextContours& textContours); void filterByBoxSize(TextContours& textContours, int minHeightPx, int maxHeightPx); void filterByParentContour( TextContours& textContours ); void filterContourHoles(TextContours& textContours); void filterByOuterMask(TextContours& textContours); std::vector<cv::Point> getCharArea(LineSegment topLine, LineSegment bottomLine); void filterBetweenLines(cv::Mat img, TextContours& textContours, std::vector<TextLine> textLines ); }; } #endif // OPENALPR_CHARACTERANALYSIS_H
2,047
26.675676
105
h
openalpr
openalpr-master/src/openalpr/textdetection/linefinder.h
/* * Copyright (c) 2015 OpenALPR Technology, Inc. * Open source Automated License Plate Recognition [http://www.openalpr.com] * * This file is part of OpenALPR. * * OpenALPR is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License * version 3 as published by the Free Software Foundation * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // This class finds lines of text given an array of contours #ifndef OPENALPR_LINEFINDER_H #define OPENALPR_LINEFINDER_H #include "opencv2/imgproc/imgproc.hpp" #include "textcontours.h" #include "textline.h" #include "pipeline_data.h" #include "ocr/segmentation/histogramhorizontal.h" namespace alpr { class CharPointInfo { public: CharPointInfo(std::vector<cv::Point> contour, int index); cv::Rect boundingBox; cv::Point top; cv::Point bottom; int contourIndex; }; class LineFinder { public: LineFinder(PipelineData* pipeline_data); virtual ~LineFinder(); std::vector<std::vector<cv::Point> > findLines(cv::Mat image, const TextContours contours); private: PipelineData* pipeline_data; // Returns 4 points, counter clockwise that bound the detected character area std::vector<cv::Point> getBestLine(const TextContours contours, std::vector<CharPointInfo> charPoints); // Extends the top and bottom lines to the left and right edge of the image. Returns 4 points, counter clockwise. std::vector<cv::Point> extendToEdges(cv::Size imageSize, std::vector<cv::Point> charArea); std::vector<cv::Point> findNextBestLine(cv::Size imageSize, std::vector<cv::Point> bestLine); // Gets a polygon that covers the entire area we wish to run a horizontal histogram over // This needs to be done to handle rotation/skew std::vector<cv::Point> calculateCroppedRegionForHistogram(cv::Size imageSize, std::vector<cv::Point> charArea); }; } #endif /* OPENALPR_LINEFINDER_H */
2,333
31.873239
118
h
openalpr
openalpr-master/src/openalpr/textdetection/platemask.h
/* * Copyright (c) 2015 OpenALPR Technology, Inc. * Open source Automated License Plate Recognition [http://www.openalpr.com] * * This file is part of OpenALPR. * * OpenALPR is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License * version 3 as published by the Free Software Foundation * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef OPENALPR_PLATEMASK_H #define OPENALPR_PLATEMASK_H #include "opencv2/imgproc/imgproc.hpp" #include "pipeline_data.h" #include "textcontours.h" namespace alpr { class PlateMask { public: PlateMask(PipelineData* pipeline_data); virtual ~PlateMask(); bool hasPlateMask; cv::Mat getMask(); void findOuterBoxMask(std::vector<TextContours > contours); private: PipelineData* pipeline_data; cv::Mat plateMask; }; } #endif /* OPENALPR_PLATEMASK_H */
1,265
23.346154
76
h
openalpr
openalpr-master/src/openalpr/textdetection/textcontours.h
/* * Copyright (c) 2015 OpenALPR Technology, Inc. * Open source Automated License Plate Recognition [http://www.openalpr.com] * * This file is part of OpenALPR. * * OpenALPR is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License * version 3 as published by the Free Software Foundation * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef TEXTCONTOURS_H #define TEXTCONTOURS_H #include <vector> #include "opencv2/imgproc/imgproc.hpp" namespace alpr { class TextContours { public: TextContours(); TextContours(cv::Mat threshold); virtual ~TextContours(); void load(cv::Mat threshold); int width; int height; std::vector<bool> goodIndices; std::vector<std::vector<cv::Point> > contours; std::vector<cv::Vec4i> hierarchy; unsigned int size(); int getGoodIndicesCount(); std::vector<bool> getIndicesCopy(); void setIndices(std::vector<bool> newIndices); cv::Mat drawDebugImage() const; cv::Mat drawDebugImage(cv::Mat baseImage) const; private: }; } #endif /* TEXTCONTOURS_H */
1,493
23.096774
76
h
openalpr
openalpr-master/src/openalpr/textdetection/textline.h
/* * Copyright (c) 2015 OpenALPR Technology, Inc. * Open source Automated License Plate Recognition [http://www.openalpr.com] * * This file is part of OpenALPR. * * OpenALPR is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License * version 3 as published by the Free Software Foundation * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef OPENALPR_TEXTLINE_H #define OPENALPR_TEXTLINE_H #include "utility.h" #include "opencv2/imgproc/imgproc.hpp" namespace alpr { class TextLine { public: TextLine(std::vector<cv::Point> textArea, std::vector<cv::Point> linePolygon, cv::Size imgSize); TextLine(std::vector<cv::Point2f> textArea, std::vector<cv::Point2f> linePolygon, cv::Size imgSize); virtual ~TextLine(); std::vector<cv::Point> linePolygon; std::vector<cv::Point> textArea; LineSegment topLine; LineSegment bottomLine; LineSegment charBoxTop; LineSegment charBoxBottom; LineSegment charBoxLeft; LineSegment charBoxRight; float lineHeight; float angle; cv::Mat drawDebugImage(cv::Mat baseImage); private: void initialize(std::vector<cv::Point> textArea, std::vector<cv::Point> linePolygon, cv::Size imgSize); }; } #endif /* OPENALPR_TEXTLINE_H */
1,667
26.8
107
h
openalpr
openalpr-master/src/statedetection/line_segment.h
/* * Copyright (c) 2015 OpenALPR Technology, Inc. * Open source Automated License Plate Recognition [http://www.openalpr.com] * * This file is part of OpenALPR. * * OpenALPR is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License * version 3 as published by the Free Software Foundation * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef OPENALPR_LINE_SEGMENT_H #define OPENALPR_LINE_SEGMENT_H #include "opencv2/core/core.hpp" class LineSegment { public: cv::Point p1, p2; float slope; float length; float angle; // LineSegment(Point point1, Point point2); LineSegment(); LineSegment(int x1, int y1, int x2, int y2); LineSegment(cv::Point p1, cv::Point p2); void init(int x1, int y1, int x2, int y2); bool isPointBelowLine(cv::Point tp); float getPointAt(float x); cv::Point closestPointOnSegmentTo(cv::Point p); cv::Point intersection(LineSegment line); LineSegment getParallelLine(float distance); cv::Point midpoint(); inline std::string str() { std::stringstream ss; ss << "(" << p1.x << ", " << p1.y << ") : (" << p2.x << ", " << p2.y << ")"; return ss.str() ; } private: double distanceBetweenPoints(cv::Point p1, cv::Point p2); float angleBetweenPoints(cv::Point p1, cv::Point p2); }; #endif //OPENALPR_LINE_SEGMENT_H
1,733
24.5
80
h
openalpr
openalpr-master/src/statedetection/state_detector.h
/* * Copyright (c) 2015 OpenALPR Technology, Inc. * Open source Automated License Plate Recognition [http://www.openalpr.com] * * This file is part of OpenALPR. * * OpenALPR is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License * version 3 as published by the Free Software Foundation * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef OPENALPR_STATE_DETECTOR_H #define OPENALPR_STATE_DETECTOR_H #include <string> #include <vector> namespace alpr { struct StateCandidate { std::string state_code; float confidence; }; class StateDetectorImpl; class StateDetector { public: StateDetector(const std::string country, const std::string configFile, const std::string runtimeDir); virtual ~StateDetector(); bool isLoaded(); // Maximum number of candidates to return void setTopN(int topN); // Given an image of a license plate, provide the likely state candidates std::vector<StateCandidate> detect(std::vector<char> imageBytes); std::vector<StateCandidate> detect(unsigned char* pixelData, int bytesPerPixel, int imgWidth, int imgHeight); StateDetectorImpl* impl; }; } #endif //OPENALPR_STATE_DETECTOR_H
1,628
28.089286
115
h
openalpr
openalpr-master/src/statedetection/state_detector_impl.h
/* * Copyright (c) 2015 OpenALPR Technology, Inc. * Open source Automated License Plate Recognition [http://www.openalpr.com] * * This file is part of OpenALPR. * * OpenALPR is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License * version 3 as published by the Free Software Foundation * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef SRC_STATE_DETECTOR_IMPL_H #define SRC_STATE_DETECTOR_IMPL_H #include "state_detector.h" #include "featurematcher.h" #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> namespace alpr { class StateDetectorImpl { public: StateDetectorImpl(const std::string country, const std::string runtimeDir); virtual ~StateDetectorImpl(); bool isLoaded(); // Maximum number of candidates to return void setTopN(int topN); std::vector<StateCandidate> detect(std::vector<char> imageBytes); std::vector<StateCandidate> detect(unsigned char* pixelData, int bytesPerPixel, int imgWidth, int imgHeight); std::vector<StateCandidate> detect(cv::Mat image); FeatureMatcher featureMatcher; }; } #endif //SRC_STATE_DETECTOR_IMPL_H
1,573
30.48
115
h
openalpr
openalpr-master/src/tclap/Arg.h
// -*- Mode: c++; c-basic-offset: 4; tab-width: 4; -*- /****************************************************************************** * * file: Arg.h * * Copyright (c) 2003, Michael E. Smoot . * Copyright (c) 2004, Michael E. Smoot, Daniel Aarno . * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_ARGUMENT_H #define TCLAP_ARGUMENT_H #ifdef HAVE_CONFIG_H #include <config.h> #else #define HAVE_SSTREAM #endif #include <string> #include <vector> #include <list> #if defined(HAVE_SSTREAM) #include <sstream> typedef std::istringstream istringstream; #elif defined(HAVE_STRSTREAM) #include <strstream> typedef std::istrstream istringstream; #else #error "Need a stringstream (sstream or strstream) to compile!" #endif #include "ArgException.h" #include "Visitor.h" #include "CmdLineInterface.h" #include "ArgTraits.h" #include "StandardTraits.h" namespace TCLAP { /** * A virtual base class that defines the essential data for all arguments. * This class, or one of its existing children, must be subclassed to do * anything. */ class Arg { private: /** * Prevent accidental copying. */ Arg(const Arg& rhs); /** * Prevent accidental copying. */ Arg& operator=(const Arg& rhs); /** * Indicates whether the rest of the arguments should be ignored. */ static bool& ignoreRestRef() { static bool ign = false; return ign; } /** * The delimiter that separates an argument flag/name from the * value. */ static char& delimiterRef() { static char delim = ' '; return delim; } protected: /** * The single char flag used to identify the argument. * This value (preceded by a dash {-}), can be used to identify * an argument on the command line. The _flag can be blank, * in fact this is how unlabeled args work. Unlabeled args must * override appropriate functions to get correct handling. Note * that the _flag does NOT include the dash as part of the flag. */ std::string _flag; /** * A single work namd indentifying the argument. * This value (preceded by two dashed {--}) can also be used * to identify an argument on the command line. Note that the * _name does NOT include the two dashes as part of the _name. The * _name cannot be blank. */ std::string _name; /** * Description of the argument. */ std::string _description; /** * Indicating whether the argument is required. */ bool _required; /** * Label to be used in usage description. Normally set to * "required", but can be changed when necessary. */ std::string _requireLabel; /** * Indicates whether a value is required for the argument. * Note that the value may be required but the argument/value * combination may not be, as specified by _required. */ bool _valueRequired; /** * Indicates whether the argument has been set. * Indicates that a value on the command line has matched the * name/flag of this argument and the values have been set accordingly. */ bool _alreadySet; /** * A pointer to a vistitor object. * The visitor allows special handling to occur as soon as the * argument is matched. This defaults to NULL and should not * be used unless absolutely necessary. */ Visitor* _visitor; /** * Whether this argument can be ignored, if desired. */ bool _ignoreable; /** * Indicates that the arg was set as part of an XOR and not on the * command line. */ bool _xorSet; bool _acceptsMultipleValues; /** * Performs the special handling described by the Vistitor. */ void _checkWithVisitor() const; /** * Primary constructor. YOU (yes you) should NEVER construct an Arg * directly, this is a base class that is extended by various children * that are meant to be used. Use SwitchArg, ValueArg, MultiArg, * UnlabeledValueArg, or UnlabeledMultiArg instead. * * \param flag - The flag identifying the argument. * \param name - The name identifying the argument. * \param desc - The description of the argument, used in the usage. * \param req - Whether the argument is required. * \param valreq - Whether the a value is required for the argument. * \param v - The visitor checked by the argument. Defaults to NULL. */ Arg( const std::string& flag, const std::string& name, const std::string& desc, bool req, bool valreq, Visitor* v = NULL ); public: /** * Destructor. */ virtual ~Arg(); /** * Adds this to the specified list of Args. * \param argList - The list to add this to. */ virtual void addToList( std::list<Arg*>& argList ) const; /** * Begin ignoring arguments since the "--" argument was specified. */ static void beginIgnoring() { ignoreRestRef() = true; } /** * Whether to ignore the rest. */ static bool ignoreRest() { return ignoreRestRef(); } /** * The delimiter that separates an argument flag/name from the * value. */ static char delimiter() { return delimiterRef(); } /** * The char used as a place holder when SwitchArgs are combined. * Currently set to the bell char (ASCII 7). */ static char blankChar() { return (char)7; } /** * The char that indicates the beginning of a flag. Defaults to '-', but * clients can define TCLAP_FLAGSTARTCHAR to override. */ #ifndef TCLAP_FLAGSTARTCHAR #define TCLAP_FLAGSTARTCHAR '-' #endif static char flagStartChar() { return TCLAP_FLAGSTARTCHAR; } /** * The sting that indicates the beginning of a flag. Defaults to "-", but * clients can define TCLAP_FLAGSTARTSTRING to override. Should be the same * as TCLAP_FLAGSTARTCHAR. */ #ifndef TCLAP_FLAGSTARTSTRING #define TCLAP_FLAGSTARTSTRING "-" #endif static const std::string flagStartString() { return TCLAP_FLAGSTARTSTRING; } /** * The sting that indicates the beginning of a name. Defaults to "--", but * clients can define TCLAP_NAMESTARTSTRING to override. */ #ifndef TCLAP_NAMESTARTSTRING #define TCLAP_NAMESTARTSTRING "--" #endif static const std::string nameStartString() { return TCLAP_NAMESTARTSTRING; } /** * The name used to identify the ignore rest argument. */ static const std::string ignoreNameString() { return "ignore_rest"; } /** * Sets the delimiter for all arguments. * \param c - The character that delimits flags/names from values. */ static void setDelimiter( char c ) { delimiterRef() = c; } /** * Pure virtual method meant to handle the parsing and value assignment * of the string on the command line. * \param i - Pointer the the current argument in the list. * \param args - Mutable list of strings. What is * passed in from main. */ virtual bool processArg(int *i, std::vector<std::string>& args) = 0; /** * Operator ==. * Equality operator. Must be virtual to handle unlabeled args. * \param a - The Arg to be compared to this. */ virtual bool operator==(const Arg& a) const; /** * Returns the argument flag. */ const std::string& getFlag() const; /** * Returns the argument name. */ const std::string& getName() const; /** * Returns the argument description. */ std::string getDescription() const; /** * Indicates whether the argument is required. */ virtual bool isRequired() const; /** * Sets _required to true. This is used by the XorHandler. * You really have no reason to ever use it. */ void forceRequired(); /** * Sets the _alreadySet value to true. This is used by the XorHandler. * You really have no reason to ever use it. */ void xorSet(); /** * Indicates whether a value must be specified for argument. */ bool isValueRequired() const; /** * Indicates whether the argument has already been set. Only true * if the arg has been matched on the command line. */ bool isSet() const; /** * Indicates whether the argument can be ignored, if desired. */ bool isIgnoreable() const; /** * A method that tests whether a string matches this argument. * This is generally called by the processArg() method. This * method could be re-implemented by a child to change how * arguments are specified on the command line. * \param s - The string to be compared to the flag/name to determine * whether the arg matches. */ virtual bool argMatches( const std::string& s ) const; /** * Returns a simple string representation of the argument. * Primarily for debugging. */ virtual std::string toString() const; /** * Returns a short ID for the usage. * \param valueId - The value used in the id. */ virtual std::string shortID( const std::string& valueId = "val" ) const; /** * Returns a long ID for the usage. * \param valueId - The value used in the id. */ virtual std::string longID( const std::string& valueId = "val" ) const; /** * Trims a value off of the flag. * \param flag - The string from which the flag and value will be * trimmed. Contains the flag once the value has been trimmed. * \param value - Where the value trimmed from the string will * be stored. */ virtual void trimFlag( std::string& flag, std::string& value ) const; /** * Checks whether a given string has blank chars, indicating that * it is a combined SwitchArg. If so, return true, otherwise return * false. * \param s - string to be checked. */ bool _hasBlanks( const std::string& s ) const; /** * Sets the requireLabel. Used by XorHandler. You shouldn't ever * use this. * \param s - Set the requireLabel to this value. */ void setRequireLabel( const std::string& s ); /** * Used for MultiArgs and XorHandler to determine whether args * can still be set. */ virtual bool allowMore(); /** * Use by output classes to determine whether an Arg accepts * multiple values. */ virtual bool acceptsMultipleValues(); /** * Clears the Arg object and allows it to be reused by new * command lines. */ virtual void reset(); }; /** * Typedef of an Arg list iterator. */ typedef std::list<Arg*>::iterator ArgListIterator; /** * Typedef of an Arg vector iterator. */ typedef std::vector<Arg*>::iterator ArgVectorIterator; /** * Typedef of a Visitor list iterator. */ typedef std::list<Visitor*>::iterator VisitorListIterator; /* * Extract a value of type T from it's string representation contained * in strVal. The ValueLike parameter used to select the correct * specialization of ExtractValue depending on the value traits of T. * ValueLike traits use operator>> to assign the value from strVal. */ template<typename T> void ExtractValue(T &destVal, const std::string& strVal, ValueLike vl) { static_cast<void>(vl); // Avoid warning about unused vl std::istringstream is(strVal); int valuesRead = 0; while ( is.good() ) { if ( is.peek() != EOF ) #ifdef TCLAP_SETBASE_ZERO is >> std::setbase(0) >> destVal; #else is >> destVal; #endif else break; valuesRead++; } if ( is.fail() ) throw( ArgParseException("Couldn't read argument value " "from string '" + strVal + "'")); if ( valuesRead > 1 ) throw( ArgParseException("More than one valid value parsed from " "string '" + strVal + "'")); } /* * Extract a value of type T from it's string representation contained * in strVal. The ValueLike parameter used to select the correct * specialization of ExtractValue depending on the value traits of T. * StringLike uses assignment (operator=) to assign from strVal. */ template<typename T> void ExtractValue(T &destVal, const std::string& strVal, StringLike sl) { static_cast<void>(sl); // Avoid warning about unused sl SetString(destVal, strVal); } ////////////////////////////////////////////////////////////////////// //BEGIN Arg.cpp ////////////////////////////////////////////////////////////////////// inline Arg::Arg(const std::string& flag, const std::string& name, const std::string& desc, bool req, bool valreq, Visitor* v) : _flag(flag), _name(name), _description(desc), _required(req), _requireLabel("required"), _valueRequired(valreq), _alreadySet(false), _visitor( v ), _ignoreable(true), _xorSet(false), _acceptsMultipleValues(false) { if ( _flag.length() > 1 ) throw(SpecificationException( "Argument flag can only be one character long", toString() ) ); if ( _name != ignoreNameString() && ( _flag == Arg::flagStartString() || _flag == Arg::nameStartString() || _flag == " " ) ) throw(SpecificationException("Argument flag cannot be either '" + Arg::flagStartString() + "' or '" + Arg::nameStartString() + "' or a space.", toString() ) ); if ( ( _name.substr( 0, Arg::flagStartString().length() ) == Arg::flagStartString() ) || ( _name.substr( 0, Arg::nameStartString().length() ) == Arg::nameStartString() ) || ( _name.find( " ", 0 ) != std::string::npos ) ) throw(SpecificationException("Argument name begin with either '" + Arg::flagStartString() + "' or '" + Arg::nameStartString() + "' or space.", toString() ) ); } inline Arg::~Arg() { } inline std::string Arg::shortID( const std::string& valueId ) const { std::string id = ""; if ( _flag != "" ) id = Arg::flagStartString() + _flag; else id = Arg::nameStartString() + _name; if ( _valueRequired ) id += std::string( 1, Arg::delimiter() ) + "<" + valueId + ">"; if ( !_required ) id = "[" + id + "]"; return id; } inline std::string Arg::longID( const std::string& valueId ) const { std::string id = ""; if ( _flag != "" ) { id += Arg::flagStartString() + _flag; if ( _valueRequired ) id += std::string( 1, Arg::delimiter() ) + "<" + valueId + ">"; id += ", "; } id += Arg::nameStartString() + _name; if ( _valueRequired ) id += std::string( 1, Arg::delimiter() ) + "<" + valueId + ">"; return id; } inline bool Arg::operator==(const Arg& a) const { if ( ( _flag != "" && _flag == a._flag ) || _name == a._name) return true; else return false; } inline std::string Arg::getDescription() const { std::string desc = ""; if ( _required ) desc = "(" + _requireLabel + ") "; // if ( _valueRequired ) // desc += "(value required) "; desc += _description; return desc; } inline const std::string& Arg::getFlag() const { return _flag; } inline const std::string& Arg::getName() const { return _name; } inline bool Arg::isRequired() const { return _required; } inline bool Arg::isValueRequired() const { return _valueRequired; } inline bool Arg::isSet() const { if ( _alreadySet && !_xorSet ) return true; else return false; } inline bool Arg::isIgnoreable() const { return _ignoreable; } inline void Arg::setRequireLabel( const std::string& s) { _requireLabel = s; } inline bool Arg::argMatches( const std::string& argFlag ) const { if ( ( argFlag == Arg::flagStartString() + _flag && _flag != "" ) || argFlag == Arg::nameStartString() + _name ) return true; else return false; } inline std::string Arg::toString() const { std::string s = ""; if ( _flag != "" ) s += Arg::flagStartString() + _flag + " "; s += "(" + Arg::nameStartString() + _name + ")"; return s; } inline void Arg::_checkWithVisitor() const { if ( _visitor != NULL ) _visitor->visit(); } /** * Implementation of trimFlag. */ inline void Arg::trimFlag(std::string& flag, std::string& value) const { int stop = 0; for ( int i = 0; static_cast<unsigned int>(i) < flag.length(); i++ ) if ( flag[i] == Arg::delimiter() ) { stop = i; break; } if ( stop > 1 ) { value = flag.substr(stop+1); flag = flag.substr(0,stop); } } /** * Implementation of _hasBlanks. */ inline bool Arg::_hasBlanks( const std::string& s ) const { for ( int i = 1; static_cast<unsigned int>(i) < s.length(); i++ ) if ( s[i] == Arg::blankChar() ) return true; return false; } inline void Arg::forceRequired() { _required = true; } inline void Arg::xorSet() { _alreadySet = true; _xorSet = true; } /** * Overridden by Args that need to added to the end of the list. */ inline void Arg::addToList( std::list<Arg*>& argList ) const { argList.push_front( const_cast<Arg*>(this) ); } inline bool Arg::allowMore() { return false; } inline bool Arg::acceptsMultipleValues() { return _acceptsMultipleValues; } inline void Arg::reset() { _xorSet = false; _alreadySet = false; } ////////////////////////////////////////////////////////////////////// //END Arg.cpp ////////////////////////////////////////////////////////////////////// } //namespace TCLAP #endif
18,430
24.84993
90
h
openalpr
openalpr-master/src/tclap/ArgException.h
// -*- Mode: c++; c-basic-offset: 4; tab-width: 4; -*- /****************************************************************************** * * file: ArgException.h * * Copyright (c) 2003, Michael E. Smoot . * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_ARG_EXCEPTION_H #define TCLAP_ARG_EXCEPTION_H #include <string> #include <exception> namespace TCLAP { /** * A simple class that defines and argument exception. Should be caught * whenever a CmdLine is created and parsed. */ class ArgException : public std::exception { public: /** * Constructor. * \param text - The text of the exception. * \param id - The text identifying the argument source. * \param td - Text describing the type of ArgException it is. * of the exception. */ ArgException( const std::string& text = "undefined exception", const std::string& id = "undefined", const std::string& td = "Generic ArgException") : std::exception(), _errorText(text), _argId( id ), _typeDescription(td) { } /** * Destructor. */ virtual ~ArgException() throw() { } /** * Returns the error text. */ std::string error() const { return ( _errorText ); } /** * Returns the argument id. */ std::string argId() const { if ( _argId == "undefined" ) return " "; else return ( "Argument: " + _argId ); } /** * Returns the arg id and error text. */ const char* what() const throw() { static std::string ex; ex = _argId + " -- " + _errorText; return ex.c_str(); } /** * Returns the type of the exception. Used to explain and distinguish * between different child exceptions. */ std::string typeDescription() const { return _typeDescription; } private: /** * The text of the exception message. */ std::string _errorText; /** * The argument related to this exception. */ std::string _argId; /** * Describes the type of the exception. Used to distinguish * between different child exceptions. */ std::string _typeDescription; }; /** * Thrown from within the child Arg classes when it fails to properly * parse the argument it has been passed. */ class ArgParseException : public ArgException { public: /** * Constructor. * \param text - The text of the exception. * \param id - The text identifying the argument source * of the exception. */ ArgParseException( const std::string& text = "undefined exception", const std::string& id = "undefined" ) : ArgException( text, id, std::string( "Exception found while parsing " ) + std::string( "the value the Arg has been passed." )) { } }; /** * Thrown from CmdLine when the arguments on the command line are not * properly specified, e.g. too many arguments, required argument missing, etc. */ class CmdLineParseException : public ArgException { public: /** * Constructor. * \param text - The text of the exception. * \param id - The text identifying the argument source * of the exception. */ CmdLineParseException( const std::string& text = "undefined exception", const std::string& id = "undefined" ) : ArgException( text, id, std::string( "Exception found when the values ") + std::string( "on the command line do not meet ") + std::string( "the requirements of the defined ") + std::string( "Args." )) { } }; /** * Thrown from Arg and CmdLine when an Arg is improperly specified, e.g. * same flag as another Arg, same name, etc. */ class SpecificationException : public ArgException { public: /** * Constructor. * \param text - The text of the exception. * \param id - The text identifying the argument source * of the exception. */ SpecificationException( const std::string& text = "undefined exception", const std::string& id = "undefined" ) : ArgException( text, id, std::string("Exception found when an Arg object ")+ std::string("is improperly defined by the ") + std::string("developer." )) { } }; class ExitException { public: ExitException(int estat) : _estat(estat) {} int getExitStatus() const { return _estat; } private: int _estat; }; } // namespace TCLAP #endif
5,434
25.129808
79
h
openalpr
openalpr-master/src/tclap/ArgTraits.h
// -*- Mode: c++; c-basic-offset: 4; tab-width: 4; -*- /****************************************************************************** * * file: ArgTraits.h * * Copyright (c) 2007, Daniel Aarno, Michael E. Smoot . * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ // This is an internal tclap file, you should probably not have to // include this directly #ifndef TCLAP_ARGTRAITS_H #define TCLAP_ARGTRAITS_H namespace TCLAP { // We use two empty structs to get compile type specialization // function to work /** * A value like argument value type is a value that can be set using * operator>>. This is the default value type. */ struct ValueLike { typedef ValueLike ValueCategory; virtual ~ValueLike() {} }; /** * A string like argument value type is a value that can be set using * operator=(string). Useful if the value type contains spaces which * will be broken up into individual tokens by operator>>. */ struct StringLike { virtual ~StringLike() {} }; /** * A class can inherit from this object to make it have string like * traits. This is a compile time thing and does not add any overhead * to the inherenting class. */ struct StringLikeTrait { typedef StringLike ValueCategory; virtual ~StringLikeTrait() {} }; /** * A class can inherit from this object to make it have value like * traits. This is a compile time thing and does not add any overhead * to the inherenting class. */ struct ValueLikeTrait { typedef ValueLike ValueCategory; virtual ~ValueLikeTrait() {} }; /** * Arg traits are used to get compile type specialization when parsing * argument values. Using an ArgTraits you can specify the way that * values gets assigned to any particular type during parsing. The two * supported types are StringLike and ValueLike. */ template<typename T> struct ArgTraits { typedef typename T::ValueCategory ValueCategory; virtual ~ArgTraits() {} //typedef ValueLike ValueCategory; }; #endif } // namespace
2,621
26.893617
79
h
openalpr
openalpr-master/src/tclap/CmdLine.h
// -*- Mode: c++; c-basic-offset: 4; tab-width: 4; -*- /****************************************************************************** * * file: CmdLine.h * * Copyright (c) 2003, Michael E. Smoot . * Copyright (c) 2004, Michael E. Smoot, Daniel Aarno. * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_CMDLINE_H #define TCLAP_CMDLINE_H #include "SwitchArg.h" #include "MultiSwitchArg.h" #include "UnlabeledValueArg.h" #include "UnlabeledMultiArg.h" #include "XorHandler.h" #include "HelpVisitor.h" #include "VersionVisitor.h" #include "IgnoreRestVisitor.h" #include "CmdLineOutput.h" #include "StdOutput.h" #include "Constraint.h" #include "ValuesConstraint.h" #include <string> #include <vector> #include <list> #include <algorithm> #include <stdlib.h> // Needed for exit(), which isn't defined in some envs. namespace TCLAP { template<typename T> void DelPtr(T ptr) { delete ptr; } template<typename C> void ClearContainer(C &c) { typedef typename C::value_type value_type; std::for_each(c.begin(), c.end(), DelPtr<value_type>); c.clear(); } /** * The base class that manages the command line definition and passes * along the parsing to the appropriate Arg classes. */ class CmdLine : public CmdLineInterface { protected: /** * The list of arguments that will be tested against the * command line. */ std::list<Arg*> _argList; /** * The name of the program. Set to argv[0]. */ std::string _progName; /** * A message used to describe the program. Used in the usage output. */ std::string _message; /** * The version to be displayed with the --version switch. */ std::string _version; /** * The number of arguments that are required to be present on * the command line. This is set dynamically, based on the * Args added to the CmdLine object. */ int _numRequired; /** * The character that is used to separate the argument flag/name * from the value. Defaults to ' ' (space). */ char _delimiter; /** * The handler that manages xoring lists of args. */ XorHandler _xorHandler; /** * A list of Args to be explicitly deleted when the destructor * is called. At the moment, this only includes the three default * Args. */ std::list<Arg*> _argDeleteOnExitList; /** * A list of Visitors to be explicitly deleted when the destructor * is called. At the moment, these are the Visitors created for the * default Args. */ std::list<Visitor*> _visitorDeleteOnExitList; /** * Object that handles all output for the CmdLine. */ CmdLineOutput* _output; /** * Should CmdLine handle parsing exceptions internally? */ bool _handleExceptions; /** * Throws an exception listing the missing args. */ void missingArgsException(); /** * Checks whether a name/flag string matches entirely matches * the Arg::blankChar. Used when multiple switches are combined * into a single argument. * \param s - The message to be used in the usage. */ bool _emptyCombined(const std::string& s); /** * Perform a delete ptr; operation on ptr when this object is deleted. */ void deleteOnExit(Arg* ptr); /** * Perform a delete ptr; operation on ptr when this object is deleted. */ void deleteOnExit(Visitor* ptr); private: /** * Prevent accidental copying. */ CmdLine(const CmdLine& rhs); CmdLine& operator=(const CmdLine& rhs); /** * Encapsulates the code common to the constructors * (which is all of it). */ void _constructor(); /** * Is set to true when a user sets the output object. We use this so * that we don't delete objects that are created outside of this lib. */ bool _userSetOutput; /** * Whether or not to automatically create help and version switches. */ bool _helpAndVersion; public: /** * Command line constructor. Defines how the arguments will be * parsed. * \param message - The message to be used in the usage * output. * \param delimiter - The character that is used to separate * the argument flag/name from the value. Defaults to ' ' (space). * \param version - The version number to be used in the * --version switch. * \param helpAndVersion - Whether or not to create the Help and * Version switches. Defaults to true. */ CmdLine(const std::string& message, const char delimiter = ' ', const std::string& version = "none", bool helpAndVersion = true); /** * Deletes any resources allocated by a CmdLine object. */ virtual ~CmdLine(); /** * Adds an argument to the list of arguments to be parsed. * \param a - Argument to be added. */ void add( Arg& a ); /** * An alternative add. Functionally identical. * \param a - Argument to be added. */ void add( Arg* a ); /** * Add two Args that will be xor'd. If this method is used, add does * not need to be called. * \param a - Argument to be added and xor'd. * \param b - Argument to be added and xor'd. */ void xorAdd( Arg& a, Arg& b ); /** * Add a list of Args that will be xor'd. If this method is used, * add does not need to be called. * \param xors - List of Args to be added and xor'd. */ void xorAdd( std::vector<Arg*>& xors ); /** * Parses the command line. * \param argc - Number of arguments. * \param argv - Array of arguments. */ bool parse(int argc, const char * const * argv); /** * Parses the command line. * \param args - A vector of strings representing the args. * args[0] is still the program name. */ bool parse(std::vector<std::string>& args); /** * */ CmdLineOutput* getOutput(); /** * */ void setOutput(CmdLineOutput* co); /** * */ std::string& getVersion(); /** * */ std::string& getProgramName(); /** * */ std::list<Arg*>& getArgList(); /** * */ XorHandler& getXorHandler(); /** * */ char getDelimiter(); /** * */ std::string& getMessage(); /** * */ bool hasHelpAndVersion(); /** * Disables or enables CmdLine's internal parsing exception handling. * * @param state Should CmdLine handle parsing exceptions internally? */ void setExceptionHandling(const bool state); /** * Returns the current state of the internal exception handling. * * @retval true Parsing exceptions are handled internally. * @retval false Parsing exceptions are propagated to the caller. */ bool getExceptionHandling() const; /** * Allows the CmdLine object to be reused. */ void reset(); }; /////////////////////////////////////////////////////////////////////////////// //Begin CmdLine.cpp /////////////////////////////////////////////////////////////////////////////// inline CmdLine::CmdLine(const std::string& m, char delim, const std::string& v, bool help ) : _argList(std::list<Arg*>()), _progName("not_set_yet"), _message(m), _version(v), _numRequired(0), _delimiter(delim), _xorHandler(XorHandler()), _argDeleteOnExitList(std::list<Arg*>()), _visitorDeleteOnExitList(std::list<Visitor*>()), _output(0), _handleExceptions(true), _userSetOutput(false), _helpAndVersion(help) { _constructor(); } inline CmdLine::~CmdLine() { ClearContainer(_argDeleteOnExitList); ClearContainer(_visitorDeleteOnExitList); if ( !_userSetOutput ) { delete _output; _output = 0; } } inline void CmdLine::_constructor() { _output = new StdOutput; Arg::setDelimiter( _delimiter ); Visitor* v; if ( _helpAndVersion ) { v = new HelpVisitor( this, &_output ); SwitchArg* help = new SwitchArg("h","help", "Displays usage information and exits.", false, v); add( help ); deleteOnExit(help); deleteOnExit(v); v = new VersionVisitor( this, &_output ); SwitchArg* vers = new SwitchArg("","version", "Displays version information and exits.", false, v); add( vers ); deleteOnExit(vers); deleteOnExit(v); } v = new IgnoreRestVisitor(); SwitchArg* ignore = new SwitchArg(Arg::flagStartString(), Arg::ignoreNameString(), "Ignores the rest of the labeled arguments following this flag.", false, v); add( ignore ); deleteOnExit(ignore); deleteOnExit(v); } inline void CmdLine::xorAdd( std::vector<Arg*>& ors ) { _xorHandler.add( ors ); for (ArgVectorIterator it = ors.begin(); it != ors.end(); it++) { (*it)->forceRequired(); (*it)->setRequireLabel( "OR required" ); add( *it ); } } inline void CmdLine::xorAdd( Arg& a, Arg& b ) { std::vector<Arg*> ors; ors.push_back( &a ); ors.push_back( &b ); xorAdd( ors ); } inline void CmdLine::add( Arg& a ) { add( &a ); } inline void CmdLine::add( Arg* a ) { for( ArgListIterator it = _argList.begin(); it != _argList.end(); it++ ) if ( *a == *(*it) ) throw( SpecificationException( "Argument with same flag/name already exists!", a->longID() ) ); a->addToList( _argList ); if ( a->isRequired() ) _numRequired++; } inline bool CmdLine::parse(int argc, const char * const * argv) { // this step is necessary so that we have easy access to // mutable strings. std::vector<std::string> args; for (int i = 0; i < argc; i++) args.push_back(argv[i]); return parse(args); } inline bool CmdLine::parse(std::vector<std::string>& args) { bool shouldExit = false; int estat = 0; try { _progName = args.front(); args.erase(args.begin()); int requiredCount = 0; for (int i = 0; static_cast<unsigned int>(i) < args.size(); i++) { bool matched = false; for (ArgListIterator it = _argList.begin(); it != _argList.end(); it++) { if ( (*it)->processArg( &i, args ) ) { requiredCount += _xorHandler.check( *it ); matched = true; break; } } // checks to see if the argument is an empty combined // switch and if so, then we've actually matched it if ( !matched && _emptyCombined( args[i] ) ) matched = true; if ( !matched && !Arg::ignoreRest() ) throw(CmdLineParseException("Couldn't find match " "for argument", args[i])); } if ( requiredCount < _numRequired ) missingArgsException(); if ( requiredCount > _numRequired ) throw(CmdLineParseException("Too many arguments!")); } catch ( ArgException& e ) { // If we're not handling the exceptions, rethrow. if ( !_handleExceptions) { throw; } try { _output->failure(*this,e); } catch ( ExitException &ee ) { estat = ee.getExitStatus(); shouldExit = true; } } catch (ExitException &ee) { // If we're not handling the exceptions, rethrow. if ( !_handleExceptions) { throw; } estat = ee.getExitStatus(); shouldExit = true; } if (shouldExit) { //exit(estat); return false; } return true; } inline bool CmdLine::_emptyCombined(const std::string& s) { if ( s.length() > 0 && s[0] != Arg::flagStartChar() ) return false; for ( int i = 1; static_cast<unsigned int>(i) < s.length(); i++ ) if ( s[i] != Arg::blankChar() ) return false; return true; } inline void CmdLine::missingArgsException() { int count = 0; std::string missingArgList; for (ArgListIterator it = _argList.begin(); it != _argList.end(); it++) { if ( (*it)->isRequired() && !(*it)->isSet() ) { missingArgList += (*it)->getName(); missingArgList += ", "; count++; } } missingArgList = missingArgList.substr(0,missingArgList.length()-2); std::string msg; if ( count > 1 ) msg = "Required arguments missing: "; else msg = "Required argument missing: "; msg += missingArgList; throw(CmdLineParseException(msg)); } inline void CmdLine::deleteOnExit(Arg* ptr) { _argDeleteOnExitList.push_back(ptr); } inline void CmdLine::deleteOnExit(Visitor* ptr) { _visitorDeleteOnExitList.push_back(ptr); } inline CmdLineOutput* CmdLine::getOutput() { return _output; } inline void CmdLine::setOutput(CmdLineOutput* co) { if ( !_userSetOutput ) delete _output; _userSetOutput = true; _output = co; } inline std::string& CmdLine::getVersion() { return _version; } inline std::string& CmdLine::getProgramName() { return _progName; } inline std::list<Arg*>& CmdLine::getArgList() { return _argList; } inline XorHandler& CmdLine::getXorHandler() { return _xorHandler; } inline char CmdLine::getDelimiter() { return _delimiter; } inline std::string& CmdLine::getMessage() { return _message; } inline bool CmdLine::hasHelpAndVersion() { return _helpAndVersion; } inline void CmdLine::setExceptionHandling(const bool state) { _handleExceptions = state; } inline bool CmdLine::getExceptionHandling() const { return _handleExceptions; } inline void CmdLine::reset() { for( ArgListIterator it = _argList.begin(); it != _argList.end(); it++ ) (*it)->reset(); _progName.clear(); } /////////////////////////////////////////////////////////////////////////////// //End CmdLine.cpp /////////////////////////////////////////////////////////////////////////////// } //namespace TCLAP #endif
14,732
22.686495
102
h
openalpr
openalpr-master/src/tclap/CmdLineInterface.h
/****************************************************************************** * * file: CmdLineInterface.h * * Copyright (c) 2003, Michael E. Smoot . * Copyright (c) 2004, Michael E. Smoot, Daniel Aarno. * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_COMMANDLINE_INTERFACE_H #define TCLAP_COMMANDLINE_INTERFACE_H #include <string> #include <vector> #include <list> #include <algorithm> namespace TCLAP { class Arg; class CmdLineOutput; class XorHandler; /** * The base class that manages the command line definition and passes * along the parsing to the appropriate Arg classes. */ class CmdLineInterface { public: /** * Destructor */ virtual ~CmdLineInterface() {} /** * Adds an argument to the list of arguments to be parsed. * \param a - Argument to be added. */ virtual void add( Arg& a )=0; /** * An alternative add. Functionally identical. * \param a - Argument to be added. */ virtual void add( Arg* a )=0; /** * Add two Args that will be xor'd. * If this method is used, add does * not need to be called. * \param a - Argument to be added and xor'd. * \param b - Argument to be added and xor'd. */ virtual void xorAdd( Arg& a, Arg& b )=0; /** * Add a list of Args that will be xor'd. If this method is used, * add does not need to be called. * \param xors - List of Args to be added and xor'd. */ virtual void xorAdd( std::vector<Arg*>& xors )=0; /** * Parses the command line. * \param argc - Number of arguments. * \param argv - Array of arguments. */ virtual bool parse(int argc, const char * const * argv)=0; /** * Parses the command line. * \param args - A vector of strings representing the args. * args[0] is still the program name. */ bool parse(std::vector<std::string>& args); /** * Returns the CmdLineOutput object. */ virtual CmdLineOutput* getOutput()=0; /** * \param co - CmdLineOutput object that we want to use instead. */ virtual void setOutput(CmdLineOutput* co)=0; /** * Returns the version string. */ virtual std::string& getVersion()=0; /** * Returns the program name string. */ virtual std::string& getProgramName()=0; /** * Returns the argList. */ virtual std::list<Arg*>& getArgList()=0; /** * Returns the XorHandler. */ virtual XorHandler& getXorHandler()=0; /** * Returns the delimiter string. */ virtual char getDelimiter()=0; /** * Returns the message string. */ virtual std::string& getMessage()=0; /** * Indicates whether or not the help and version switches were created * automatically. */ virtual bool hasHelpAndVersion()=0; /** * Resets the instance as if it had just been constructed so that the * instance can be reused. */ virtual void reset()=0; }; } //namespace #endif
3,700
23.509934
79
h
openalpr
openalpr-master/src/tclap/CmdLineOutput.h
/****************************************************************************** * * file: CmdLineOutput.h * * Copyright (c) 2004, Michael E. Smoot * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_CMDLINEOUTPUT_H #define TCLAP_CMDLINEOUTPUT_H #include <string> #include <vector> #include <list> #include <algorithm> namespace TCLAP { class CmdLineInterface; class ArgException; /** * The interface that any output object must implement. */ class CmdLineOutput { public: /** * Virtual destructor. */ virtual ~CmdLineOutput() {} /** * Generates some sort of output for the USAGE. * \param c - The CmdLine object the output is generated for. */ virtual void usage(CmdLineInterface& c)=0; /** * Generates some sort of output for the version. * \param c - The CmdLine object the output is generated for. */ virtual void version(CmdLineInterface& c)=0; /** * Generates some sort of output for a failure. * \param c - The CmdLine object the output is generated for. * \param e - The ArgException that caused the failure. */ virtual void failure( CmdLineInterface& c, ArgException& e )=0; }; } //namespace TCLAP #endif
1,914
24.878378
79
h
openalpr
openalpr-master/src/tclap/Constraint.h
/****************************************************************************** * * file: Constraint.h * * Copyright (c) 2005, Michael E. Smoot * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_CONSTRAINT_H #define TCLAP_CONSTRAINT_H #include <string> #include <vector> #include <list> #include <algorithm> namespace TCLAP { /** * The interface that defines the interaction between the Arg and Constraint. */ template<class T> class Constraint { public: /** * Returns a description of the Constraint. */ virtual std::string description() const =0; /** * Returns the short ID for the Constraint. */ virtual std::string shortID() const =0; /** * The method used to verify that the value parsed from the command * line meets the constraint. * \param value - The value that will be checked. */ virtual bool check(const T& value) const =0; /** * Destructor. * Silences warnings about Constraint being a base class with virtual * functions but without a virtual destructor. */ virtual ~Constraint() { ; } }; } //namespace TCLAP #endif
1,816
24.591549
79
h
openalpr
openalpr-master/src/tclap/DocBookOutput.h
// -*- Mode: c++; c-basic-offset: 4; tab-width: 4; -*- /****************************************************************************** * * file: DocBookOutput.h * * Copyright (c) 2004, Michael E. Smoot * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_DOCBOOKOUTPUT_H #define TCLAP_DOCBOOKOUTPUT_H #include <string> #include <vector> #include <list> #include <iostream> #include <algorithm> #include <tclap/CmdLineInterface.h> #include <tclap/CmdLineOutput.h> #include <tclap/XorHandler.h> #include <tclap/Arg.h> namespace TCLAP { /** * A class that generates DocBook output for usage() method for the * given CmdLine and its Args. */ class DocBookOutput : public CmdLineOutput { public: /** * Prints the usage to stdout. Can be overridden to * produce alternative behavior. * \param c - The CmdLine object the output is generated for. */ virtual void usage(CmdLineInterface& c); /** * Prints the version to stdout. Can be overridden * to produce alternative behavior. * \param c - The CmdLine object the output is generated for. */ virtual void version(CmdLineInterface& c); /** * Prints (to stderr) an error message, short usage * Can be overridden to produce alternative behavior. * \param c - The CmdLine object the output is generated for. * \param e - The ArgException that caused the failure. */ virtual void failure(CmdLineInterface& c, ArgException& e ); protected: /** * Substitutes the char r for string x in string s. * \param s - The string to operate on. * \param r - The char to replace. * \param x - What to replace r with. */ void substituteSpecialChars( std::string& s, char r, std::string& x ); void removeChar( std::string& s, char r); void basename( std::string& s ); void printShortArg(Arg* it); void printLongArg(Arg* it); char theDelimiter; }; inline void DocBookOutput::version(CmdLineInterface& _cmd) { std::cout << _cmd.getVersion() << std::endl; } inline void DocBookOutput::usage(CmdLineInterface& _cmd ) { std::list<Arg*> argList = _cmd.getArgList(); std::string progName = _cmd.getProgramName(); std::string xversion = _cmd.getVersion(); theDelimiter = _cmd.getDelimiter(); XorHandler xorHandler = _cmd.getXorHandler(); std::vector< std::vector<Arg*> > xorList = xorHandler.getXorList(); basename(progName); std::cout << "<?xml version='1.0'?>" << std::endl; std::cout << "<!DOCTYPE refentry PUBLIC \"-//OASIS//DTD DocBook XML V4.2//EN\"" << std::endl; std::cout << "\t\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\">" << std::endl << std::endl; std::cout << "<refentry>" << std::endl; std::cout << "<refmeta>" << std::endl; std::cout << "<refentrytitle>" << progName << "</refentrytitle>" << std::endl; std::cout << "<manvolnum>1</manvolnum>" << std::endl; std::cout << "</refmeta>" << std::endl; std::cout << "<refnamediv>" << std::endl; std::cout << "<refname>" << progName << "</refname>" << std::endl; std::cout << "<refpurpose>" << _cmd.getMessage() << "</refpurpose>" << std::endl; std::cout << "</refnamediv>" << std::endl; std::cout << "<refsynopsisdiv>" << std::endl; std::cout << "<cmdsynopsis>" << std::endl; std::cout << "<command>" << progName << "</command>" << std::endl; // xor for ( int i = 0; (unsigned int)i < xorList.size(); i++ ) { std::cout << "<group choice='req'>" << std::endl; for ( ArgVectorIterator it = xorList[i].begin(); it != xorList[i].end(); it++ ) printShortArg((*it)); std::cout << "</group>" << std::endl; } // rest of args for (ArgListIterator it = argList.begin(); it != argList.end(); it++) if ( !xorHandler.contains( (*it) ) ) printShortArg((*it)); std::cout << "</cmdsynopsis>" << std::endl; std::cout << "</refsynopsisdiv>" << std::endl; std::cout << "<refsect1>" << std::endl; std::cout << "<title>Description</title>" << std::endl; std::cout << "<para>" << std::endl; std::cout << _cmd.getMessage() << std::endl; std::cout << "</para>" << std::endl; std::cout << "</refsect1>" << std::endl; std::cout << "<refsect1>" << std::endl; std::cout << "<title>Options</title>" << std::endl; std::cout << "<variablelist>" << std::endl; for (ArgListIterator it = argList.begin(); it != argList.end(); it++) printLongArg((*it)); std::cout << "</variablelist>" << std::endl; std::cout << "</refsect1>" << std::endl; std::cout << "<refsect1>" << std::endl; std::cout << "<title>Version</title>" << std::endl; std::cout << "<para>" << std::endl; std::cout << xversion << std::endl; std::cout << "</para>" << std::endl; std::cout << "</refsect1>" << std::endl; std::cout << "</refentry>" << std::endl; } inline void DocBookOutput::failure( CmdLineInterface& _cmd, ArgException& e ) { static_cast<void>(_cmd); // unused std::cout << e.what() << std::endl; throw ExitException(1); } inline void DocBookOutput::substituteSpecialChars( std::string& s, char r, std::string& x ) { size_t p; while ( (p = s.find_first_of(r)) != std::string::npos ) { s.erase(p,1); s.insert(p,x); } } inline void DocBookOutput::removeChar( std::string& s, char r) { size_t p; while ( (p = s.find_first_of(r)) != std::string::npos ) { s.erase(p,1); } } inline void DocBookOutput::basename( std::string& s ) { size_t p = s.find_last_of('/'); if ( p != std::string::npos ) { s.erase(0, p + 1); } } inline void DocBookOutput::printShortArg(Arg* a) { std::string lt = "&lt;"; std::string gt = "&gt;"; std::string id = a->shortID(); substituteSpecialChars(id,'<',lt); substituteSpecialChars(id,'>',gt); removeChar(id,'['); removeChar(id,']'); std::string choice = "opt"; if ( a->isRequired() ) choice = "plain"; std::cout << "<arg choice='" << choice << '\''; if ( a->acceptsMultipleValues() ) std::cout << " rep='repeat'"; std::cout << '>'; if ( !a->getFlag().empty() ) std::cout << a->flagStartChar() << a->getFlag(); else std::cout << a->nameStartString() << a->getName(); if ( a->isValueRequired() ) { std::string arg = a->shortID(); removeChar(arg,'['); removeChar(arg,']'); removeChar(arg,'<'); removeChar(arg,'>'); arg.erase(0, arg.find_last_of(theDelimiter) + 1); std::cout << theDelimiter; std::cout << "<replaceable>" << arg << "</replaceable>"; } std::cout << "</arg>" << std::endl; } inline void DocBookOutput::printLongArg(Arg* a) { std::string lt = "&lt;"; std::string gt = "&gt;"; std::string desc = a->getDescription(); substituteSpecialChars(desc,'<',lt); substituteSpecialChars(desc,'>',gt); std::cout << "<varlistentry>" << std::endl; if ( !a->getFlag().empty() ) { std::cout << "<term>" << std::endl; std::cout << "<option>"; std::cout << a->flagStartChar() << a->getFlag(); std::cout << "</option>" << std::endl; std::cout << "</term>" << std::endl; } std::cout << "<term>" << std::endl; std::cout << "<option>"; std::cout << a->nameStartString() << a->getName(); if ( a->isValueRequired() ) { std::string arg = a->shortID(); removeChar(arg,'['); removeChar(arg,']'); removeChar(arg,'<'); removeChar(arg,'>'); arg.erase(0, arg.find_last_of(theDelimiter) + 1); std::cout << theDelimiter; std::cout << "<replaceable>" << arg << "</replaceable>"; } std::cout << "</option>" << std::endl; std::cout << "</term>" << std::endl; std::cout << "<listitem>" << std::endl; std::cout << "<para>" << std::endl; std::cout << desc << std::endl; std::cout << "</para>" << std::endl; std::cout << "</listitem>" << std::endl; std::cout << "</varlistentry>" << std::endl; } } //namespace TCLAP #endif
8,525
30.461255
105
h
openalpr
openalpr-master/src/tclap/HelpVisitor.h
/****************************************************************************** * * file: HelpVisitor.h * * Copyright (c) 2003, Michael E. Smoot . * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_HELP_VISITOR_H #define TCLAP_HELP_VISITOR_H #include "CmdLineInterface.h" #include "CmdLineOutput.h" #include "Visitor.h" namespace TCLAP { /** * A Visitor object that calls the usage method of the given CmdLineOutput * object for the specified CmdLine object. */ class HelpVisitor: public Visitor { private: /** * Prevent accidental copying. */ HelpVisitor(const HelpVisitor& rhs); HelpVisitor& operator=(const HelpVisitor& rhs); protected: /** * The CmdLine the output will be generated for. */ CmdLineInterface* _cmd; /** * The output object. */ CmdLineOutput** _out; public: /** * Constructor. * \param cmd - The CmdLine the output will be generated for. * \param out - The type of output. */ HelpVisitor(CmdLineInterface* cmd, CmdLineOutput** out) : Visitor(), _cmd( cmd ), _out( out ) { } /** * Calls the usage method of the CmdLineOutput for the * specified CmdLine. */ void visit() { (*_out)->usage(*_cmd); throw ExitException(0); } }; } #endif
1,975
23.097561
79
h
openalpr
openalpr-master/src/tclap/IgnoreRestVisitor.h
/****************************************************************************** * * file: IgnoreRestVisitor.h * * Copyright (c) 2003, Michael E. Smoot . * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_IGNORE_REST_VISITOR_H #define TCLAP_IGNORE_REST_VISITOR_H #include "Visitor.h" #include "Arg.h" namespace TCLAP { /** * A Vistor that tells the CmdLine to begin ignoring arguments after * this one is parsed. */ class IgnoreRestVisitor: public Visitor { public: /** * Constructor. */ IgnoreRestVisitor() : Visitor() {} /** * Sets Arg::_ignoreRest. */ void visit() { Arg::beginIgnoring(); } }; } #endif
1,336
22.45614
79
h
openalpr
openalpr-master/src/tclap/MultiArg.h
/****************************************************************************** * * file: MultiArg.h * * Copyright (c) 2003, Michael E. Smoot . * Copyright (c) 2004, Michael E. Smoot, Daniel Aarno. * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_MULTIPLE_ARGUMENT_H #define TCLAP_MULTIPLE_ARGUMENT_H #include <string> #include <vector> #include "Arg.h" #include "Constraint.h" namespace TCLAP { /** * An argument that allows multiple values of type T to be specified. Very * similar to a ValueArg, except a vector of values will be returned * instead of just one. */ template<class T> class MultiArg : public Arg { public: typedef std::vector<T> container_type; typedef typename container_type::iterator iterator; typedef typename container_type::const_iterator const_iterator; protected: /** * The list of values parsed from the CmdLine. */ std::vector<T> _values; /** * The description of type T to be used in the usage. */ std::string _typeDesc; /** * A list of constraint on this Arg. */ Constraint<T>* _constraint; /** * Extracts the value from the string. * Attempts to parse string as type T, if this fails an exception * is thrown. * \param val - The string to be read. */ void _extractValue( const std::string& val ); /** * Used by XorHandler to decide whether to keep parsing for this arg. */ bool _allowMore; public: /** * Constructor. * \param flag - The one character flag that identifies this * argument on the command line. * \param name - A one word name for the argument. Can be * used as a long flag on the command line. * \param desc - A description of what the argument is for or * does. * \param req - Whether the argument is required on the command * line. * \param typeDesc - A short, human readable description of the * type that this object expects. This is used in the generation * of the USAGE statement. The goal is to be helpful to the end user * of the program. * \param v - An optional visitor. You probably should not * use this unless you have a very good reason. */ MultiArg( const std::string& flag, const std::string& name, const std::string& desc, bool req, const std::string& typeDesc, Visitor* v = NULL); /** * Constructor. * \param flag - The one character flag that identifies this * argument on the command line. * \param name - A one word name for the argument. Can be * used as a long flag on the command line. * \param desc - A description of what the argument is for or * does. * \param req - Whether the argument is required on the command * line. * \param typeDesc - A short, human readable description of the * type that this object expects. This is used in the generation * of the USAGE statement. The goal is to be helpful to the end user * of the program. * \param parser - A CmdLine parser object to add this Arg to * \param v - An optional visitor. You probably should not * use this unless you have a very good reason. */ MultiArg( const std::string& flag, const std::string& name, const std::string& desc, bool req, const std::string& typeDesc, CmdLineInterface& parser, Visitor* v = NULL ); /** * Constructor. * \param flag - The one character flag that identifies this * argument on the command line. * \param name - A one word name for the argument. Can be * used as a long flag on the command line. * \param desc - A description of what the argument is for or * does. * \param req - Whether the argument is required on the command * line. * \param constraint - A pointer to a Constraint object used * to constrain this Arg. * \param v - An optional visitor. You probably should not * use this unless you have a very good reason. */ MultiArg( const std::string& flag, const std::string& name, const std::string& desc, bool req, Constraint<T>* constraint, Visitor* v = NULL ); /** * Constructor. * \param flag - The one character flag that identifies this * argument on the command line. * \param name - A one word name for the argument. Can be * used as a long flag on the command line. * \param desc - A description of what the argument is for or * does. * \param req - Whether the argument is required on the command * line. * \param constraint - A pointer to a Constraint object used * to constrain this Arg. * \param parser - A CmdLine parser object to add this Arg to * \param v - An optional visitor. You probably should not * use this unless you have a very good reason. */ MultiArg( const std::string& flag, const std::string& name, const std::string& desc, bool req, Constraint<T>* constraint, CmdLineInterface& parser, Visitor* v = NULL ); /** * Handles the processing of the argument. * This re-implements the Arg version of this method to set the * _value of the argument appropriately. It knows the difference * between labeled and unlabeled. * \param i - Pointer the the current argument in the list. * \param args - Mutable list of strings. Passed from main(). */ virtual bool processArg(int* i, std::vector<std::string>& args); /** * Returns a vector of type T containing the values parsed from * the command line. */ const std::vector<T>& getValue(); /** * Returns an iterator over the values parsed from the command * line. */ const_iterator begin() const { return _values.begin(); } /** * Returns the end of the values parsed from the command * line. */ const_iterator end() const { return _values.end(); } /** * Returns the a short id string. Used in the usage. * \param val - value to be used. */ virtual std::string shortID(const std::string& val="val") const; /** * Returns the a long id string. Used in the usage. * \param val - value to be used. */ virtual std::string longID(const std::string& val="val") const; /** * Once we've matched the first value, then the arg is no longer * required. */ virtual bool isRequired() const; virtual bool allowMore(); virtual void reset(); private: /** * Prevent accidental copying */ MultiArg<T>(const MultiArg<T>& rhs); MultiArg<T>& operator=(const MultiArg<T>& rhs); }; template<class T> MultiArg<T>::MultiArg(const std::string& flag, const std::string& name, const std::string& desc, bool req, const std::string& typeDesc, Visitor* v) : Arg( flag, name, desc, req, true, v ), _values(std::vector<T>()), _typeDesc( typeDesc ), _constraint( NULL ), _allowMore(false) { _acceptsMultipleValues = true; } template<class T> MultiArg<T>::MultiArg(const std::string& flag, const std::string& name, const std::string& desc, bool req, const std::string& typeDesc, CmdLineInterface& parser, Visitor* v) : Arg( flag, name, desc, req, true, v ), _values(std::vector<T>()), _typeDesc( typeDesc ), _constraint( NULL ), _allowMore(false) { parser.add( this ); _acceptsMultipleValues = true; } /** * */ template<class T> MultiArg<T>::MultiArg(const std::string& flag, const std::string& name, const std::string& desc, bool req, Constraint<T>* constraint, Visitor* v) : Arg( flag, name, desc, req, true, v ), _values(std::vector<T>()), _typeDesc( constraint->shortID() ), _constraint( constraint ), _allowMore(false) { _acceptsMultipleValues = true; } template<class T> MultiArg<T>::MultiArg(const std::string& flag, const std::string& name, const std::string& desc, bool req, Constraint<T>* constraint, CmdLineInterface& parser, Visitor* v) : Arg( flag, name, desc, req, true, v ), _values(std::vector<T>()), _typeDesc( constraint->shortID() ), _constraint( constraint ), _allowMore(false) { parser.add( this ); _acceptsMultipleValues = true; } template<class T> const std::vector<T>& MultiArg<T>::getValue() { return _values; } template<class T> bool MultiArg<T>::processArg(int *i, std::vector<std::string>& args) { if ( _ignoreable && Arg::ignoreRest() ) return false; if ( _hasBlanks( args[*i] ) ) return false; std::string flag = args[*i]; std::string value = ""; trimFlag( flag, value ); if ( argMatches( flag ) ) { if ( Arg::delimiter() != ' ' && value == "" ) throw( ArgParseException( "Couldn't find delimiter for this argument!", toString() ) ); // always take the first one, regardless of start string if ( value == "" ) { (*i)++; if ( static_cast<unsigned int>(*i) < args.size() ) _extractValue( args[*i] ); else throw( ArgParseException("Missing a value for this argument!", toString() ) ); } else _extractValue( value ); /* // continuing taking the args until we hit one with a start string while ( (unsigned int)(*i)+1 < args.size() && args[(*i)+1].find_first_of( Arg::flagStartString() ) != 0 && args[(*i)+1].find_first_of( Arg::nameStartString() ) != 0 ) _extractValue( args[++(*i)] ); */ _alreadySet = true; _checkWithVisitor(); return true; } else return false; } /** * */ template<class T> std::string MultiArg<T>::shortID(const std::string& val) const { static_cast<void>(val); // Ignore input, don't warn return Arg::shortID(_typeDesc) + " ... "; } /** * */ template<class T> std::string MultiArg<T>::longID(const std::string& val) const { static_cast<void>(val); // Ignore input, don't warn return Arg::longID(_typeDesc) + " (accepted multiple times)"; } /** * Once we've matched the first value, then the arg is no longer * required. */ template<class T> bool MultiArg<T>::isRequired() const { if ( _required ) { if ( _values.size() > 1 ) return false; else return true; } else return false; } template<class T> void MultiArg<T>::_extractValue( const std::string& val ) { try { T tmp; ExtractValue(tmp, val, typename ArgTraits<T>::ValueCategory()); _values.push_back(tmp); } catch( ArgParseException &e) { throw ArgParseException(e.error(), toString()); } if ( _constraint != NULL ) if ( ! _constraint->check( _values.back() ) ) throw( CmdLineParseException( "Value '" + val + "' does not meet constraint: " + _constraint->description(), toString() ) ); } template<class T> bool MultiArg<T>::allowMore() { bool am = _allowMore; _allowMore = true; return am; } template<class T> void MultiArg<T>::reset() { Arg::reset(); _values.clear(); } } // namespace TCLAP #endif
12,530
27.675057
79
h
openalpr
openalpr-master/src/tclap/MultiSwitchArg.h
/****************************************************************************** * * file: MultiSwitchArg.h * * Copyright (c) 2003, Michael E. Smoot . * Copyright (c) 2004, Michael E. Smoot, Daniel Aarno. * Copyright (c) 2005, Michael E. Smoot, Daniel Aarno, Erik Zeek. * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_MULTI_SWITCH_ARG_H #define TCLAP_MULTI_SWITCH_ARG_H #include <string> #include <vector> #include "SwitchArg.h" namespace TCLAP { /** * A multiple switch argument. If the switch is set on the command line, then * the getValue method will return the number of times the switch appears. */ class MultiSwitchArg : public SwitchArg { protected: /** * The value of the switch. */ int _value; /** * Used to support the reset() method so that ValueArg can be * reset to their constructed value. */ int _default; public: /** * MultiSwitchArg constructor. * \param flag - The one character flag that identifies this * argument on the command line. * \param name - A one word name for the argument. Can be * used as a long flag on the command line. * \param desc - A description of what the argument is for or * does. * \param init - Optional. The initial/default value of this Arg. * Defaults to 0. * \param v - An optional visitor. You probably should not * use this unless you have a very good reason. */ MultiSwitchArg(const std::string& flag, const std::string& name, const std::string& desc, int init = 0, Visitor* v = NULL); /** * MultiSwitchArg constructor. * \param flag - The one character flag that identifies this * argument on the command line. * \param name - A one word name for the argument. Can be * used as a long flag on the command line. * \param desc - A description of what the argument is for or * does. * \param parser - A CmdLine parser object to add this Arg to * \param init - Optional. The initial/default value of this Arg. * Defaults to 0. * \param v - An optional visitor. You probably should not * use this unless you have a very good reason. */ MultiSwitchArg(const std::string& flag, const std::string& name, const std::string& desc, CmdLineInterface& parser, int init = 0, Visitor* v = NULL); /** * Handles the processing of the argument. * This re-implements the SwitchArg version of this method to set the * _value of the argument appropriately. * \param i - Pointer the the current argument in the list. * \param args - Mutable list of strings. Passed * in from main(). */ virtual bool processArg(int* i, std::vector<std::string>& args); /** * Returns int, the number of times the switch has been set. */ int getValue(); /** * Returns the shortID for this Arg. */ std::string shortID(const std::string& val) const; /** * Returns the longID for this Arg. */ std::string longID(const std::string& val) const; void reset(); }; ////////////////////////////////////////////////////////////////////// //BEGIN MultiSwitchArg.cpp ////////////////////////////////////////////////////////////////////// inline MultiSwitchArg::MultiSwitchArg(const std::string& flag, const std::string& name, const std::string& desc, int init, Visitor* v ) : SwitchArg(flag, name, desc, false, v), _value( init ), _default( init ) { } inline MultiSwitchArg::MultiSwitchArg(const std::string& flag, const std::string& name, const std::string& desc, CmdLineInterface& parser, int init, Visitor* v ) : SwitchArg(flag, name, desc, false, v), _value( init ), _default( init ) { parser.add( this ); } inline int MultiSwitchArg::getValue() { return _value; } inline bool MultiSwitchArg::processArg(int *i, std::vector<std::string>& args) { if ( _ignoreable && Arg::ignoreRest() ) return false; if ( argMatches( args[*i] )) { // so the isSet() method will work _alreadySet = true; // Matched argument: increment value. ++_value; _checkWithVisitor(); return true; } else if ( combinedSwitchesMatch( args[*i] ) ) { // so the isSet() method will work _alreadySet = true; // Matched argument: increment value. ++_value; // Check for more in argument and increment value. while ( combinedSwitchesMatch( args[*i] ) ) ++_value; _checkWithVisitor(); return false; } else return false; } inline std::string MultiSwitchArg::shortID(const std::string& val) const { return Arg::shortID(val) + " ... "; } inline std::string MultiSwitchArg::longID(const std::string& val) const { return Arg::longID(val) + " (accepted multiple times)"; } inline void MultiSwitchArg::reset() { MultiSwitchArg::_value = MultiSwitchArg::_default; } ////////////////////////////////////////////////////////////////////// //END MultiSwitchArg.cpp ////////////////////////////////////////////////////////////////////// } //namespace TCLAP #endif
6,222
28.215962
79
h
openalpr
openalpr-master/src/tclap/OptionalUnlabeledTracker.h
/****************************************************************************** * * file: OptionalUnlabeledTracker.h * * Copyright (c) 2005, Michael E. Smoot . * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_OPTIONAL_UNLABELED_TRACKER_H #define TCLAP_OPTIONAL_UNLABELED_TRACKER_H #include <string> namespace TCLAP { class OptionalUnlabeledTracker { public: static void check( bool req, const std::string& argName ); static void gotOptional() { alreadyOptionalRef() = true; } static bool& alreadyOptional() { return alreadyOptionalRef(); } private: static bool& alreadyOptionalRef() { static bool ct = false; return ct; } }; inline void OptionalUnlabeledTracker::check( bool req, const std::string& argName ) { if ( OptionalUnlabeledTracker::alreadyOptional() ) throw( SpecificationException( "You can't specify ANY Unlabeled Arg following an optional Unlabeled Arg", argName ) ); if ( !req ) OptionalUnlabeledTracker::gotOptional(); } } // namespace TCLAP #endif
1,756
23.068493
87
h
openalpr
openalpr-master/src/tclap/StdOutput.h
// -*- Mode: c++; c-basic-offset: 4; tab-width: 4; -*- /****************************************************************************** * * file: StdOutput.h * * Copyright (c) 2004, Michael E. Smoot * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_STDCMDLINEOUTPUT_H #define TCLAP_STDCMDLINEOUTPUT_H #include <string> #include <vector> #include <list> #include <iostream> #include <algorithm> #include "CmdLineInterface.h" #include "CmdLineOutput.h" #include "XorHandler.h" #include "Arg.h" namespace TCLAP { /** * A class that isolates any output from the CmdLine object so that it * may be easily modified. */ class StdOutput : public CmdLineOutput { public: /** * Prints the usage to stdout. Can be overridden to * produce alternative behavior. * \param c - The CmdLine object the output is generated for. */ virtual void usage(CmdLineInterface& c); /** * Prints the version to stdout. Can be overridden * to produce alternative behavior. * \param c - The CmdLine object the output is generated for. */ virtual void version(CmdLineInterface& c); /** * Prints (to stderr) an error message, short usage * Can be overridden to produce alternative behavior. * \param c - The CmdLine object the output is generated for. * \param e - The ArgException that caused the failure. */ virtual void failure(CmdLineInterface& c, ArgException& e ); protected: /** * Writes a brief usage message with short args. * \param c - The CmdLine object the output is generated for. * \param os - The stream to write the message to. */ void _shortUsage( CmdLineInterface& c, std::ostream& os ) const; /** * Writes a longer usage message with long and short args, * provides descriptions and prints message. * \param c - The CmdLine object the output is generated for. * \param os - The stream to write the message to. */ void _longUsage( CmdLineInterface& c, std::ostream& os ) const; /** * This function inserts line breaks and indents long strings * according the params input. It will only break lines at spaces, * commas and pipes. * \param os - The stream to be printed to. * \param s - The string to be printed. * \param maxWidth - The maxWidth allowed for the output line. * \param indentSpaces - The number of spaces to indent the first line. * \param secondLineOffset - The number of spaces to indent the second * and all subsequent lines in addition to indentSpaces. */ void spacePrint( std::ostream& os, const std::string& s, int maxWidth, int indentSpaces, int secondLineOffset ) const; }; inline void StdOutput::version(CmdLineInterface& _cmd) { std::string progName = _cmd.getProgramName(); std::string xversion = _cmd.getVersion(); std::cout << std::endl << progName << " version: " << xversion << std::endl << std::endl; } inline void StdOutput::usage(CmdLineInterface& _cmd ) { std::cout << std::endl << "USAGE: " << std::endl << std::endl; _shortUsage( _cmd, std::cout ); std::cout << std::endl << std::endl << "Where: " << std::endl << std::endl; _longUsage( _cmd, std::cout ); std::cout << std::endl; } inline void StdOutput::failure( CmdLineInterface& _cmd, ArgException& e ) { std::string progName = _cmd.getProgramName(); std::cerr << "PARSE ERROR: " << e.argId() << std::endl << " " << e.error() << std::endl << std::endl; if ( _cmd.hasHelpAndVersion() ) { std::cerr << "Brief USAGE: " << std::endl; _shortUsage( _cmd, std::cerr ); std::cerr << std::endl << "For complete USAGE and HELP type: " << std::endl << " " << progName << " --help" << std::endl << std::endl; } else usage(_cmd); throw ExitException(1); } inline void StdOutput::_shortUsage( CmdLineInterface& _cmd, std::ostream& os ) const { std::list<Arg*> argList = _cmd.getArgList(); std::string progName = _cmd.getProgramName(); XorHandler xorHandler = _cmd.getXorHandler(); std::vector< std::vector<Arg*> > xorList = xorHandler.getXorList(); std::string s = progName + " "; // first the xor for ( int i = 0; static_cast<unsigned int>(i) < xorList.size(); i++ ) { s += " {"; for ( ArgVectorIterator it = xorList[i].begin(); it != xorList[i].end(); it++ ) s += (*it)->shortID() + "|"; s[s.length()-1] = '}'; } // then the rest for (ArgListIterator it = argList.begin(); it != argList.end(); it++) if ( !xorHandler.contains( (*it) ) ) s += " " + (*it)->shortID(); // if the program name is too long, then adjust the second line offset int secondLineOffset = static_cast<int>(progName.length()) + 2; if ( secondLineOffset > 75/2 ) secondLineOffset = static_cast<int>(75/2); spacePrint( os, s, 75, 3, secondLineOffset ); } inline void StdOutput::_longUsage( CmdLineInterface& _cmd, std::ostream& os ) const { std::list<Arg*> argList = _cmd.getArgList(); std::string message = _cmd.getMessage(); XorHandler xorHandler = _cmd.getXorHandler(); std::vector< std::vector<Arg*> > xorList = xorHandler.getXorList(); // first the xor for ( int i = 0; static_cast<unsigned int>(i) < xorList.size(); i++ ) { for ( ArgVectorIterator it = xorList[i].begin(); it != xorList[i].end(); it++ ) { spacePrint( os, (*it)->longID(), 75, 3, 3 ); spacePrint( os, (*it)->getDescription(), 75, 5, 0 ); if ( it+1 != xorList[i].end() ) spacePrint(os, "-- OR --", 75, 9, 0); } os << std::endl << std::endl; } // then the rest for (ArgListIterator it = argList.begin(); it != argList.end(); it++) if ( !xorHandler.contains( (*it) ) ) { spacePrint( os, (*it)->longID(), 75, 3, 3 ); spacePrint( os, (*it)->getDescription(), 75, 5, 0 ); os << std::endl; } os << std::endl; spacePrint( os, message, 75, 3, 0 ); } inline void StdOutput::spacePrint( std::ostream& os, const std::string& s, int maxWidth, int indentSpaces, int secondLineOffset ) const { int len = static_cast<int>(s.length()); if ( (len + indentSpaces > maxWidth) && maxWidth > 0 ) { int allowedLen = maxWidth - indentSpaces; int start = 0; while ( start < len ) { // find the substring length // int stringLen = std::min<int>( len - start, allowedLen ); // doing it this way to support a VisualC++ 2005 bug using namespace std; int stringLen = min<int>( len - start, allowedLen ); // trim the length so it doesn't end in middle of a word if ( stringLen == allowedLen ) while ( stringLen >= 0 && s[stringLen+start] != ' ' && s[stringLen+start] != ',' && s[stringLen+start] != '|' ) stringLen--; // ok, the word is longer than the line, so just split // wherever the line ends if ( stringLen <= 0 ) stringLen = allowedLen; // check for newlines for ( int i = 0; i < stringLen; i++ ) if ( s[start+i] == '\n' ) stringLen = i+1; // print the indent for ( int i = 0; i < indentSpaces; i++ ) os << " "; if ( start == 0 ) { // handle second line offsets indentSpaces += secondLineOffset; // adjust allowed len allowedLen -= secondLineOffset; } os << s.substr(start,stringLen) << std::endl; // so we don't start a line with a space while ( s[stringLen+start] == ' ' && start < len ) start++; start += stringLen; } } else { for ( int i = 0; i < indentSpaces; i++ ) os << " "; os << s << std::endl; } } } //namespace TCLAP #endif
8,756
31.675373
79
h
openalpr
openalpr-master/src/tclap/SwitchArg.h
/****************************************************************************** * * file: SwitchArg.h * * Copyright (c) 2003, Michael E. Smoot . * Copyright (c) 2004, Michael E. Smoot, Daniel Aarno. * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_SWITCH_ARG_H #define TCLAP_SWITCH_ARG_H #include <string> #include <vector> #include "Arg.h" namespace TCLAP { /** * A simple switch argument. If the switch is set on the command line, then * the getValue method will return the opposite of the default value for the * switch. */ class SwitchArg : public Arg { protected: /** * The value of the switch. */ bool _value; /** * Used to support the reset() method so that ValueArg can be * reset to their constructed value. */ bool _default; public: /** * SwitchArg constructor. * \param flag - The one character flag that identifies this * argument on the command line. * \param name - A one word name for the argument. Can be * used as a long flag on the command line. * \param desc - A description of what the argument is for or * does. * \param def - The default value for this Switch. * \param v - An optional visitor. You probably should not * use this unless you have a very good reason. */ SwitchArg(const std::string& flag, const std::string& name, const std::string& desc, bool def = false, Visitor* v = NULL); /** * SwitchArg constructor. * \param flag - The one character flag that identifies this * argument on the command line. * \param name - A one word name for the argument. Can be * used as a long flag on the command line. * \param desc - A description of what the argument is for or * does. * \param parser - A CmdLine parser object to add this Arg to * \param def - The default value for this Switch. * \param v - An optional visitor. You probably should not * use this unless you have a very good reason. */ SwitchArg(const std::string& flag, const std::string& name, const std::string& desc, CmdLineInterface& parser, bool def = false, Visitor* v = NULL); /** * Handles the processing of the argument. * This re-implements the Arg version of this method to set the * _value of the argument appropriately. * \param i - Pointer the the current argument in the list. * \param args - Mutable list of strings. Passed * in from main(). */ virtual bool processArg(int* i, std::vector<std::string>& args); /** * Checks a string to see if any of the chars in the string * match the flag for this Switch. */ bool combinedSwitchesMatch(std::string& combined); /** * Returns bool, whether or not the switch has been set. */ bool getValue(); virtual void reset(); private: /** * Checks to see if we've found the last match in * a combined string. */ bool lastCombined(std::string& combined); /** * Does the common processing of processArg. */ void commonProcessing(); }; ////////////////////////////////////////////////////////////////////// //BEGIN SwitchArg.cpp ////////////////////////////////////////////////////////////////////// inline SwitchArg::SwitchArg(const std::string& flag, const std::string& name, const std::string& desc, bool default_val, Visitor* v ) : Arg(flag, name, desc, false, false, v), _value( default_val ), _default( default_val ) { } inline SwitchArg::SwitchArg(const std::string& flag, const std::string& name, const std::string& desc, CmdLineInterface& parser, bool default_val, Visitor* v ) : Arg(flag, name, desc, false, false, v), _value( default_val ), _default(default_val) { parser.add( this ); } inline bool SwitchArg::getValue() { return _value; } inline bool SwitchArg::lastCombined(std::string& combinedSwitches ) { for ( unsigned int i = 1; i < combinedSwitches.length(); i++ ) if ( combinedSwitches[i] != Arg::blankChar() ) return false; return true; } inline bool SwitchArg::combinedSwitchesMatch(std::string& combinedSwitches ) { // make sure this is actually a combined switch if ( combinedSwitches.length() > 0 && combinedSwitches[0] != Arg::flagStartString()[0] ) return false; // make sure it isn't a long name if ( combinedSwitches.substr( 0, Arg::nameStartString().length() ) == Arg::nameStartString() ) return false; // make sure the delimiter isn't in the string if ( combinedSwitches.find_first_of( Arg::delimiter() ) != std::string::npos ) return false; // ok, we're not specifying a ValueArg, so we know that we have // a combined switch list. for ( unsigned int i = 1; i < combinedSwitches.length(); i++ ) if ( _flag.length() > 0 && combinedSwitches[i] == _flag[0] && _flag[0] != Arg::flagStartString()[0] ) { // update the combined switches so this one is no longer present // this is necessary so that no unlabeled args are matched // later in the processing. //combinedSwitches.erase(i,1); combinedSwitches[i] = Arg::blankChar(); return true; } // none of the switches passed in the list match. return false; } inline void SwitchArg::commonProcessing() { if ( _xorSet ) throw(CmdLineParseException( "Mutually exclusive argument already set!", toString())); if ( _alreadySet ) throw(CmdLineParseException("Argument already set!", toString())); _alreadySet = true; if ( _value == true ) _value = false; else _value = true; _checkWithVisitor(); } inline bool SwitchArg::processArg(int *i, std::vector<std::string>& args) { if ( _ignoreable && Arg::ignoreRest() ) return false; // if the whole string matches the flag or name string if ( argMatches( args[*i] ) ) { commonProcessing(); return true; } // if a substring matches the flag as part of a combination else if ( combinedSwitchesMatch( args[*i] ) ) { // check again to ensure we don't misinterpret // this as a MultiSwitchArg if ( combinedSwitchesMatch( args[*i] ) ) throw(CmdLineParseException("Argument already set!", toString())); commonProcessing(); // We only want to return true if we've found the last combined // match in the string, otherwise we return true so that other // switches in the combination will have a chance to match. return lastCombined( args[*i] ); } else return false; } inline void SwitchArg::reset() { Arg::reset(); _value = _default; } ////////////////////////////////////////////////////////////////////// //End SwitchArg.cpp ////////////////////////////////////////////////////////////////////// } //namespace TCLAP #endif
7,849
29.426357
80
h
openalpr
openalpr-master/src/tclap/UnlabeledMultiArg.h
/****************************************************************************** * * file: UnlabeledMultiArg.h * * Copyright (c) 2003, Michael E. Smoot. * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_MULTIPLE_UNLABELED_ARGUMENT_H #define TCLAP_MULTIPLE_UNLABELED_ARGUMENT_H #include <string> #include <vector> #include "MultiArg.h" #include "OptionalUnlabeledTracker.h" namespace TCLAP { /** * Just like a MultiArg, except that the arguments are unlabeled. Basically, * this Arg will slurp up everything that hasn't been matched to another * Arg. */ template<class T> class UnlabeledMultiArg : public MultiArg<T> { // If compiler has two stage name lookup (as gcc >= 3.4 does) // this is requried to prevent undef. symbols using MultiArg<T>::_ignoreable; using MultiArg<T>::_hasBlanks; using MultiArg<T>::_extractValue; using MultiArg<T>::_typeDesc; using MultiArg<T>::_name; using MultiArg<T>::_description; using MultiArg<T>::_alreadySet; using MultiArg<T>::toString; public: /** * Constructor. * \param name - The name of the Arg. Note that this is used for * identification, not as a long flag. * \param desc - A description of what the argument is for or * does. * \param req - Whether the argument is required on the command * line. * \param typeDesc - A short, human readable description of the * type that this object expects. This is used in the generation * of the USAGE statement. The goal is to be helpful to the end user * of the program. * \param ignoreable - Whether or not this argument can be ignored * using the "--" flag. * \param v - An optional visitor. You probably should not * use this unless you have a very good reason. */ UnlabeledMultiArg( const std::string& name, const std::string& desc, bool req, const std::string& typeDesc, bool ignoreable = false, Visitor* v = NULL ); /** * Constructor. * \param name - The name of the Arg. Note that this is used for * identification, not as a long flag. * \param desc - A description of what the argument is for or * does. * \param req - Whether the argument is required on the command * line. * \param typeDesc - A short, human readable description of the * type that this object expects. This is used in the generation * of the USAGE statement. The goal is to be helpful to the end user * of the program. * \param parser - A CmdLine parser object to add this Arg to * \param ignoreable - Whether or not this argument can be ignored * using the "--" flag. * \param v - An optional visitor. You probably should not * use this unless you have a very good reason. */ UnlabeledMultiArg( const std::string& name, const std::string& desc, bool req, const std::string& typeDesc, CmdLineInterface& parser, bool ignoreable = false, Visitor* v = NULL ); /** * Constructor. * \param name - The name of the Arg. Note that this is used for * identification, not as a long flag. * \param desc - A description of what the argument is for or * does. * \param req - Whether the argument is required on the command * line. * \param constraint - A pointer to a Constraint object used * to constrain this Arg. * \param ignoreable - Whether or not this argument can be ignored * using the "--" flag. * \param v - An optional visitor. You probably should not * use this unless you have a very good reason. */ UnlabeledMultiArg( const std::string& name, const std::string& desc, bool req, Constraint<T>* constraint, bool ignoreable = false, Visitor* v = NULL ); /** * Constructor. * \param name - The name of the Arg. Note that this is used for * identification, not as a long flag. * \param desc - A description of what the argument is for or * does. * \param req - Whether the argument is required on the command * line. * \param constraint - A pointer to a Constraint object used * to constrain this Arg. * \param parser - A CmdLine parser object to add this Arg to * \param ignoreable - Whether or not this argument can be ignored * using the "--" flag. * \param v - An optional visitor. You probably should not * use this unless you have a very good reason. */ UnlabeledMultiArg( const std::string& name, const std::string& desc, bool req, Constraint<T>* constraint, CmdLineInterface& parser, bool ignoreable = false, Visitor* v = NULL ); /** * Handles the processing of the argument. * This re-implements the Arg version of this method to set the * _value of the argument appropriately. It knows the difference * between labeled and unlabeled. * \param i - Pointer the the current argument in the list. * \param args - Mutable list of strings. Passed from main(). */ virtual bool processArg(int* i, std::vector<std::string>& args); /** * Returns the a short id string. Used in the usage. * \param val - value to be used. */ virtual std::string shortID(const std::string& val="val") const; /** * Returns the a long id string. Used in the usage. * \param val - value to be used. */ virtual std::string longID(const std::string& val="val") const; /** * Opertor ==. * \param a - The Arg to be compared to this. */ virtual bool operator==(const Arg& a) const; /** * Pushes this to back of list rather than front. * \param argList - The list this should be added to. */ virtual void addToList( std::list<Arg*>& argList ) const; }; template<class T> UnlabeledMultiArg<T>::UnlabeledMultiArg(const std::string& name, const std::string& desc, bool req, const std::string& typeDesc, bool ignoreable, Visitor* v) : MultiArg<T>("", name, desc, req, typeDesc, v) { _ignoreable = ignoreable; OptionalUnlabeledTracker::check(true, toString()); } template<class T> UnlabeledMultiArg<T>::UnlabeledMultiArg(const std::string& name, const std::string& desc, bool req, const std::string& typeDesc, CmdLineInterface& parser, bool ignoreable, Visitor* v) : MultiArg<T>("", name, desc, req, typeDesc, v) { _ignoreable = ignoreable; OptionalUnlabeledTracker::check(true, toString()); parser.add( this ); } template<class T> UnlabeledMultiArg<T>::UnlabeledMultiArg(const std::string& name, const std::string& desc, bool req, Constraint<T>* constraint, bool ignoreable, Visitor* v) : MultiArg<T>("", name, desc, req, constraint, v) { _ignoreable = ignoreable; OptionalUnlabeledTracker::check(true, toString()); } template<class T> UnlabeledMultiArg<T>::UnlabeledMultiArg(const std::string& name, const std::string& desc, bool req, Constraint<T>* constraint, CmdLineInterface& parser, bool ignoreable, Visitor* v) : MultiArg<T>("", name, desc, req, constraint, v) { _ignoreable = ignoreable; OptionalUnlabeledTracker::check(true, toString()); parser.add( this ); } template<class T> bool UnlabeledMultiArg<T>::processArg(int *i, std::vector<std::string>& args) { if ( _hasBlanks( args[*i] ) ) return false; // never ignore an unlabeled multi arg // always take the first value, regardless of the start string _extractValue( args[(*i)] ); /* // continue taking args until we hit the end or a start string while ( (unsigned int)(*i)+1 < args.size() && args[(*i)+1].find_first_of( Arg::flagStartString() ) != 0 && args[(*i)+1].find_first_of( Arg::nameStartString() ) != 0 ) _extractValue( args[++(*i)] ); */ _alreadySet = true; return true; } template<class T> std::string UnlabeledMultiArg<T>::shortID(const std::string& val) const { static_cast<void>(val); // Ignore input, don't warn return std::string("<") + _typeDesc + "> ..."; } template<class T> std::string UnlabeledMultiArg<T>::longID(const std::string& val) const { static_cast<void>(val); // Ignore input, don't warn return std::string("<") + _typeDesc + "> (accepted multiple times)"; } template<class T> bool UnlabeledMultiArg<T>::operator==(const Arg& a) const { if ( _name == a.getName() || _description == a.getDescription() ) return true; else return false; } template<class T> void UnlabeledMultiArg<T>::addToList( std::list<Arg*>& argList ) const { argList.push_back( const_cast<Arg*>(static_cast<const Arg* const>(this)) ); } } #endif
10,551
34.648649
79
h
openalpr
openalpr-master/src/tclap/UnlabeledValueArg.h
/****************************************************************************** * * file: UnlabeledValueArg.h * * Copyright (c) 2003, Michael E. Smoot . * Copyright (c) 2004, Michael E. Smoot, Daniel Aarno. * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_UNLABELED_VALUE_ARGUMENT_H #define TCLAP_UNLABELED_VALUE_ARGUMENT_H #include <string> #include <vector> #include "ValueArg.h" #include "OptionalUnlabeledTracker.h" namespace TCLAP { /** * The basic unlabeled argument that parses a value. * This is a template class, which means the type T defines the type * that a given object will attempt to parse when an UnlabeledValueArg * is reached in the list of args that the CmdLine iterates over. */ template<class T> class UnlabeledValueArg : public ValueArg<T> { // If compiler has two stage name lookup (as gcc >= 3.4 does) // this is requried to prevent undef. symbols using ValueArg<T>::_ignoreable; using ValueArg<T>::_hasBlanks; using ValueArg<T>::_extractValue; using ValueArg<T>::_typeDesc; using ValueArg<T>::_name; using ValueArg<T>::_description; using ValueArg<T>::_alreadySet; using ValueArg<T>::toString; public: /** * UnlabeledValueArg constructor. * \param name - A one word name for the argument. Note that this is used for * identification, not as a long flag. * \param desc - A description of what the argument is for or * does. * \param req - Whether the argument is required on the command * line. * \param value - The default value assigned to this argument if it * is not present on the command line. * \param typeDesc - A short, human readable description of the * type that this object expects. This is used in the generation * of the USAGE statement. The goal is to be helpful to the end user * of the program. * \param ignoreable - Allows you to specify that this argument can be * ignored if the '--' flag is set. This defaults to false (cannot * be ignored) and should generally stay that way unless you have * some special need for certain arguments to be ignored. * \param v - Optional Vistor. You should leave this blank unless * you have a very good reason. */ UnlabeledValueArg( const std::string& name, const std::string& desc, bool req, T value, const std::string& typeDesc, bool ignoreable = false, Visitor* v = NULL); /** * UnlabeledValueArg constructor. * \param name - A one word name for the argument. Note that this is used for * identification, not as a long flag. * \param desc - A description of what the argument is for or * does. * \param req - Whether the argument is required on the command * line. * \param value - The default value assigned to this argument if it * is not present on the command line. * \param typeDesc - A short, human readable description of the * type that this object expects. This is used in the generation * of the USAGE statement. The goal is to be helpful to the end user * of the program. * \param parser - A CmdLine parser object to add this Arg to * \param ignoreable - Allows you to specify that this argument can be * ignored if the '--' flag is set. This defaults to false (cannot * be ignored) and should generally stay that way unless you have * some special need for certain arguments to be ignored. * \param v - Optional Vistor. You should leave this blank unless * you have a very good reason. */ UnlabeledValueArg( const std::string& name, const std::string& desc, bool req, T value, const std::string& typeDesc, CmdLineInterface& parser, bool ignoreable = false, Visitor* v = NULL ); /** * UnlabeledValueArg constructor. * \param name - A one word name for the argument. Note that this is used for * identification, not as a long flag. * \param desc - A description of what the argument is for or * does. * \param req - Whether the argument is required on the command * line. * \param value - The default value assigned to this argument if it * is not present on the command line. * \param constraint - A pointer to a Constraint object used * to constrain this Arg. * \param ignoreable - Allows you to specify that this argument can be * ignored if the '--' flag is set. This defaults to false (cannot * be ignored) and should generally stay that way unless you have * some special need for certain arguments to be ignored. * \param v - Optional Vistor. You should leave this blank unless * you have a very good reason. */ UnlabeledValueArg( const std::string& name, const std::string& desc, bool req, T value, Constraint<T>* constraint, bool ignoreable = false, Visitor* v = NULL ); /** * UnlabeledValueArg constructor. * \param name - A one word name for the argument. Note that this is used for * identification, not as a long flag. * \param desc - A description of what the argument is for or * does. * \param req - Whether the argument is required on the command * line. * \param value - The default value assigned to this argument if it * is not present on the command line. * \param constraint - A pointer to a Constraint object used * to constrain this Arg. * \param parser - A CmdLine parser object to add this Arg to * \param ignoreable - Allows you to specify that this argument can be * ignored if the '--' flag is set. This defaults to false (cannot * be ignored) and should generally stay that way unless you have * some special need for certain arguments to be ignored. * \param v - Optional Vistor. You should leave this blank unless * you have a very good reason. */ UnlabeledValueArg( const std::string& name, const std::string& desc, bool req, T value, Constraint<T>* constraint, CmdLineInterface& parser, bool ignoreable = false, Visitor* v = NULL); /** * Handles the processing of the argument. * This re-implements the Arg version of this method to set the * _value of the argument appropriately. Handling specific to * unlabled arguments. * \param i - Pointer the the current argument in the list. * \param args - Mutable list of strings. */ virtual bool processArg(int* i, std::vector<std::string>& args); /** * Overrides shortID for specific behavior. */ virtual std::string shortID(const std::string& val="val") const; /** * Overrides longID for specific behavior. */ virtual std::string longID(const std::string& val="val") const; /** * Overrides operator== for specific behavior. */ virtual bool operator==(const Arg& a ) const; /** * Instead of pushing to the front of list, push to the back. * \param argList - The list to add this to. */ virtual void addToList( std::list<Arg*>& argList ) const; }; /** * Constructor implemenation. */ template<class T> UnlabeledValueArg<T>::UnlabeledValueArg(const std::string& name, const std::string& desc, bool req, T val, const std::string& typeDesc, bool ignoreable, Visitor* v) : ValueArg<T>("", name, desc, req, val, typeDesc, v) { _ignoreable = ignoreable; OptionalUnlabeledTracker::check(req, toString()); } template<class T> UnlabeledValueArg<T>::UnlabeledValueArg(const std::string& name, const std::string& desc, bool req, T val, const std::string& typeDesc, CmdLineInterface& parser, bool ignoreable, Visitor* v) : ValueArg<T>("", name, desc, req, val, typeDesc, v) { _ignoreable = ignoreable; OptionalUnlabeledTracker::check(req, toString()); parser.add( this ); } /** * Constructor implemenation. */ template<class T> UnlabeledValueArg<T>::UnlabeledValueArg(const std::string& name, const std::string& desc, bool req, T val, Constraint<T>* constraint, bool ignoreable, Visitor* v) : ValueArg<T>("", name, desc, req, val, constraint, v) { _ignoreable = ignoreable; OptionalUnlabeledTracker::check(req, toString()); } template<class T> UnlabeledValueArg<T>::UnlabeledValueArg(const std::string& name, const std::string& desc, bool req, T val, Constraint<T>* constraint, CmdLineInterface& parser, bool ignoreable, Visitor* v) : ValueArg<T>("", name, desc, req, val, constraint, v) { _ignoreable = ignoreable; OptionalUnlabeledTracker::check(req, toString()); parser.add( this ); } /** * Implementation of processArg(). */ template<class T> bool UnlabeledValueArg<T>::processArg(int *i, std::vector<std::string>& args) { if ( _alreadySet ) return false; if ( _hasBlanks( args[*i] ) ) return false; // never ignore an unlabeled arg _extractValue( args[*i] ); _alreadySet = true; return true; } /** * Overriding shortID for specific output. */ template<class T> std::string UnlabeledValueArg<T>::shortID(const std::string& val) const { static_cast<void>(val); // Ignore input, don't warn return std::string("<") + _typeDesc + ">"; } /** * Overriding longID for specific output. */ template<class T> std::string UnlabeledValueArg<T>::longID(const std::string& val) const { static_cast<void>(val); // Ignore input, don't warn // Ideally we would like to be able to use RTTI to return the name // of the type required for this argument. However, g++ at least, // doesn't appear to return terribly useful "names" of the types. return std::string("<") + _typeDesc + ">"; } /** * Overriding operator== for specific behavior. */ template<class T> bool UnlabeledValueArg<T>::operator==(const Arg& a ) const { if ( _name == a.getName() || _description == a.getDescription() ) return true; else return false; } template<class T> void UnlabeledValueArg<T>::addToList( std::list<Arg*>& argList ) const { argList.push_back( const_cast<Arg*>(static_cast<const Arg* const>(this)) ); } } #endif
12,282
35.665672
82
h
openalpr
openalpr-master/src/tclap/ValueArg.h
/****************************************************************************** * * file: ValueArg.h * * Copyright (c) 2003, Michael E. Smoot . * Copyright (c) 2004, Michael E. Smoot, Daniel Aarno. * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_VALUE_ARGUMENT_H #define TCLAP_VALUE_ARGUMENT_H #include <string> #include <vector> #include "Arg.h" #include "Constraint.h" namespace TCLAP { /** * The basic labeled argument that parses a value. * This is a template class, which means the type T defines the type * that a given object will attempt to parse when the flag/name is matched * on the command line. While there is nothing stopping you from creating * an unflagged ValueArg, it is unwise and would cause significant problems. * Instead use an UnlabeledValueArg. */ template<class T> class ValueArg : public Arg { protected: /** * The value parsed from the command line. * Can be of any type, as long as the >> operator for the type * is defined. */ T _value; /** * Used to support the reset() method so that ValueArg can be * reset to their constructed value. */ T _default; /** * A human readable description of the type to be parsed. * This is a hack, plain and simple. Ideally we would use RTTI to * return the name of type T, but until there is some sort of * consistent support for human readable names, we are left to our * own devices. */ std::string _typeDesc; /** * A Constraint this Arg must conform to. */ Constraint<T>* _constraint; /** * Extracts the value from the string. * Attempts to parse string as type T, if this fails an exception * is thrown. * \param val - value to be parsed. */ void _extractValue( const std::string& val ); public: /** * Labeled ValueArg constructor. * You could conceivably call this constructor with a blank flag, * but that would make you a bad person. It would also cause * an exception to be thrown. If you want an unlabeled argument, * use the other constructor. * \param flag - The one character flag that identifies this * argument on the command line. * \param name - A one word name for the argument. Can be * used as a long flag on the command line. * \param desc - A description of what the argument is for or * does. * \param req - Whether the argument is required on the command * line. * \param value - The default value assigned to this argument if it * is not present on the command line. * \param typeDesc - A short, human readable description of the * type that this object expects. This is used in the generation * of the USAGE statement. The goal is to be helpful to the end user * of the program. * \param v - An optional visitor. You probably should not * use this unless you have a very good reason. */ ValueArg( const std::string& flag, const std::string& name, const std::string& desc, bool req, T value, const std::string& typeDesc, Visitor* v = NULL); /** * Labeled ValueArg constructor. * You could conceivably call this constructor with a blank flag, * but that would make you a bad person. It would also cause * an exception to be thrown. If you want an unlabeled argument, * use the other constructor. * \param flag - The one character flag that identifies this * argument on the command line. * \param name - A one word name for the argument. Can be * used as a long flag on the command line. * \param desc - A description of what the argument is for or * does. * \param req - Whether the argument is required on the command * line. * \param value - The default value assigned to this argument if it * is not present on the command line. * \param typeDesc - A short, human readable description of the * type that this object expects. This is used in the generation * of the USAGE statement. The goal is to be helpful to the end user * of the program. * \param parser - A CmdLine parser object to add this Arg to * \param v - An optional visitor. You probably should not * use this unless you have a very good reason. */ ValueArg( const std::string& flag, const std::string& name, const std::string& desc, bool req, T value, const std::string& typeDesc, CmdLineInterface& parser, Visitor* v = NULL ); /** * Labeled ValueArg constructor. * You could conceivably call this constructor with a blank flag, * but that would make you a bad person. It would also cause * an exception to be thrown. If you want an unlabeled argument, * use the other constructor. * \param flag - The one character flag that identifies this * argument on the command line. * \param name - A one word name for the argument. Can be * used as a long flag on the command line. * \param desc - A description of what the argument is for or * does. * \param req - Whether the argument is required on the command * line. * \param value - The default value assigned to this argument if it * is not present on the command line. * \param constraint - A pointer to a Constraint object used * to constrain this Arg. * \param parser - A CmdLine parser object to add this Arg to. * \param v - An optional visitor. You probably should not * use this unless you have a very good reason. */ ValueArg( const std::string& flag, const std::string& name, const std::string& desc, bool req, T value, Constraint<T>* constraint, CmdLineInterface& parser, Visitor* v = NULL ); /** * Labeled ValueArg constructor. * You could conceivably call this constructor with a blank flag, * but that would make you a bad person. It would also cause * an exception to be thrown. If you want an unlabeled argument, * use the other constructor. * \param flag - The one character flag that identifies this * argument on the command line. * \param name - A one word name for the argument. Can be * used as a long flag on the command line. * \param desc - A description of what the argument is for or * does. * \param req - Whether the argument is required on the command * line. * \param value - The default value assigned to this argument if it * is not present on the command line. * \param constraint - A pointer to a Constraint object used * to constrain this Arg. * \param v - An optional visitor. You probably should not * use this unless you have a very good reason. */ ValueArg( const std::string& flag, const std::string& name, const std::string& desc, bool req, T value, Constraint<T>* constraint, Visitor* v = NULL ); /** * Handles the processing of the argument. * This re-implements the Arg version of this method to set the * _value of the argument appropriately. It knows the difference * between labeled and unlabeled. * \param i - Pointer the the current argument in the list. * \param args - Mutable list of strings. Passed * in from main(). */ virtual bool processArg(int* i, std::vector<std::string>& args); /** * Returns the value of the argument. */ T& getValue() ; /** * Specialization of shortID. * \param val - value to be used. */ virtual std::string shortID(const std::string& val = "val") const; /** * Specialization of longID. * \param val - value to be used. */ virtual std::string longID(const std::string& val = "val") const; virtual void reset() ; private: /** * Prevent accidental copying */ ValueArg<T>(const ValueArg<T>& rhs); ValueArg<T>& operator=(const ValueArg<T>& rhs); }; /** * Constructor implementation. */ template<class T> ValueArg<T>::ValueArg(const std::string& flag, const std::string& name, const std::string& desc, bool req, T val, const std::string& typeDesc, Visitor* v) : Arg(flag, name, desc, req, true, v), _value( val ), _default( val ), _typeDesc( typeDesc ), _constraint( NULL ) { } template<class T> ValueArg<T>::ValueArg(const std::string& flag, const std::string& name, const std::string& desc, bool req, T val, const std::string& typeDesc, CmdLineInterface& parser, Visitor* v) : Arg(flag, name, desc, req, true, v), _value( val ), _default( val ), _typeDesc( typeDesc ), _constraint( NULL ) { parser.add( this ); } template<class T> ValueArg<T>::ValueArg(const std::string& flag, const std::string& name, const std::string& desc, bool req, T val, Constraint<T>* constraint, Visitor* v) : Arg(flag, name, desc, req, true, v), _value( val ), _default( val ), _typeDesc( constraint->shortID() ), _constraint( constraint ) { } template<class T> ValueArg<T>::ValueArg(const std::string& flag, const std::string& name, const std::string& desc, bool req, T val, Constraint<T>* constraint, CmdLineInterface& parser, Visitor* v) : Arg(flag, name, desc, req, true, v), _value( val ), _default( val ), _typeDesc( constraint->shortID() ), _constraint( constraint ) { parser.add( this ); } /** * Implementation of getValue(). */ template<class T> T& ValueArg<T>::getValue() { return _value; } /** * Implementation of processArg(). */ template<class T> bool ValueArg<T>::processArg(int *i, std::vector<std::string>& args) { if ( _ignoreable && Arg::ignoreRest() ) return false; if ( _hasBlanks( args[*i] ) ) return false; std::string flag = args[*i]; std::string value = ""; trimFlag( flag, value ); if ( argMatches( flag ) ) { if ( _alreadySet ) { if ( _xorSet ) throw( CmdLineParseException( "Mutually exclusive argument already set!", toString()) ); else throw( CmdLineParseException("Argument already set!", toString()) ); } if ( Arg::delimiter() != ' ' && value == "" ) throw( ArgParseException( "Couldn't find delimiter for this argument!", toString() ) ); if ( value == "" ) { (*i)++; if ( static_cast<unsigned int>(*i) < args.size() ) _extractValue( args[*i] ); else throw( ArgParseException("Missing a value for this argument!", toString() ) ); } else _extractValue( value ); _alreadySet = true; _checkWithVisitor(); return true; } else return false; } /** * Implementation of shortID. */ template<class T> std::string ValueArg<T>::shortID(const std::string& val) const { static_cast<void>(val); // Ignore input, don't warn return Arg::shortID( _typeDesc ); } /** * Implementation of longID. */ template<class T> std::string ValueArg<T>::longID(const std::string& val) const { static_cast<void>(val); // Ignore input, don't warn return Arg::longID( _typeDesc ); } template<class T> void ValueArg<T>::_extractValue( const std::string& val ) { try { ExtractValue(_value, val, typename ArgTraits<T>::ValueCategory()); } catch( ArgParseException &e) { throw ArgParseException(e.error(), toString()); } if ( _constraint != NULL ) if ( ! _constraint->check( _value ) ) throw( CmdLineParseException( "Value '" + val + + "' does not meet constraint: " + _constraint->description(), toString() ) ); } template<class T> void ValueArg<T>::reset() { Arg::reset(); _value = _default; } } // namespace TCLAP #endif
13,418
30.574118
79
h
openalpr
openalpr-master/src/tclap/ValuesConstraint.h
/****************************************************************************** * * file: ValuesConstraint.h * * Copyright (c) 2005, Michael E. Smoot * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_VALUESCONSTRAINT_H #define TCLAP_VALUESCONSTRAINT_H #include <string> #include <vector> #include "Constraint.h" #ifdef HAVE_CONFIG_H #include <config.h> #else #define HAVE_SSTREAM #endif #if defined(HAVE_SSTREAM) #include <sstream> #elif defined(HAVE_STRSTREAM) #include <strstream> #else #error "Need a stringstream (sstream or strstream) to compile!" #endif namespace TCLAP { /** * A Constraint that constrains the Arg to only those values specified * in the constraint. */ template<class T> class ValuesConstraint : public Constraint<T> { public: /** * Constructor. * \param allowed - vector of allowed values. */ ValuesConstraint(std::vector<T>& allowed); /** * Virtual destructor. */ virtual ~ValuesConstraint() {} /** * Returns a description of the Constraint. */ virtual std::string description() const; /** * Returns the short ID for the Constraint. */ virtual std::string shortID() const; /** * The method used to verify that the value parsed from the command * line meets the constraint. * \param value - The value that will be checked. */ virtual bool check(const T& value) const; protected: /** * The list of valid values. */ std::vector<T> _allowed; /** * The string used to describe the allowed values of this constraint. */ std::string _typeDesc; }; template<class T> ValuesConstraint<T>::ValuesConstraint(std::vector<T>& allowed) : _allowed(allowed), _typeDesc("") { for ( unsigned int i = 0; i < _allowed.size(); i++ ) { #if defined(HAVE_SSTREAM) std::ostringstream os; #elif defined(HAVE_STRSTREAM) std::ostrstream os; #else #error "Need a stringstream (sstream or strstream) to compile!" #endif os << _allowed[i]; std::string temp( os.str() ); if ( i > 0 ) _typeDesc += "|"; _typeDesc += temp; } } template<class T> bool ValuesConstraint<T>::check( const T& val ) const { if ( std::find(_allowed.begin(),_allowed.end(),val) == _allowed.end() ) return false; else return true; } template<class T> std::string ValuesConstraint<T>::shortID() const { return _typeDesc; } template<class T> std::string ValuesConstraint<T>::description() const { return _typeDesc; } } //namespace TCLAP #endif
3,203
21.096552
79
h
openalpr
openalpr-master/src/tclap/VersionVisitor.h
// -*- Mode: c++; c-basic-offset: 4; tab-width: 4; -*- /****************************************************************************** * * file: VersionVisitor.h * * Copyright (c) 2003, Michael E. Smoot . * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_VERSION_VISITOR_H #define TCLAP_VERSION_VISITOR_H #include "CmdLineInterface.h" #include "CmdLineOutput.h" #include "Visitor.h" namespace TCLAP { /** * A Vistor that will call the version method of the given CmdLineOutput * for the specified CmdLine object and then exit. */ class VersionVisitor: public Visitor { private: /** * Prevent accidental copying */ VersionVisitor(const VersionVisitor& rhs); VersionVisitor& operator=(const VersionVisitor& rhs); protected: /** * The CmdLine of interest. */ CmdLineInterface* _cmd; /** * The output object. */ CmdLineOutput** _out; public: /** * Constructor. * \param cmd - The CmdLine the output is generated for. * \param out - The type of output. */ VersionVisitor( CmdLineInterface* cmd, CmdLineOutput** out ) : Visitor(), _cmd( cmd ), _out( out ) { } /** * Calls the version method of the output object using the * specified CmdLine. */ void visit() { (*_out)->version(*_cmd); throw ExitException(0); } }; } #endif
2,044
23.345238
79
h
openalpr
openalpr-master/src/tclap/Visitor.h
/****************************************************************************** * * file: Visitor.h * * Copyright (c) 2003, Michael E. Smoot . * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_VISITOR_H #define TCLAP_VISITOR_H namespace TCLAP { /** * A base class that defines the interface for visitors. */ class Visitor { public: /** * Constructor. Does nothing. */ Visitor() { } /** * Destructor. Does nothing. */ virtual ~Visitor() { } /** * Does nothing. Should be overridden by child. */ virtual void visit() { } }; } #endif
1,266
22.036364
79
h
openalpr
openalpr-master/src/tclap/XorHandler.h
/****************************************************************************** * * file: XorHandler.h * * Copyright (c) 2003, Michael E. Smoot . * Copyright (c) 2004, Michael E. Smoot, Daniel Aarno. * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_XORHANDLER_H #define TCLAP_XORHANDLER_H #include "Arg.h" #include <string> #include <vector> #include <algorithm> namespace TCLAP { /** * This class handles lists of Arg's that are to be XOR'd on the command * line. This is used by CmdLine and you shouldn't ever use it. */ class XorHandler { protected: /** * The list of of lists of Arg's to be or'd together. */ std::vector< std::vector<Arg*> > _orList; public: /** * Constructor. Does nothing. */ XorHandler( ) : _orList(std::vector< std::vector<Arg*> >()) {} /** * Add a list of Arg*'s that will be orred together. * \param ors - list of Arg* that will be xor'd. */ void add( std::vector<Arg*>& ors ); /** * Checks whether the specified Arg is in one of the xor lists and * if it does match one, returns the size of the xor list that the * Arg matched. If the Arg matches, then it also sets the rest of * the Arg's in the list. You shouldn't use this. * \param a - The Arg to be checked. */ int check( const Arg* a ); /** * Returns the XOR specific short usage. */ std::string shortUsage(); /** * Prints the XOR specific long usage. * \param os - Stream to print to. */ void printLongUsage(std::ostream& os); /** * Simply checks whether the Arg is contained in one of the arg * lists. * \param a - The Arg to be checked. */ bool contains( const Arg* a ); std::vector< std::vector<Arg*> >& getXorList(); }; ////////////////////////////////////////////////////////////////////// //BEGIN XOR.cpp ////////////////////////////////////////////////////////////////////// inline void XorHandler::add( std::vector<Arg*>& ors ) { _orList.push_back( ors ); } inline int XorHandler::check( const Arg* a ) { // iterate over each XOR list for ( int i = 0; static_cast<unsigned int>(i) < _orList.size(); i++ ) { // if the XOR list contains the arg.. ArgVectorIterator ait = std::find( _orList[i].begin(), _orList[i].end(), a ); if ( ait != _orList[i].end() ) { // first check to see if a mutually exclusive switch // has not already been set for ( ArgVectorIterator it = _orList[i].begin(); it != _orList[i].end(); it++ ) if ( a != (*it) && (*it)->isSet() ) throw(CmdLineParseException( "Mutually exclusive argument already set!", (*it)->toString())); // go through and set each arg that is not a for ( ArgVectorIterator it = _orList[i].begin(); it != _orList[i].end(); it++ ) if ( a != (*it) ) (*it)->xorSet(); // return the number of required args that have now been set if ( (*ait)->allowMore() ) return 0; else return static_cast<int>(_orList[i].size()); } } if ( a->isRequired() ) return 1; else return 0; } inline bool XorHandler::contains( const Arg* a ) { for ( int i = 0; static_cast<unsigned int>(i) < _orList.size(); i++ ) for ( ArgVectorIterator it = _orList[i].begin(); it != _orList[i].end(); it++ ) if ( a == (*it) ) return true; return false; } inline std::vector< std::vector<Arg*> >& XorHandler::getXorList() { return _orList; } ////////////////////////////////////////////////////////////////////// //END XOR.cpp ////////////////////////////////////////////////////////////////////// } //namespace TCLAP #endif
4,502
26.625767
79
h
openalpr
openalpr-master/src/tclap/ZshCompletionOutput.h
// -*- Mode: c++; c-basic-offset: 4; tab-width: 4; -*- /****************************************************************************** * * file: ZshCompletionOutput.h * * Copyright (c) 2006, Oliver Kiddle * All rights reverved. * * See the file COPYING in the top directory of this distribution for * more information. * * THE SOFTWARE IS PROVIDED _AS IS_, WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * *****************************************************************************/ #ifndef TCLAP_ZSHCOMPLETIONOUTPUT_H #define TCLAP_ZSHCOMPLETIONOUTPUT_H #include <string> #include <vector> #include <list> #include <iostream> #include <map> #include <tclap/CmdLineInterface.h> #include <tclap/CmdLineOutput.h> #include <tclap/XorHandler.h> #include <tclap/Arg.h> namespace TCLAP { /** * A class that generates a Zsh completion function as output from the usage() * method for the given CmdLine and its Args. */ class ZshCompletionOutput : public CmdLineOutput { public: ZshCompletionOutput(); /** * Prints the usage to stdout. Can be overridden to * produce alternative behavior. * \param c - The CmdLine object the output is generated for. */ virtual void usage(CmdLineInterface& c); /** * Prints the version to stdout. Can be overridden * to produce alternative behavior. * \param c - The CmdLine object the output is generated for. */ virtual void version(CmdLineInterface& c); /** * Prints (to stderr) an error message, short usage * Can be overridden to produce alternative behavior. * \param c - The CmdLine object the output is generated for. * \param e - The ArgException that caused the failure. */ virtual void failure(CmdLineInterface& c, ArgException& e ); protected: void basename( std::string& s ); void quoteSpecialChars( std::string& s ); std::string getMutexList( CmdLineInterface& _cmd, Arg* a ); void printOption( Arg* it, std::string mutex ); void printArg( Arg* it ); std::map<std::string, std::string> common; char theDelimiter; }; ZshCompletionOutput::ZshCompletionOutput() : common(std::map<std::string, std::string>()), theDelimiter('=') { common["host"] = "_hosts"; common["hostname"] = "_hosts"; common["file"] = "_files"; common["filename"] = "_files"; common["user"] = "_users"; common["username"] = "_users"; common["directory"] = "_directories"; common["path"] = "_directories"; common["url"] = "_urls"; } inline void ZshCompletionOutput::version(CmdLineInterface& _cmd) { std::cout << _cmd.getVersion() << std::endl; } inline void ZshCompletionOutput::usage(CmdLineInterface& _cmd ) { std::list<Arg*> argList = _cmd.getArgList(); std::string progName = _cmd.getProgramName(); std::string xversion = _cmd.getVersion(); theDelimiter = _cmd.getDelimiter(); basename(progName); std::cout << "#compdef " << progName << std::endl << std::endl << "# " << progName << " version " << _cmd.getVersion() << std::endl << std::endl << "_arguments -s -S"; for (ArgListIterator it = argList.begin(); it != argList.end(); it++) { if ( (*it)->shortID().at(0) == '<' ) printArg((*it)); else if ( (*it)->getFlag() != "-" ) printOption((*it), getMutexList(_cmd, *it)); } std::cout << std::endl; } inline void ZshCompletionOutput::failure( CmdLineInterface& _cmd, ArgException& e ) { static_cast<void>(_cmd); // unused std::cout << e.what() << std::endl; } inline void ZshCompletionOutput::quoteSpecialChars( std::string& s ) { size_t idx = s.find_last_of(':'); while ( idx != std::string::npos ) { s.insert(idx, 1, '\\'); idx = s.find_last_of(':', idx); } idx = s.find_last_of('\''); while ( idx != std::string::npos ) { s.insert(idx, "'\\'"); if (idx == 0) idx = std::string::npos; else idx = s.find_last_of('\'', --idx); } } inline void ZshCompletionOutput::basename( std::string& s ) { size_t p = s.find_last_of('/'); if ( p != std::string::npos ) { s.erase(0, p + 1); } } inline void ZshCompletionOutput::printArg(Arg* a) { static int count = 1; std::cout << " \\" << std::endl << " '"; if ( a->acceptsMultipleValues() ) std::cout << '*'; else std::cout << count++; std::cout << ':'; if ( !a->isRequired() ) std::cout << ':'; std::cout << a->getName() << ':'; std::map<std::string, std::string>::iterator compArg = common.find(a->getName()); if ( compArg != common.end() ) { std::cout << compArg->second; } else { std::cout << "_guard \"^-*\" " << a->getName(); } std::cout << '\''; } inline void ZshCompletionOutput::printOption(Arg* a, std::string mutex) { std::string flag = a->flagStartChar() + a->getFlag(); std::string name = a->nameStartString() + a->getName(); std::string desc = a->getDescription(); // remove full stop and capitalisation from description as // this is the convention for zsh function if (!desc.compare(0, 12, "(required) ")) { desc.erase(0, 12); } if (!desc.compare(0, 15, "(OR required) ")) { desc.erase(0, 15); } size_t len = desc.length(); if (len && desc.at(--len) == '.') { desc.erase(len); } if (len) { desc.replace(0, 1, 1, tolower(desc.at(0))); } std::cout << " \\" << std::endl << " '" << mutex; if ( a->getFlag().empty() ) { std::cout << name; } else { std::cout << "'{" << flag << ',' << name << "}'"; } if ( theDelimiter == '=' && a->isValueRequired() ) std::cout << "=-"; quoteSpecialChars(desc); std::cout << '[' << desc << ']'; if ( a->isValueRequired() ) { std::string arg = a->shortID(); arg.erase(0, arg.find_last_of(theDelimiter) + 1); if ( arg.at(arg.length()-1) == ']' ) arg.erase(arg.length()-1); if ( arg.at(arg.length()-1) == ']' ) { arg.erase(arg.length()-1); } if ( arg.at(0) == '<' ) { arg.erase(arg.length()-1); arg.erase(0, 1); } size_t p = arg.find('|'); if ( p != std::string::npos ) { do { arg.replace(p, 1, 1, ' '); } while ( (p = arg.find_first_of('|', p)) != std::string::npos ); quoteSpecialChars(arg); std::cout << ": :(" << arg << ')'; } else { std::cout << ':' << arg; std::map<std::string, std::string>::iterator compArg = common.find(arg); if ( compArg != common.end() ) { std::cout << ':' << compArg->second; } } } std::cout << '\''; } inline std::string ZshCompletionOutput::getMutexList( CmdLineInterface& _cmd, Arg* a) { XorHandler xorHandler = _cmd.getXorHandler(); std::vector< std::vector<Arg*> > xorList = xorHandler.getXorList(); if (a->getName() == "help" || a->getName() == "version") { return "(-)"; } std::ostringstream list; if ( a->acceptsMultipleValues() ) { list << '*'; } for ( int i = 0; static_cast<unsigned int>(i) < xorList.size(); i++ ) { for ( ArgVectorIterator it = xorList[i].begin(); it != xorList[i].end(); it++) if ( a == (*it) ) { list << '('; for ( ArgVectorIterator iu = xorList[i].begin(); iu != xorList[i].end(); iu++ ) { bool notCur = (*iu) != a; bool hasFlag = !(*iu)->getFlag().empty(); if ( iu != xorList[i].begin() && (notCur || hasFlag) ) list << ' '; if (hasFlag) list << (*iu)->flagStartChar() << (*iu)->getFlag() << ' '; if ( notCur || hasFlag ) list << (*iu)->nameStartString() << (*iu)->getName(); } list << ')'; return list.str(); } } // wasn't found in xor list if (!a->getFlag().empty()) { list << "(" << a->flagStartChar() << a->getFlag() << ' ' << a->nameStartString() << a->getName() << ')'; } return list.str(); } } //namespace TCLAP #endif
8,415
26.061093
93
h
openalpr
openalpr-master/src/video/videobuffer.h
#ifndef OPENALPR_VIDEOBUFFER_H #define OPENALPR_VIDEOBUFFER_H #include <cstdio> #include <iostream> #include <stdexcept> #include <sstream> #include <vector> #include "opencv2/highgui/highgui.hpp" #include "support/filesystem.h" #include "support/tinythread.h" #include "support/platform.h" class VideoDispatcher { public: VideoDispatcher(std::string mjpeg_url, int fps) { this->active = true; this->latestFrameNumber = -1; this->lastFrameRead = -1; this->fps = fps; this->mjpeg_url = mjpeg_url; } int getLatestFrame(cv::Mat* frame, std::vector<cv::Rect>& regionsOfInterest) { tthread::lock_guard<tthread::mutex> guard(mMutex); if (latestFrameNumber == lastFrameRead) return -1; frame->create(latestFrame.size(), latestFrame.type()); latestFrame.copyTo(*frame); this->lastFrameRead = this->latestFrameNumber; // Copy the regionsOfInterest array for (int i = 0; i < this->latestRegionsOfInterest.size(); i++) regionsOfInterest.push_back(this->latestRegionsOfInterest[i]); return this->lastFrameRead; } void setLatestFrame(cv::Mat frame) { frame.copyTo(this->latestFrame); this->latestRegionsOfInterest = calculateRegionsOfInterest(&this->latestFrame); this->latestFrameNumber++; } virtual void log_info(std::string message) { std::cout << message << std::endl; } virtual void log_error(std::string error) { std::cerr << error << std::endl; } std::vector<cv::Rect> calculateRegionsOfInterest(cv::Mat* frame) { cv::Rect rect(0, 0, frame->cols, frame->rows); std::vector<cv::Rect> rois; rois.push_back(rect); return rois; } bool active; int latestFrameNumber; int lastFrameRead; std::string mjpeg_url; int fps; tthread::mutex mMutex; private: cv::Mat latestFrame; std::vector<cv::Rect> latestRegionsOfInterest; }; class VideoBuffer { public: VideoBuffer(); virtual ~VideoBuffer(); void connect(std::string mjpeg_url, int fps); // If a new frame is available, the function sets "frame" to it and returns the frame number // If no frames are available, or the latest has already been grabbed, returns -1. // regionsOfInterest is set to a list of good regions to check for license plates. Default is one rectangle for the entire frame. int getLatestFrame(cv::Mat* frame, std::vector<cv::Rect>& regionsOfInterest); void disconnect(); protected: virtual VideoDispatcher* createDispatcher(std::string mjpeg_url, int fps); private: VideoDispatcher* dispatcher; }; #endif // OPENALPR_VIDEOBUFFER_H
2,852
22.578512
134
h
s2anet
s2anet-master/mmdet/ops/box_iou_rotated/src/box_iou_rotated.h
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved #pragma once #include <torch/extension.h> #include <torch/types.h> at::Tensor box_iou_rotated_cpu( const at::Tensor& boxes1, const at::Tensor& boxes2); #ifdef WITH_CUDA at::Tensor box_iou_rotated_cuda( const at::Tensor& boxes1, const at::Tensor& boxes2); #endif // Interface for Python // inline is needed to prevent multiple function definitions when this header is // included by different cpps inline at::Tensor box_iou_rotated( const at::Tensor& boxes1, const at::Tensor& boxes2) { assert(boxes1.device().is_cuda() == boxes2.device().is_cuda()); if (boxes1.device().is_cuda()) { #ifdef WITH_CUDA return box_iou_rotated_cuda(boxes1, boxes2); #else AT_ERROR("Not compiled with GPU support"); #endif } return box_iou_rotated_cpu(boxes1, boxes2); } PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("box_iou_rotated", &box_iou_rotated, "IoU for rotated boxes"); }
983
24.894737
80
h
s2anet
s2anet-master/mmdet/ops/box_iou_rotated/src/box_iou_rotated_utils.h
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved #pragma once #include <cassert> #include <cmath> #ifdef __CUDACC__ // Designates functions callable from the host (CPU) and the device (GPU) #define HOST_DEVICE __host__ __device__ #define HOST_DEVICE_INLINE HOST_DEVICE __forceinline__ #else #include <algorithm> #define HOST_DEVICE #define HOST_DEVICE_INLINE HOST_DEVICE inline #endif namespace { template <typename T> struct RotatedBox { T x_ctr, y_ctr, w, h, a; }; template <typename T> struct Point { T x, y; HOST_DEVICE_INLINE Point(const T& px = 0, const T& py = 0) : x(px), y(py) {} HOST_DEVICE_INLINE Point operator+(const Point& p) const { return Point(x + p.x, y + p.y); } HOST_DEVICE_INLINE Point& operator+=(const Point& p) { x += p.x; y += p.y; return *this; } HOST_DEVICE_INLINE Point operator-(const Point& p) const { return Point(x - p.x, y - p.y); } HOST_DEVICE_INLINE Point operator*(const T coeff) const { return Point(x * coeff, y * coeff); } }; template <typename T> HOST_DEVICE_INLINE T dot_2d(const Point<T>& A, const Point<T>& B) { return A.x * B.x + A.y * B.y; } template <typename T> HOST_DEVICE_INLINE T cross_2d(const Point<T>& A, const Point<T>& B) { return A.x * B.y - B.x * A.y; } template <typename T> HOST_DEVICE_INLINE void get_rotated_vertices( const RotatedBox<T>& box, Point<T> (&pts)[4]) { // M_PI / 180. == 0.01745329251 //double theta = box.a * 0.01745329251; //MODIFIED double theta = box.a; T cosTheta2 = (T)cos(theta) * 0.5f; T sinTheta2 = (T)sin(theta) * 0.5f; // y: top --> down; x: left --> right pts[0].x = box.x_ctr - sinTheta2 * box.h - cosTheta2 * box.w; pts[0].y = box.y_ctr + cosTheta2 * box.h - sinTheta2 * box.w; pts[1].x = box.x_ctr + sinTheta2 * box.h - cosTheta2 * box.w; pts[1].y = box.y_ctr - cosTheta2 * box.h - sinTheta2 * box.w; pts[2].x = 2 * box.x_ctr - pts[0].x; pts[2].y = 2 * box.y_ctr - pts[0].y; pts[3].x = 2 * box.x_ctr - pts[1].x; pts[3].y = 2 * box.y_ctr - pts[1].y; } template <typename T> HOST_DEVICE_INLINE int get_intersection_points( const Point<T> (&pts1)[4], const Point<T> (&pts2)[4], Point<T> (&intersections)[24]) { // Line vector // A line from p1 to p2 is: p1 + (p2-p1)*t, t=[0,1] Point<T> vec1[4], vec2[4]; for (int i = 0; i < 4; i++) { vec1[i] = pts1[(i + 1) % 4] - pts1[i]; vec2[i] = pts2[(i + 1) % 4] - pts2[i]; } // Line test - test all line combos for intersection int num = 0; // number of intersections for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { // Solve for 2x2 Ax=b T det = cross_2d<T>(vec2[j], vec1[i]); // This takes care of parallel lines if (fabs(det) <= 1e-14) { continue; } auto vec12 = pts2[j] - pts1[i]; T t1 = cross_2d<T>(vec2[j], vec12) / det; T t2 = cross_2d<T>(vec1[i], vec12) / det; if (t1 >= 0.0f && t1 <= 1.0f && t2 >= 0.0f && t2 <= 1.0f) { intersections[num++] = pts1[i] + vec1[i] * t1; } } } // Check for vertices of rect1 inside rect2 { const auto& AB = vec2[0]; const auto& DA = vec2[3]; auto ABdotAB = dot_2d<T>(AB, AB); auto ADdotAD = dot_2d<T>(DA, DA); for (int i = 0; i < 4; i++) { // assume ABCD is the rectangle, and P is the point to be judged // P is inside ABCD iff. P's projection on AB lies within AB // and P's projection on AD lies within AD auto AP = pts1[i] - pts2[0]; auto APdotAB = dot_2d<T>(AP, AB); auto APdotAD = -dot_2d<T>(AP, DA); if ((APdotAB >= 0) && (APdotAD >= 0) && (APdotAB <= ABdotAB) && (APdotAD <= ADdotAD)) { intersections[num++] = pts1[i]; } } } // Reverse the check - check for vertices of rect2 inside rect1 { const auto& AB = vec1[0]; const auto& DA = vec1[3]; auto ABdotAB = dot_2d<T>(AB, AB); auto ADdotAD = dot_2d<T>(DA, DA); for (int i = 0; i < 4; i++) { auto AP = pts2[i] - pts1[0]; auto APdotAB = dot_2d<T>(AP, AB); auto APdotAD = -dot_2d<T>(AP, DA); if ((APdotAB >= 0) && (APdotAD >= 0) && (APdotAB <= ABdotAB) && (APdotAD <= ADdotAD)) { intersections[num++] = pts2[i]; } } } return num; } template <typename T> HOST_DEVICE_INLINE int convex_hull_graham( const Point<T> (&p)[24], const int& num_in, Point<T> (&q)[24], bool shift_to_zero = false) { assert(num_in >= 2); // Step 1: // Find point with minimum y // if more than 1 points have the same minimum y, // pick the one with the minimum x. int t = 0; for (int i = 1; i < num_in; i++) { if (p[i].y < p[t].y || (p[i].y == p[t].y && p[i].x < p[t].x)) { t = i; } } auto& start = p[t]; // starting point // Step 2: // Subtract starting point from every points (for sorting in the next step) for (int i = 0; i < num_in; i++) { q[i] = p[i] - start; } // Swap the starting point to position 0 auto tmp = q[0]; q[0] = q[t]; q[t] = tmp; // Step 3: // Sort point 1 ~ num_in according to their relative cross-product values // (essentially sorting according to angles) // If the angles are the same, sort according to their distance to origin T dist[24]; for (int i = 0; i < num_in; i++) { dist[i] = dot_2d<T>(q[i], q[i]); } #ifdef __CUDACC__ // CUDA version // In the future, we can potentially use thrust // for sorting here to improve speed (though not guaranteed) for (int i = 1; i < num_in - 1; i++) { for (int j = i + 1; j < num_in; j++) { T crossProduct = cross_2d<T>(q[i], q[j]); if ((crossProduct < -1e-6) || (fabs(crossProduct) < 1e-6 && dist[i] > dist[j])) { auto q_tmp = q[i]; q[i] = q[j]; q[j] = q_tmp; auto dist_tmp = dist[i]; dist[i] = dist[j]; dist[j] = dist_tmp; } } } #else // CPU version std::sort( q + 1, q + num_in, [](const Point<T>& A, const Point<T>& B) -> bool { T temp = cross_2d<T>(A, B); if (fabs(temp) < 1e-6) { return dot_2d<T>(A, A) < dot_2d<T>(B, B); } else { return temp > 0; } }); #endif // Step 4: // Make sure there are at least 2 points (that don't overlap with each other) // in the stack int k; // index of the non-overlapped second point for (k = 1; k < num_in; k++) { if (dist[k] > 1e-8) { break; } } if (k == num_in) { // We reach the end, which means the convex hull is just one point q[0] = p[t]; return 1; } q[1] = q[k]; int m = 2; // 2 points in the stack // Step 5: // Finally we can start the scanning process. // When a non-convex relationship between the 3 points is found // (either concave shape or duplicated points), // we pop the previous point from the stack // until the 3-point relationship is convex again, or // until the stack only contains two points for (int i = k + 1; i < num_in; i++) { while (m > 1 && cross_2d<T>(q[i] - q[m - 2], q[m - 1] - q[m - 2]) >= 0) { m--; } q[m++] = q[i]; } // Step 6 (Optional): // In general sense we need the original coordinates, so we // need to shift the points back (reverting Step 2) // But if we're only interested in getting the area/perimeter of the shape // We can simply return. if (!shift_to_zero) { for (int i = 0; i < m; i++) { q[i] += start; } } return m; } template <typename T> HOST_DEVICE_INLINE T polygon_area(const Point<T> (&q)[24], const int& m) { if (m <= 2) { return 0; } T area = 0; for (int i = 1; i < m - 1; i++) { area += fabs(cross_2d<T>(q[i] - q[0], q[i + 1] - q[0])); } return area / 2.0; } template <typename T> HOST_DEVICE_INLINE T rotated_boxes_intersection( const RotatedBox<T>& box1, const RotatedBox<T>& box2) { // There are up to 4 x 4 + 4 + 4 = 24 intersections (including dups) returned // from rotated_rect_intersection_pts Point<T> intersectPts[24], orderedPts[24]; Point<T> pts1[4]; Point<T> pts2[4]; get_rotated_vertices<T>(box1, pts1); get_rotated_vertices<T>(box2, pts2); int num = get_intersection_points<T>(pts1, pts2, intersectPts); if (num <= 2) { return 0.0; } // Convex Hull to order the intersection points in clockwise order and find // the contour area. int num_convex = convex_hull_graham<T>(intersectPts, num, orderedPts, true); return polygon_area<T>(orderedPts, num_convex); } } // namespace template <typename T> HOST_DEVICE_INLINE T single_box_iou_rotated(T const* const box1_raw, T const* const box2_raw) { // shift center to the middle point to achieve higher precision in result RotatedBox<T> box1, box2; auto center_shift_x = (box1_raw[0] + box2_raw[0]) / 2.0; auto center_shift_y = (box1_raw[1] + box2_raw[1]) / 2.0; box1.x_ctr = box1_raw[0] - center_shift_x; box1.y_ctr = box1_raw[1] - center_shift_y; box1.w = box1_raw[2]; box1.h = box1_raw[3]; box1.a = box1_raw[4]; box2.x_ctr = box2_raw[0] - center_shift_x; box2.y_ctr = box2_raw[1] - center_shift_y; box2.w = box2_raw[2]; box2.h = box2_raw[3]; box2.a = box2_raw[4]; const T area1 = box1.w * box1.h; const T area2 = box2.w * box2.h; if (area1 < 1e-14 || area2 < 1e-14) { return 0.f; } const T intersection = rotated_boxes_intersection<T>(box1, box2); const T iou = intersection / (area1 + area2 - intersection); return iou; }
9,476
26.629738
79
h
s2anet
s2anet-master/mmdet/ops/box_iou_rotated_diff/src/cuda_utils.h
#ifndef _CUDA_UTILS_H #define _CUDA_UTILS_H #include <ATen/ATen.h> #include <ATen/cuda/CUDAContext.h> #include <cmath> #include <cuda.h> #include <cuda_runtime.h> #include <vector> #define TOTAL_THREADS 512 inline int opt_n_thread(int work_size){ const int pow_2 = std::log(static_cast<double>(work_size)) / std::log(2.0); return max(min(1<<pow_2, TOTAL_THREADS), 1); } inline dim3 opt_block_config(int x, int y){ const int x_thread = opt_n_thread(x); const int y_thread = max(min(opt_n_thread(y), TOTAL_THREADS/x_thread), 1); dim3 block_config(x_thread, y_thread, 1); return block_config; } # define CUDA_CHECK_ERRORS() \ do { \ cudaError_t err = cudaGetLastError(); \ if (cudaSuccess!=err){ \ fprintf(stderr, "CUDA kernel failed : %s\n%s at L:%d in %s\n", \ cudaGetErrorString(err), __PRETTY_FUNCTION__, __LINE__, \ __FILE__); \ exit(-1); \ } \ } while(0) \ #endif
1,409
37.108108
79
h
s2anet
s2anet-master/mmdet/ops/box_iou_rotated_diff/src/utils.h
#pragma once #include <ATen/cuda/CUDAContext.h> #include <torch/extension.h> #define CHECK_CUDA(x) \ do { \ TORCH_CHECK(x.is_cuda(), #x " must be a CUDA tensor"); \ } while (0) #define CHECK_CONTIGUOUS(x) \ do { \ TORCH_CHECK(x.is_contiguous(), #x " must ne a contiguous tensor"); \ } while (0) #define CHECK_IS_INT(x) \ do { \ TORCH_CHECK(x.scalar_type()==at::ScalarType::Int, \ #x " must be a int tensor"); \ } while (0) #define CHECK_IS_FLOAT(x) \ do { \ TORCH_CHECK(x.scalar_type()==at::ScalarType::Float, \ #x " must be a float tensor"); \ } while (0) #define CHECK_IS_BOOL(x) \ do { \ TORCH_CHECK(x.scalar_type()==at::ScalarType::Bool, \ #x " must be a bool tensor"); \ } while (0)
1,538
48.645161
82
h
s2anet
s2anet-master/mmdet/ops/ml_nms_rotated/src/box_iou_rotated_utils.h
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved #pragma once #include <cassert> #include <cmath> #ifdef __CUDACC__ // Designates functions callable from the host (CPU) and the device (GPU) #define HOST_DEVICE __host__ __device__ #define HOST_DEVICE_INLINE HOST_DEVICE __forceinline__ #else #include <algorithm> #define HOST_DEVICE #define HOST_DEVICE_INLINE HOST_DEVICE inline #endif namespace { template <typename T> struct RotatedBox { T x_ctr, y_ctr, w, h, a; }; template <typename T> struct Point { T x, y; HOST_DEVICE_INLINE Point(const T& px = 0, const T& py = 0) : x(px), y(py) {} HOST_DEVICE_INLINE Point operator+(const Point& p) const { return Point(x + p.x, y + p.y); } HOST_DEVICE_INLINE Point& operator+=(const Point& p) { x += p.x; y += p.y; return *this; } HOST_DEVICE_INLINE Point operator-(const Point& p) const { return Point(x - p.x, y - p.y); } HOST_DEVICE_INLINE Point operator*(const T coeff) const { return Point(x * coeff, y * coeff); } }; template <typename T> HOST_DEVICE_INLINE T dot_2d(const Point<T>& A, const Point<T>& B) { return A.x * B.x + A.y * B.y; } template <typename T> HOST_DEVICE_INLINE T cross_2d(const Point<T>& A, const Point<T>& B) { return A.x * B.y - B.x * A.y; } template <typename T> HOST_DEVICE_INLINE void get_rotated_vertices( const RotatedBox<T>& box, Point<T> (&pts)[4]) { // M_PI / 180. == 0.01745329251 //double theta = box.a * 0.01745329251; //MODIFIED double theta = box.a; T cosTheta2 = (T)cos(theta) * 0.5f; T sinTheta2 = (T)sin(theta) * 0.5f; // y: top --> down; x: left --> right pts[0].x = box.x_ctr - sinTheta2 * box.h - cosTheta2 * box.w; pts[0].y = box.y_ctr + cosTheta2 * box.h - sinTheta2 * box.w; pts[1].x = box.x_ctr + sinTheta2 * box.h - cosTheta2 * box.w; pts[1].y = box.y_ctr - cosTheta2 * box.h - sinTheta2 * box.w; pts[2].x = 2 * box.x_ctr - pts[0].x; pts[2].y = 2 * box.y_ctr - pts[0].y; pts[3].x = 2 * box.x_ctr - pts[1].x; pts[3].y = 2 * box.y_ctr - pts[1].y; } template <typename T> HOST_DEVICE_INLINE int get_intersection_points( const Point<T> (&pts1)[4], const Point<T> (&pts2)[4], Point<T> (&intersections)[24]) { // Line vector // A line from p1 to p2 is: p1 + (p2-p1)*t, t=[0,1] Point<T> vec1[4], vec2[4]; for (int i = 0; i < 4; i++) { vec1[i] = pts1[(i + 1) % 4] - pts1[i]; vec2[i] = pts2[(i + 1) % 4] - pts2[i]; } // Line test - test all line combos for intersection int num = 0; // number of intersections for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { // Solve for 2x2 Ax=b T det = cross_2d<T>(vec2[j], vec1[i]); // This takes care of parallel lines if (fabs(det) <= 1e-14) { continue; } auto vec12 = pts2[j] - pts1[i]; T t1 = cross_2d<T>(vec2[j], vec12) / det; T t2 = cross_2d<T>(vec1[i], vec12) / det; if (t1 >= 0.0f && t1 <= 1.0f && t2 >= 0.0f && t2 <= 1.0f) { intersections[num++] = pts1[i] + vec1[i] * t1; } } } // Check for vertices of rect1 inside rect2 { const auto& AB = vec2[0]; const auto& DA = vec2[3]; auto ABdotAB = dot_2d<T>(AB, AB); auto ADdotAD = dot_2d<T>(DA, DA); for (int i = 0; i < 4; i++) { // assume ABCD is the rectangle, and P is the point to be judged // P is inside ABCD iff. P's projection on AB lies within AB // and P's projection on AD lies within AD auto AP = pts1[i] - pts2[0]; auto APdotAB = dot_2d<T>(AP, AB); auto APdotAD = -dot_2d<T>(AP, DA); if ((APdotAB >= 0) && (APdotAD >= 0) && (APdotAB <= ABdotAB) && (APdotAD <= ADdotAD)) { intersections[num++] = pts1[i]; } } } // Reverse the check - check for vertices of rect2 inside rect1 { const auto& AB = vec1[0]; const auto& DA = vec1[3]; auto ABdotAB = dot_2d<T>(AB, AB); auto ADdotAD = dot_2d<T>(DA, DA); for (int i = 0; i < 4; i++) { auto AP = pts2[i] - pts1[0]; auto APdotAB = dot_2d<T>(AP, AB); auto APdotAD = -dot_2d<T>(AP, DA); if ((APdotAB >= 0) && (APdotAD >= 0) && (APdotAB <= ABdotAB) && (APdotAD <= ADdotAD)) { intersections[num++] = pts2[i]; } } } return num; } template <typename T> HOST_DEVICE_INLINE int convex_hull_graham( const Point<T> (&p)[24], const int& num_in, Point<T> (&q)[24], bool shift_to_zero = false) { assert(num_in >= 2); // Step 1: // Find point with minimum y // if more than 1 points have the same minimum y, // pick the one with the minimum x. int t = 0; for (int i = 1; i < num_in; i++) { if (p[i].y < p[t].y || (p[i].y == p[t].y && p[i].x < p[t].x)) { t = i; } } auto& start = p[t]; // starting point // Step 2: // Subtract starting point from every points (for sorting in the next step) for (int i = 0; i < num_in; i++) { q[i] = p[i] - start; } // Swap the starting point to position 0 auto tmp = q[0]; q[0] = q[t]; q[t] = tmp; // Step 3: // Sort point 1 ~ num_in according to their relative cross-product values // (essentially sorting according to angles) // If the angles are the same, sort according to their distance to origin T dist[24]; for (int i = 0; i < num_in; i++) { dist[i] = dot_2d<T>(q[i], q[i]); } #ifdef __CUDACC__ // CUDA version // In the future, we can potentially use thrust // for sorting here to improve speed (though not guaranteed) for (int i = 1; i < num_in - 1; i++) { for (int j = i + 1; j < num_in; j++) { T crossProduct = cross_2d<T>(q[i], q[j]); if ((crossProduct < -1e-6) || (fabs(crossProduct) < 1e-6 && dist[i] > dist[j])) { auto q_tmp = q[i]; q[i] = q[j]; q[j] = q_tmp; auto dist_tmp = dist[i]; dist[i] = dist[j]; dist[j] = dist_tmp; } } } #else // CPU version std::sort( q + 1, q + num_in, [](const Point<T>& A, const Point<T>& B) -> bool { T temp = cross_2d<T>(A, B); if (fabs(temp) < 1e-6) { return dot_2d<T>(A, A) < dot_2d<T>(B, B); } else { return temp > 0; } }); #endif // Step 4: // Make sure there are at least 2 points (that don't overlap with each other) // in the stack int k; // index of the non-overlapped second point for (k = 1; k < num_in; k++) { if (dist[k] > 1e-8) { break; } } if (k == num_in) { // We reach the end, which means the convex hull is just one point q[0] = p[t]; return 1; } q[1] = q[k]; int m = 2; // 2 points in the stack // Step 5: // Finally we can start the scanning process. // When a non-convex relationship between the 3 points is found // (either concave shape or duplicated points), // we pop the previous point from the stack // until the 3-point relationship is convex again, or // until the stack only contains two points for (int i = k + 1; i < num_in; i++) { while (m > 1 && cross_2d<T>(q[i] - q[m - 2], q[m - 1] - q[m - 2]) >= 0) { m--; } q[m++] = q[i]; } // Step 6 (Optional): // In general sense we need the original coordinates, so we // need to shift the points back (reverting Step 2) // But if we're only interested in getting the area/perimeter of the shape // We can simply return. if (!shift_to_zero) { for (int i = 0; i < m; i++) { q[i] += start; } } return m; } template <typename T> HOST_DEVICE_INLINE T polygon_area(const Point<T> (&q)[24], const int& m) { if (m <= 2) { return 0; } T area = 0; for (int i = 1; i < m - 1; i++) { area += fabs(cross_2d<T>(q[i] - q[0], q[i + 1] - q[0])); } return area / 2.0; } template <typename T> HOST_DEVICE_INLINE T rotated_boxes_intersection( const RotatedBox<T>& box1, const RotatedBox<T>& box2) { // There are up to 4 x 4 + 4 + 4 = 24 intersections (including dups) returned // from rotated_rect_intersection_pts Point<T> intersectPts[24], orderedPts[24]; Point<T> pts1[4]; Point<T> pts2[4]; get_rotated_vertices<T>(box1, pts1); get_rotated_vertices<T>(box2, pts2); int num = get_intersection_points<T>(pts1, pts2, intersectPts); if (num <= 2) { return 0.0; } // Convex Hull to order the intersection points in clockwise order and find // the contour area. int num_convex = convex_hull_graham<T>(intersectPts, num, orderedPts, true); return polygon_area<T>(orderedPts, num_convex); } } // namespace template <typename T> HOST_DEVICE_INLINE T single_box_iou_rotated(T const* const box1_raw, T const* const box2_raw) { // we dont calculate IoU if two bboxes belong to two classes and set it to zero // box: [x,y,w,h,a,l] if (box1_raw[5] != box2_raw[5]) { return 0.0; } // shift center to the middle point to achieve higher precision in result RotatedBox<T> box1, box2; auto center_shift_x = (box1_raw[0] + box2_raw[0]) / 2.0; auto center_shift_y = (box1_raw[1] + box2_raw[1]) / 2.0; box1.x_ctr = box1_raw[0] - center_shift_x; box1.y_ctr = box1_raw[1] - center_shift_y; box1.w = box1_raw[2]; box1.h = box1_raw[3]; box1.a = box1_raw[4]; box2.x_ctr = box2_raw[0] - center_shift_x; box2.y_ctr = box2_raw[1] - center_shift_y; box2.w = box2_raw[2]; box2.h = box2_raw[3]; box2.a = box2_raw[4]; const T area1 = box1.w * box1.h; const T area2 = box2.w * box2.h; if (area1 < 1e-14 || area2 < 1e-14) { return 0.f; } const T intersection = rotated_boxes_intersection<T>(box1, box2); const T iou = intersection / (area1 + area2 - intersection); return iou; }
9,640
26.624642
81
h
s2anet
s2anet-master/mmdet/ops/ml_nms_rotated/src/nms_rotated.h
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved #pragma once #include <torch/extension.h> #include <torch/types.h> at::Tensor nms_rotated_cpu( const at::Tensor& dets, const at::Tensor& scores, const at::Tensor& labels, const float iou_threshold); #ifdef WITH_CUDA at::Tensor nms_rotated_cuda( const at::Tensor& dets, const at::Tensor& scores, const at::Tensor& labels, const float iou_threshold); #endif // Interface for Python // inline is needed to prevent multiple function definitions when this header is // included by different cpps inline at::Tensor nms_rotated( const at::Tensor& dets, const at::Tensor& scores, const at::Tensor& labels, const float iou_threshold) { assert(dets.device().is_cuda() == scores.device().is_cuda()); if (dets.device().is_cuda()) { #ifdef WITH_CUDA return nms_rotated_cuda(dets, scores, labels, iou_threshold); #else AT_ERROR("Not compiled with GPU support"); #endif } return nms_rotated_cpu(dets, scores, labels, iou_threshold); } PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("ml_nms_rotated", &nms_rotated, "multi label NMS for rotated boxes"); }
1,186
25.377778
80
h
s2anet
s2anet-master/mmdet/ops/nms_rotated/src/box_iou_rotated_utils.h
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved #pragma once #include <cassert> #include <cmath> #ifdef __CUDACC__ // Designates functions callable from the host (CPU) and the device (GPU) #define HOST_DEVICE __host__ __device__ #define HOST_DEVICE_INLINE HOST_DEVICE __forceinline__ #else #include <algorithm> #define HOST_DEVICE #define HOST_DEVICE_INLINE HOST_DEVICE inline #endif namespace { template <typename T> struct RotatedBox { T x_ctr, y_ctr, w, h, a; }; template <typename T> struct Point { T x, y; HOST_DEVICE_INLINE Point(const T& px = 0, const T& py = 0) : x(px), y(py) {} HOST_DEVICE_INLINE Point operator+(const Point& p) const { return Point(x + p.x, y + p.y); } HOST_DEVICE_INLINE Point& operator+=(const Point& p) { x += p.x; y += p.y; return *this; } HOST_DEVICE_INLINE Point operator-(const Point& p) const { return Point(x - p.x, y - p.y); } HOST_DEVICE_INLINE Point operator*(const T coeff) const { return Point(x * coeff, y * coeff); } }; template <typename T> HOST_DEVICE_INLINE T dot_2d(const Point<T>& A, const Point<T>& B) { return A.x * B.x + A.y * B.y; } template <typename T> HOST_DEVICE_INLINE T cross_2d(const Point<T>& A, const Point<T>& B) { return A.x * B.y - B.x * A.y; } template <typename T> HOST_DEVICE_INLINE void get_rotated_vertices( const RotatedBox<T>& box, Point<T> (&pts)[4]) { // M_PI / 180. == 0.01745329251 //double theta = box.a * 0.01745329251; //MODIFIED double theta = box.a; T cosTheta2 = (T)cos(theta) * 0.5f; T sinTheta2 = (T)sin(theta) * 0.5f; // y: top --> down; x: left --> right pts[0].x = box.x_ctr - sinTheta2 * box.h - cosTheta2 * box.w; pts[0].y = box.y_ctr + cosTheta2 * box.h - sinTheta2 * box.w; pts[1].x = box.x_ctr + sinTheta2 * box.h - cosTheta2 * box.w; pts[1].y = box.y_ctr - cosTheta2 * box.h - sinTheta2 * box.w; pts[2].x = 2 * box.x_ctr - pts[0].x; pts[2].y = 2 * box.y_ctr - pts[0].y; pts[3].x = 2 * box.x_ctr - pts[1].x; pts[3].y = 2 * box.y_ctr - pts[1].y; } template <typename T> HOST_DEVICE_INLINE int get_intersection_points( const Point<T> (&pts1)[4], const Point<T> (&pts2)[4], Point<T> (&intersections)[24]) { // Line vector // A line from p1 to p2 is: p1 + (p2-p1)*t, t=[0,1] Point<T> vec1[4], vec2[4]; for (int i = 0; i < 4; i++) { vec1[i] = pts1[(i + 1) % 4] - pts1[i]; vec2[i] = pts2[(i + 1) % 4] - pts2[i]; } // Line test - test all line combos for intersection int num = 0; // number of intersections for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { // Solve for 2x2 Ax=b T det = cross_2d<T>(vec2[j], vec1[i]); // This takes care of parallel lines if (fabs(det) <= 1e-14) { continue; } auto vec12 = pts2[j] - pts1[i]; T t1 = cross_2d<T>(vec2[j], vec12) / det; T t2 = cross_2d<T>(vec1[i], vec12) / det; if (t1 >= 0.0f && t1 <= 1.0f && t2 >= 0.0f && t2 <= 1.0f) { intersections[num++] = pts1[i] + vec1[i] * t1; } } } // Check for vertices of rect1 inside rect2 { const auto& AB = vec2[0]; const auto& DA = vec2[3]; auto ABdotAB = dot_2d<T>(AB, AB); auto ADdotAD = dot_2d<T>(DA, DA); for (int i = 0; i < 4; i++) { // assume ABCD is the rectangle, and P is the point to be judged // P is inside ABCD iff. P's projection on AB lies within AB // and P's projection on AD lies within AD auto AP = pts1[i] - pts2[0]; auto APdotAB = dot_2d<T>(AP, AB); auto APdotAD = -dot_2d<T>(AP, DA); if ((APdotAB >= 0) && (APdotAD >= 0) && (APdotAB <= ABdotAB) && (APdotAD <= ADdotAD)) { intersections[num++] = pts1[i]; } } } // Reverse the check - check for vertices of rect2 inside rect1 { const auto& AB = vec1[0]; const auto& DA = vec1[3]; auto ABdotAB = dot_2d<T>(AB, AB); auto ADdotAD = dot_2d<T>(DA, DA); for (int i = 0; i < 4; i++) { auto AP = pts2[i] - pts1[0]; auto APdotAB = dot_2d<T>(AP, AB); auto APdotAD = -dot_2d<T>(AP, DA); if ((APdotAB >= 0) && (APdotAD >= 0) && (APdotAB <= ABdotAB) && (APdotAD <= ADdotAD)) { intersections[num++] = pts2[i]; } } } return num; } template <typename T> HOST_DEVICE_INLINE int convex_hull_graham( const Point<T> (&p)[24], const int& num_in, Point<T> (&q)[24], bool shift_to_zero = false) { assert(num_in >= 2); // Step 1: // Find point with minimum y // if more than 1 points have the same minimum y, // pick the one with the minimum x. int t = 0; for (int i = 1; i < num_in; i++) { if (p[i].y < p[t].y || (p[i].y == p[t].y && p[i].x < p[t].x)) { t = i; } } auto& start = p[t]; // starting point // Step 2: // Subtract starting point from every points (for sorting in the next step) for (int i = 0; i < num_in; i++) { q[i] = p[i] - start; } // Swap the starting point to position 0 auto tmp = q[0]; q[0] = q[t]; q[t] = tmp; // Step 3: // Sort point 1 ~ num_in according to their relative cross-product values // (essentially sorting according to angles) // If the angles are the same, sort according to their distance to origin T dist[24]; for (int i = 0; i < num_in; i++) { dist[i] = dot_2d<T>(q[i], q[i]); } #ifdef __CUDACC__ // CUDA version // In the future, we can potentially use thrust // for sorting here to improve speed (though not guaranteed) for (int i = 1; i < num_in - 1; i++) { for (int j = i + 1; j < num_in; j++) { T crossProduct = cross_2d<T>(q[i], q[j]); if ((crossProduct < -1e-6) || (fabs(crossProduct) < 1e-6 && dist[i] > dist[j])) { auto q_tmp = q[i]; q[i] = q[j]; q[j] = q_tmp; auto dist_tmp = dist[i]; dist[i] = dist[j]; dist[j] = dist_tmp; } } } #else // CPU version std::sort( q + 1, q + num_in, [](const Point<T>& A, const Point<T>& B) -> bool { T temp = cross_2d<T>(A, B); if (fabs(temp) < 1e-6) { return dot_2d<T>(A, A) < dot_2d<T>(B, B); } else { return temp > 0; } }); #endif // Step 4: // Make sure there are at least 2 points (that don't overlap with each other) // in the stack int k; // index of the non-overlapped second point for (k = 1; k < num_in; k++) { if (dist[k] > 1e-8) { break; } } if (k == num_in) { // We reach the end, which means the convex hull is just one point q[0] = p[t]; return 1; } q[1] = q[k]; int m = 2; // 2 points in the stack // Step 5: // Finally we can start the scanning process. // When a non-convex relationship between the 3 points is found // (either concave shape or duplicated points), // we pop the previous point from the stack // until the 3-point relationship is convex again, or // until the stack only contains two points for (int i = k + 1; i < num_in; i++) { while (m > 1 && cross_2d<T>(q[i] - q[m - 2], q[m - 1] - q[m - 2]) >= 0) { m--; } q[m++] = q[i]; } // Step 6 (Optional): // In general sense we need the original coordinates, so we // need to shift the points back (reverting Step 2) // But if we're only interested in getting the area/perimeter of the shape // We can simply return. if (!shift_to_zero) { for (int i = 0; i < m; i++) { q[i] += start; } } return m; } template <typename T> HOST_DEVICE_INLINE T polygon_area(const Point<T> (&q)[24], const int& m) { if (m <= 2) { return 0; } T area = 0; for (int i = 1; i < m - 1; i++) { area += fabs(cross_2d<T>(q[i] - q[0], q[i + 1] - q[0])); } return area / 2.0; } template <typename T> HOST_DEVICE_INLINE T rotated_boxes_intersection( const RotatedBox<T>& box1, const RotatedBox<T>& box2) { // There are up to 4 x 4 + 4 + 4 = 24 intersections (including dups) returned // from rotated_rect_intersection_pts Point<T> intersectPts[24], orderedPts[24]; Point<T> pts1[4]; Point<T> pts2[4]; get_rotated_vertices<T>(box1, pts1); get_rotated_vertices<T>(box2, pts2); int num = get_intersection_points<T>(pts1, pts2, intersectPts); if (num <= 2) { return 0.0; } // Convex Hull to order the intersection points in clockwise order and find // the contour area. int num_convex = convex_hull_graham<T>(intersectPts, num, orderedPts, true); return polygon_area<T>(orderedPts, num_convex); } } // namespace template <typename T> HOST_DEVICE_INLINE T single_box_iou_rotated(T const* const box1_raw, T const* const box2_raw) { // shift center to the middle point to achieve higher precision in result RotatedBox<T> box1, box2; auto center_shift_x = (box1_raw[0] + box2_raw[0]) / 2.0; auto center_shift_y = (box1_raw[1] + box2_raw[1]) / 2.0; box1.x_ctr = box1_raw[0] - center_shift_x; box1.y_ctr = box1_raw[1] - center_shift_y; box1.w = box1_raw[2]; box1.h = box1_raw[3]; box1.a = box1_raw[4]; box2.x_ctr = box2_raw[0] - center_shift_x; box2.y_ctr = box2_raw[1] - center_shift_y; box2.w = box2_raw[2]; box2.h = box2_raw[3]; box2.a = box2_raw[4]; const T area1 = box1.w * box1.h; const T area2 = box2.w * box2.h; if (area1 < 1e-14 || area2 < 1e-14) { return 0.f; } const T intersection = rotated_boxes_intersection<T>(box1, box2); const T iou = intersection / (area1 + area2 - intersection); return iou; }
9,476
26.629738
79
h
s2anet
s2anet-master/mmdet/ops/nms_rotated/src/nms_rotated.h
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved #pragma once #include <torch/extension.h> #include <torch/types.h> at::Tensor nms_rotated_cpu( const at::Tensor& dets, const at::Tensor& scores, const float iou_threshold); #ifdef WITH_CUDA at::Tensor nms_rotated_cuda( const at::Tensor& dets, const at::Tensor& scores, const float iou_threshold); #endif // Interface for Python // inline is needed to prevent multiple function definitions when this header is // included by different cpps inline at::Tensor nms_rotated( const at::Tensor& dets, const at::Tensor& scores, const float iou_threshold) { assert(dets.device().is_cuda() == scores.device().is_cuda()); if (dets.device().is_cuda()) { #ifdef WITH_CUDA return nms_rotated_cuda(dets, scores, iou_threshold); #else AT_ERROR("Not compiled with GPU support"); #endif } return nms_rotated_cpu(dets, scores, iou_threshold); } PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("nms_rotated", &nms_rotated, "NMS for rotated boxes"); }
1,065
24.380952
80
h
s2anet
s2anet-master/mmdet/ops/orn/src/ActiveRotatingFilter.h
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. #pragma once #include "./cpu/vision.h" #ifdef WITH_CUDA #include "./cuda/vision.h" #endif // Interface for Python at::Tensor ARF_forward(const at::Tensor& weight, const at::Tensor& indices) { if (weight.type().is_cuda()) { #ifdef WITH_CUDA return ARF_forward_cuda(weight, indices); #else AT_ERROR("Not compiled with GPU support"); #endif } return ARF_forward_cpu(weight, indices); } at::Tensor ARF_backward(const at::Tensor& indices, const at::Tensor& gradOutput) { if (gradOutput.type().is_cuda()) { #ifdef WITH_CUDA return ARF_backward_cuda(indices, gradOutput); #else AT_ERROR("Not compiled with GPU support"); #endif } return ARF_backward_cpu(indices, gradOutput); AT_ERROR("Not implemented on the CPU"); }
856
24.205882
72
h
s2anet
s2anet-master/mmdet/ops/orn/src/RotationInvariantEncoding.h
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. #pragma once #include "./cpu/vision.h" #ifdef WITH_CUDA #include "./cuda/vision.h" #endif // Interface for Python std::tuple<at::Tensor, at::Tensor> RIE_forward(const at::Tensor& feature, const uint8 nOrientation) { if (feature.type().is_cuda()) { #ifdef WITH_CUDA return RIE_forward_cuda(feature, nOrientation); #else AT_ERROR("Not compiled with GPU support"); #endif } return RIE_forward_cpu(feature, nOrientation); } at::Tensor RIE_backward(const at::Tensor& mainDirection, const at::Tensor& gradOutput, const uint8 nOrientation) { if (gradOutput.type().is_cuda()) { #ifdef WITH_CUDA return RIE_backward_cuda(mainDirection, gradOutput, nOrientation); #else AT_ERROR("Not compiled with GPU support"); #endif } return RIE_backward_cpu(mainDirection, gradOutput, nOrientation); AT_ERROR("Not implemented on the CPU"); }
1,013
27.971429
74
h
s2anet
s2anet-master/mmdet/ops/orn/src/cpu/vision.h
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. #pragma once // #include <torch/extension.h> #include <torch/serialize/tensor.h> typedef unsigned long uint64; typedef unsigned int uint32; typedef unsigned short uint16; typedef unsigned char uint8; std::tuple<at::Tensor, at::Tensor> RIE_forward_cpu(const at::Tensor& feature, const uint8 nOrientation); at::Tensor RIE_backward_cpu(const at::Tensor& mainDirection, const at::Tensor& gradOutput, const uint8 nOrientation); at::Tensor ARF_forward_cpu(const at::Tensor& weight, const at::Tensor& indices); at::Tensor ARF_backward_cpu(const at::Tensor& indices, const at::Tensor& gradOutput);
830
35.130435
77
h
s2anet
s2anet-master/mmdet/ops/orn/src/cuda/vision.h
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. #pragma once // #include <torch/extension.h> #include <torch/serialize/tensor.h> typedef unsigned long uint64; typedef unsigned int uint32; typedef unsigned short uint16; typedef unsigned char uint8; std::tuple<at::Tensor, at::Tensor> RIE_forward_cuda(const at::Tensor& feature, const uint8 nOrientation); at::Tensor RIE_backward_cuda(const at::Tensor& mainDirection, const at::Tensor& gradOutput, const uint8 nOrientation); at::Tensor ARF_forward_cuda(const at::Tensor& weight, const at::Tensor& indices); at::Tensor ARF_backward_cuda(const at::Tensor& indices, const at::Tensor& gradOutput);
839
35.521739
78
h
s2anet
s2anet-master/mmdet/ops/roi_align_rotated/src/ROIAlignRotated.h
// Copyright (c) Facebook, Inc. and its affiliates. #pragma once #include <torch/extension.h> #include <torch/types.h> at::Tensor ROIAlignRotated_forward_cpu( const at::Tensor& input, const at::Tensor& rois, const float spatial_scale, const int pooled_height, const int pooled_width, const int sampling_ratio); at::Tensor ROIAlignRotated_backward_cpu( const at::Tensor& grad, const at::Tensor& rois, const float spatial_scale, const int pooled_height, const int pooled_width, const int batch_size, const int channels, const int height, const int width, const int sampling_ratio); #if defined(WITH_CUDA) || defined(WITH_HIP) at::Tensor ROIAlignRotated_forward_cuda( const at::Tensor& input, const at::Tensor& rois, const float spatial_scale, const int pooled_height, const int pooled_width, const int sampling_ratio); at::Tensor ROIAlignRotated_backward_cuda( const at::Tensor& grad, const at::Tensor& rois, const float spatial_scale, const int pooled_height, const int pooled_width, const int batch_size, const int channels, const int height, const int width, const int sampling_ratio); #endif // Interface for Python inline at::Tensor ROIAlignRotated_forward( const at::Tensor& input, const at::Tensor& rois, const float spatial_scale, const int pooled_height, const int pooled_width, const int sampling_ratio) { if (input.is_cuda()) { #if defined(WITH_CUDA) || defined(WITH_HIP) return ROIAlignRotated_forward_cuda( input, rois, spatial_scale, pooled_height, pooled_width, sampling_ratio); #else AT_ERROR("Not compiled with GPU support"); #endif } return ROIAlignRotated_forward_cpu( input, rois, spatial_scale, pooled_height, pooled_width, sampling_ratio); } inline at::Tensor ROIAlignRotated_backward( const at::Tensor& grad, const at::Tensor& rois, const float spatial_scale, const int pooled_height, const int pooled_width, const int batch_size, const int channels, const int height, const int width, const int sampling_ratio) { if (grad.is_cuda()) { #if defined(WITH_CUDA) || defined(WITH_HIP) return ROIAlignRotated_backward_cuda( grad, rois, spatial_scale, pooled_height, pooled_width, batch_size, channels, height, width, sampling_ratio); #else AT_ERROR("Not compiled with GPU support"); #endif } return ROIAlignRotated_backward_cpu( grad, rois, spatial_scale, pooled_height, pooled_width, batch_size, channels, height, width, sampling_ratio); } PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def( "roi_align_rotated_forward", &ROIAlignRotated_forward, "Forward pass for Rotated ROI-Align Operator"); m.def( "roi_align_rotated_backward", &ROIAlignRotated_backward, "Backward pass for Rotated ROI-Align Operator"); }
3,088
23.322835
79
h
null
CHPDet-main/cocoapi/common/gason.h
// https://github.com/vivkin/gason - pulled January 10, 2016 #pragma once #include <stdint.h> #include <stddef.h> #include <assert.h> enum JsonTag { JSON_NUMBER = 0, JSON_STRING, JSON_ARRAY, JSON_OBJECT, JSON_TRUE, JSON_FALSE, JSON_NULL = 0xF }; struct JsonNode; #define JSON_VALUE_PAYLOAD_MASK 0x00007FFFFFFFFFFFULL #define JSON_VALUE_NAN_MASK 0x7FF8000000000000ULL #define JSON_VALUE_TAG_MASK 0xF #define JSON_VALUE_TAG_SHIFT 47 union JsonValue { uint64_t ival; double fval; JsonValue(double x) : fval(x) { } JsonValue(JsonTag tag = JSON_NULL, void *payload = nullptr) { assert((uintptr_t)payload <= JSON_VALUE_PAYLOAD_MASK); ival = JSON_VALUE_NAN_MASK | ((uint64_t)tag << JSON_VALUE_TAG_SHIFT) | (uintptr_t)payload; } bool isDouble() const { return (int64_t)ival <= (int64_t)JSON_VALUE_NAN_MASK; } JsonTag getTag() const { return isDouble() ? JSON_NUMBER : JsonTag((ival >> JSON_VALUE_TAG_SHIFT) & JSON_VALUE_TAG_MASK); } uint64_t getPayload() const { assert(!isDouble()); return ival & JSON_VALUE_PAYLOAD_MASK; } double toNumber() const { assert(getTag() == JSON_NUMBER); return fval; } char *toString() const { assert(getTag() == JSON_STRING); return (char *)getPayload(); } JsonNode *toNode() const { assert(getTag() == JSON_ARRAY || getTag() == JSON_OBJECT); return (JsonNode *)getPayload(); } }; struct JsonNode { JsonValue value; JsonNode *next; char *key; }; struct JsonIterator { JsonNode *p; void operator++() { p = p->next; } bool operator!=(const JsonIterator &x) const { return p != x.p; } JsonNode *operator*() const { return p; } JsonNode *operator->() const { return p; } }; inline JsonIterator begin(JsonValue o) { return JsonIterator{o.toNode()}; } inline JsonIterator end(JsonValue) { return JsonIterator{nullptr}; } #define JSON_ERRNO_MAP(XX) \ XX(OK, "ok") \ XX(BAD_NUMBER, "bad number") \ XX(BAD_STRING, "bad string") \ XX(BAD_IDENTIFIER, "bad identifier") \ XX(STACK_OVERFLOW, "stack overflow") \ XX(STACK_UNDERFLOW, "stack underflow") \ XX(MISMATCH_BRACKET, "mismatch bracket") \ XX(UNEXPECTED_CHARACTER, "unexpected character") \ XX(UNQUOTED_KEY, "unquoted key") \ XX(BREAKING_BAD, "breaking bad") \ XX(ALLOCATION_FAILURE, "allocation failure") enum JsonErrno { #define XX(no, str) JSON_##no, JSON_ERRNO_MAP(XX) #undef XX }; const char *jsonStrError(int err); class JsonAllocator { struct Zone { Zone *next; size_t used; } *head = nullptr; public: JsonAllocator() = default; JsonAllocator(const JsonAllocator &) = delete; JsonAllocator &operator=(const JsonAllocator &) = delete; JsonAllocator(JsonAllocator &&x) : head(x.head) { x.head = nullptr; } JsonAllocator &operator=(JsonAllocator &&x) { head = x.head; x.head = nullptr; return *this; } ~JsonAllocator() { deallocate(); } void *allocate(size_t size); void deallocate(); }; int jsonParse(char *str, char **endptr, JsonValue *value, JsonAllocator &allocator);
3,483
24.430657
104
h
null
CHPDet-main/cocoapi/common/maskApi.c
/************************************************************************** * Microsoft COCO Toolbox. version 2.0 * Data, paper, and tutorials available at: http://mscoco.org/ * Code written by Piotr Dollar and Tsung-Yi Lin, 2015. * Licensed under the Simplified BSD License [see coco/license.txt] **************************************************************************/ #include "maskApi.h" #include <math.h> #include <stdlib.h> uint umin( uint a, uint b ) { return (a<b) ? a : b; } uint umax( uint a, uint b ) { return (a>b) ? a : b; } void rleInit( RLE *R, siz h, siz w, siz m, uint *cnts ) { R->h=h; R->w=w; R->m=m; R->cnts=(m==0)?0:malloc(sizeof(uint)*m); siz j; if(cnts) for(j=0; j<m; j++) R->cnts[j]=cnts[j]; } void rleFree( RLE *R ) { free(R->cnts); R->cnts=0; } void rlesInit( RLE **R, siz n ) { siz i; *R = (RLE*) malloc(sizeof(RLE)*n); for(i=0; i<n; i++) rleInit((*R)+i,0,0,0,0); } void rlesFree( RLE **R, siz n ) { siz i; for(i=0; i<n; i++) rleFree((*R)+i); free(*R); *R=0; } void rleEncode( RLE *R, const byte *M, siz h, siz w, siz n ) { siz i, j, k, a=w*h; uint c, *cnts; byte p; cnts = malloc(sizeof(uint)*(a+1)); for(i=0; i<n; i++) { const byte *T=M+a*i; k=0; p=0; c=0; for(j=0; j<a; j++) { if(T[j]!=p) { cnts[k++]=c; c=0; p=T[j]; } c++; } cnts[k++]=c; rleInit(R+i,h,w,k,cnts); } free(cnts); } void rleDecode( const RLE *R, byte *M, siz n ) { siz i, j, k; for( i=0; i<n; i++ ) { byte v=0; for( j=0; j<R[i].m; j++ ) { for( k=0; k<R[i].cnts[j]; k++ ) *(M++)=v; v=!v; }} } void rleMerge( const RLE *R, RLE *M, siz n, int intersect ) { uint *cnts, c, ca, cb, cc, ct; int v, va, vb, vp; siz i, a, b, h=R[0].h, w=R[0].w, m=R[0].m; RLE A, B; if(n==0) { rleInit(M,0,0,0,0); return; } if(n==1) { rleInit(M,h,w,m,R[0].cnts); return; } cnts = malloc(sizeof(uint)*(h*w+1)); for( a=0; a<m; a++ ) cnts[a]=R[0].cnts[a]; for( i=1; i<n; i++ ) { B=R[i]; if(B.h!=h||B.w!=w) { h=w=m=0; break; } rleInit(&A,h,w,m,cnts); ca=A.cnts[0]; cb=B.cnts[0]; v=va=vb=0; m=0; a=b=1; cc=0; ct=1; while( ct>0 ) { c=umin(ca,cb); cc+=c; ct=0; ca-=c; if(!ca && a<A.m) { ca=A.cnts[a++]; va=!va; } ct+=ca; cb-=c; if(!cb && b<B.m) { cb=B.cnts[b++]; vb=!vb; } ct+=cb; vp=v; if(intersect) v=va&&vb; else v=va||vb; if( v!=vp||ct==0 ) { cnts[m++]=cc; cc=0; } } rleFree(&A); } rleInit(M,h,w,m,cnts); free(cnts); } void rleArea( const RLE *R, siz n, uint *a ) { siz i, j; for( i=0; i<n; i++ ) { a[i]=0; for( j=1; j<R[i].m; j+=2 ) a[i]+=R[i].cnts[j]; } } void rleIou( RLE *dt, RLE *gt, siz m, siz n, byte *iscrowd, double *o ) { siz g, d; BB db, gb; int crowd; db=malloc(sizeof(double)*m*4); rleToBbox(dt,db,m); gb=malloc(sizeof(double)*n*4); rleToBbox(gt,gb,n); bbIou(db,gb,m,n,iscrowd,o); free(db); free(gb); for( g=0; g<n; g++ ) for( d=0; d<m; d++ ) if(o[g*m+d]>0) { crowd=iscrowd!=NULL && iscrowd[g]; if(dt[d].h!=gt[g].h || dt[d].w!=gt[g].w) { o[g*m+d]=-1; continue; } siz ka, kb, a, b; uint c, ca, cb, ct, i, u; int va, vb; ca=dt[d].cnts[0]; ka=dt[d].m; va=vb=0; cb=gt[g].cnts[0]; kb=gt[g].m; a=b=1; i=u=0; ct=1; while( ct>0 ) { c=umin(ca,cb); if(va||vb) { u+=c; if(va&&vb) i+=c; } ct=0; ca-=c; if(!ca && a<ka) { ca=dt[d].cnts[a++]; va=!va; } ct+=ca; cb-=c; if(!cb && b<kb) { cb=gt[g].cnts[b++]; vb=!vb; } ct+=cb; } if(i==0) u=1; else if(crowd) rleArea(dt+d,1,&u); o[g*m+d] = (double)i/(double)u; } } void rleNms( RLE *dt, siz n, uint *keep, double thr ) { siz i, j; double u; for( i=0; i<n; i++ ) keep[i]=1; for( i=0; i<n; i++ ) if(keep[i]) { for( j=i+1; j<n; j++ ) if(keep[j]) { rleIou(dt+i,dt+j,1,1,0,&u); if(u>thr) keep[j]=0; } } } void bbIou( BB dt, BB gt, siz m, siz n, byte *iscrowd, double *o ) { double h, w, i, u, ga, da; siz g, d; int crowd; for( g=0; g<n; g++ ) { BB G=gt+g*4; ga=G[2]*G[3]; crowd=iscrowd!=NULL && iscrowd[g]; for( d=0; d<m; d++ ) { BB D=dt+d*4; da=D[2]*D[3]; o[g*m+d]=0; w=fmin(D[2]+D[0],G[2]+G[0])-fmax(D[0],G[0]); if(w<=0) continue; h=fmin(D[3]+D[1],G[3]+G[1])-fmax(D[1],G[1]); if(h<=0) continue; i=w*h; u = crowd ? da : da+ga-i; o[g*m+d]=i/u; } } } void bbNms( BB dt, siz n, uint *keep, double thr ) { siz i, j; double u; for( i=0; i<n; i++ ) keep[i]=1; for( i=0; i<n; i++ ) if(keep[i]) { for( j=i+1; j<n; j++ ) if(keep[j]) { bbIou(dt+i*4,dt+j*4,1,1,0,&u); if(u>thr) keep[j]=0; } } } void rleToBbox( const RLE *R, BB bb, siz n ) { siz i; for( i=0; i<n; i++ ) { uint h, w, x, y, xs, ys, xe, ye, xp, cc, t; siz j, m; h=(uint)R[i].h; w=(uint)R[i].w; m=R[i].m; m=((siz)(m/2))*2; xs=w; ys=h; xe=ye=0; cc=0; if(m==0) { bb[4*i+0]=bb[4*i+1]=bb[4*i+2]=bb[4*i+3]=0; continue; } for( j=0; j<m; j++ ) { cc+=R[i].cnts[j]; t=cc-j%2; y=t%h; x=(t-y)/h; if(j%2==0) xp=x; else if(xp<x) { ys=0; ye=h-1; } xs=umin(xs,x); xe=umax(xe,x); ys=umin(ys,y); ye=umax(ye,y); } bb[4*i+0]=xs; bb[4*i+2]=xe-xs+1; bb[4*i+1]=ys; bb[4*i+3]=ye-ys+1; } } void rleFrBbox( RLE *R, const BB bb, siz h, siz w, siz n ) { siz i; for( i=0; i<n; i++ ) { double xs=bb[4*i+0], xe=xs+bb[4*i+2]; double ys=bb[4*i+1], ye=ys+bb[4*i+3]; double xy[8] = {xs,ys,xs,ye,xe,ye,xe,ys}; rleFrPoly( R+i, xy, 4, h, w ); } } int uintCompare(const void *a, const void *b) { uint c=*((uint*)a), d=*((uint*)b); return c>d?1:c<d?-1:0; } void rleFrPoly( RLE *R, const double *xy, siz k, siz h, siz w ) { /* upsample and get discrete points densely along entire boundary */ siz j, m=0; double scale=5; int *x, *y, *u, *v; uint *a, *b; x=malloc(sizeof(int)*(k+1)); y=malloc(sizeof(int)*(k+1)); for(j=0; j<k; j++) x[j]=(int)(scale*xy[j*2+0]+.5); x[k]=x[0]; for(j=0; j<k; j++) y[j]=(int)(scale*xy[j*2+1]+.5); y[k]=y[0]; for(j=0; j<k; j++) m+=umax(abs(x[j]-x[j+1]),abs(y[j]-y[j+1]))+1; u=malloc(sizeof(int)*m); v=malloc(sizeof(int)*m); m=0; for( j=0; j<k; j++ ) { int xs=x[j], xe=x[j+1], ys=y[j], ye=y[j+1], dx, dy, t, d; int flip; double s; dx=abs(xe-xs); dy=abs(ys-ye); flip = (dx>=dy && xs>xe) || (dx<dy && ys>ye); if(flip) { t=xs; xs=xe; xe=t; t=ys; ys=ye; ye=t; } s = dx>=dy ? (double)(ye-ys)/dx : (double)(xe-xs)/dy; if(dx>=dy) for( d=0; d<=dx; d++ ) { t=flip?dx-d:d; u[m]=t+xs; v[m]=(int)(ys+s*t+.5); m++; } else for( d=0; d<=dy; d++ ) { t=flip?dy-d:d; v[m]=t+ys; u[m]=(int)(xs+s*t+.5); m++; } } /* get points along y-boundary and downsample */ free(x); free(y); k=m; m=0; double xd, yd; x=malloc(sizeof(int)*k); y=malloc(sizeof(int)*k); for( j=1; j<k; j++ ) if(u[j]!=u[j-1]) { xd=(double)(u[j]<u[j-1]?u[j]:u[j]-1); xd=(xd+.5)/scale-.5; if( floor(xd)!=xd || xd<0 || xd>w-1 ) continue; yd=(double)(v[j]<v[j-1]?v[j]:v[j-1]); yd=(yd+.5)/scale-.5; if(yd<0) yd=0; else if(yd>h) yd=h; yd=ceil(yd); x[m]=(int) xd; y[m]=(int) yd; m++; } /* compute rle encoding given y-boundary points */ k=m; a=malloc(sizeof(uint)*(k+1)); for( j=0; j<k; j++ ) a[j]=(uint)(x[j]*(int)(h)+y[j]); a[k++]=(uint)(h*w); free(u); free(v); free(x); free(y); qsort(a,k,sizeof(uint),uintCompare); uint p=0; for( j=0; j<k; j++ ) { uint t=a[j]; a[j]-=p; p=t; } b=malloc(sizeof(uint)*k); j=m=0; b[m++]=a[j++]; while(j<k) if(a[j]>0) b[m++]=a[j++]; else { j++; if(j<k) b[m-1]+=a[j++]; } rleInit(R,h,w,m,b); free(a); free(b); } char* rleToString( const RLE *R ) { /* Similar to LEB128 but using 6 bits/char and ascii chars 48-111. */ siz i, m=R->m, p=0; long x; int more; char *s=malloc(sizeof(char)*m*6); for( i=0; i<m; i++ ) { x=(long) R->cnts[i]; if(i>2) x-=(long) R->cnts[i-2]; more=1; while( more ) { char c=x & 0x1f; x >>= 5; more=(c & 0x10) ? x!=-1 : x!=0; if(more) c |= 0x20; c+=48; s[p++]=c; } } s[p]=0; return s; } void rleFrString( RLE *R, char *s, siz h, siz w ) { siz m=0, p=0, k; long x; int more; uint *cnts; while( s[m] ) m++; cnts=malloc(sizeof(uint)*m); m=0; while( s[p] ) { x=0; k=0; more=1; while( more ) { char c=s[p]-48; x |= (c & 0x1f) << 5*k; more = c & 0x20; p++; k++; if(!more && (c & 0x10)) x |= -1 << 5*k; } if(m>2) x+=(long) cnts[m-2]; cnts[m++]=(uint) x; } rleInit(R,h,w,m,cnts); free(cnts); }
8,308
34.814655
75
c
null
CHPDet-main/cocoapi/common/maskApi.h
/************************************************************************** * Microsoft COCO Toolbox. version 2.0 * Data, paper, and tutorials available at: http://mscoco.org/ * Code written by Piotr Dollar and Tsung-Yi Lin, 2015. * Licensed under the Simplified BSD License [see coco/license.txt] **************************************************************************/ #pragma once typedef unsigned int uint; typedef unsigned long siz; typedef unsigned char byte; typedef double* BB; typedef struct { siz h, w, m; uint *cnts; } RLE; /* Initialize/destroy RLE. */ void rleInit( RLE *R, siz h, siz w, siz m, uint *cnts ); void rleFree( RLE *R ); /* Initialize/destroy RLE array. */ void rlesInit( RLE **R, siz n ); void rlesFree( RLE **R, siz n ); /* Encode binary masks using RLE. */ void rleEncode( RLE *R, const byte *mask, siz h, siz w, siz n ); /* Decode binary masks encoded via RLE. */ void rleDecode( const RLE *R, byte *mask, siz n ); /* Compute union or intersection of encoded masks. */ void rleMerge( const RLE *R, RLE *M, siz n, int intersect ); /* Compute area of encoded masks. */ void rleArea( const RLE *R, siz n, uint *a ); /* Compute intersection over union between masks. */ void rleIou( RLE *dt, RLE *gt, siz m, siz n, byte *iscrowd, double *o ); /* Compute non-maximum suppression between bounding masks */ void rleNms( RLE *dt, siz n, uint *keep, double thr ); /* Compute intersection over union between bounding boxes. */ void bbIou( BB dt, BB gt, siz m, siz n, byte *iscrowd, double *o ); /* Compute non-maximum suppression between bounding boxes */ void bbNms( BB dt, siz n, uint *keep, double thr ); /* Get bounding boxes surrounding encoded masks. */ void rleToBbox( const RLE *R, BB bb, siz n ); /* Convert bounding boxes to encoded masks. */ void rleFrBbox( RLE *R, const BB bb, siz h, siz w, siz n ); /* Convert polygon to encoded mask. */ void rleFrPoly( RLE *R, const double *xy, siz k, siz h, siz w ); /* Get compressed string representation of encoded mask. */ char* rleToString( const RLE *R ); /* Convert from compressed string representation of encoded mask. */ void rleFrString( RLE *R, char *s, siz h, siz w );
2,176
34.688525
75
h
null
CHPDet-main/src/lib/models/networks/DCNv2/src/dcn_v2.h
#pragma once #include "cpu/vision.h" #ifdef WITH_CUDA #include "cuda/vision.h" #endif at::Tensor dcn_v2_forward(const at::Tensor &input, const at::Tensor &weight, const at::Tensor &bias, const at::Tensor &offset, const at::Tensor &mask, const int kernel_h, const int kernel_w, const int stride_h, const int stride_w, const int pad_h, const int pad_w, const int dilation_h, const int dilation_w, const int deformable_group) { if (input.type().is_cuda()) { #ifdef WITH_CUDA return dcn_v2_cuda_forward(input, weight, bias, offset, mask, kernel_h, kernel_w, stride_h, stride_w, pad_h, pad_w, dilation_h, dilation_w, deformable_group); #else AT_ERROR("Not compiled with GPU support"); #endif } AT_ERROR("Not implemented on the CPU"); } std::vector<at::Tensor> dcn_v2_backward(const at::Tensor &input, const at::Tensor &weight, const at::Tensor &bias, const at::Tensor &offset, const at::Tensor &mask, const at::Tensor &grad_output, int kernel_h, int kernel_w, int stride_h, int stride_w, int pad_h, int pad_w, int dilation_h, int dilation_w, int deformable_group) { if (input.type().is_cuda()) { #ifdef WITH_CUDA return dcn_v2_cuda_backward(input, weight, bias, offset, mask, grad_output, kernel_h, kernel_w, stride_h, stride_w, pad_h, pad_w, dilation_h, dilation_w, deformable_group); #else AT_ERROR("Not compiled with GPU support"); #endif } AT_ERROR("Not implemented on the CPU"); } std::tuple<at::Tensor, at::Tensor> dcn_v2_psroi_pooling_forward(const at::Tensor &input, const at::Tensor &bbox, const at::Tensor &trans, const int no_trans, const float spatial_scale, const int output_dim, const int group_size, const int pooled_size, const int part_size, const int sample_per_part, const float trans_std) { if (input.type().is_cuda()) { #ifdef WITH_CUDA return dcn_v2_psroi_pooling_cuda_forward(input, bbox, trans, no_trans, spatial_scale, output_dim, group_size, pooled_size, part_size, sample_per_part, trans_std); #else AT_ERROR("Not compiled with GPU support"); #endif } AT_ERROR("Not implemented on the CPU"); } std::tuple<at::Tensor, at::Tensor> dcn_v2_psroi_pooling_backward(const at::Tensor &out_grad, const at::Tensor &input, const at::Tensor &bbox, const at::Tensor &trans, const at::Tensor &top_count, const int no_trans, const float spatial_scale, const int output_dim, const int group_size, const int pooled_size, const int part_size, const int sample_per_part, const float trans_std) { if (input.type().is_cuda()) { #ifdef WITH_CUDA return dcn_v2_psroi_pooling_cuda_backward(out_grad, input, bbox, trans, top_count, no_trans, spatial_scale, output_dim, group_size, pooled_size, part_size, sample_per_part, trans_std); #else AT_ERROR("Not compiled with GPU support"); #endif } AT_ERROR("Not implemented on the CPU"); }
5,494
36.896552
69
h
null
CHPDet-main/src/lib/models/networks/DCNv2/src/cpu/vision.h
#pragma once #include <torch/extension.h> at::Tensor dcn_v2_cpu_forward(const at::Tensor &input, const at::Tensor &weight, const at::Tensor &bias, const at::Tensor &offset, const at::Tensor &mask, const int kernel_h, const int kernel_w, const int stride_h, const int stride_w, const int pad_h, const int pad_w, const int dilation_h, const int dilation_w, const int deformable_group); std::vector<at::Tensor> dcn_v2_cpu_backward(const at::Tensor &input, const at::Tensor &weight, const at::Tensor &bias, const at::Tensor &offset, const at::Tensor &mask, const at::Tensor &grad_output, int kernel_h, int kernel_w, int stride_h, int stride_w, int pad_h, int pad_w, int dilation_h, int dilation_w, int deformable_group); std::tuple<at::Tensor, at::Tensor> dcn_v2_psroi_pooling_cpu_forward(const at::Tensor &input, const at::Tensor &bbox, const at::Tensor &trans, const int no_trans, const float spatial_scale, const int output_dim, const int group_size, const int pooled_size, const int part_size, const int sample_per_part, const float trans_std); std::tuple<at::Tensor, at::Tensor> dcn_v2_psroi_pooling_cpu_backward(const at::Tensor &out_grad, const at::Tensor &input, const at::Tensor &bbox, const at::Tensor &trans, const at::Tensor &top_count, const int no_trans, const float spatial_scale, const int output_dim, const int group_size, const int pooled_size, const int part_size, const int sample_per_part, const float trans_std);
2,665
43.433333
63
h
null
CHPDet-main/src/lib/models/networks/DCNv2/src/cuda/vision.h
#pragma once #include <torch/extension.h> at::Tensor dcn_v2_cuda_forward(const at::Tensor &input, const at::Tensor &weight, const at::Tensor &bias, const at::Tensor &offset, const at::Tensor &mask, const int kernel_h, const int kernel_w, const int stride_h, const int stride_w, const int pad_h, const int pad_w, const int dilation_h, const int dilation_w, const int deformable_group); std::vector<at::Tensor> dcn_v2_cuda_backward(const at::Tensor &input, const at::Tensor &weight, const at::Tensor &bias, const at::Tensor &offset, const at::Tensor &mask, const at::Tensor &grad_output, int kernel_h, int kernel_w, int stride_h, int stride_w, int pad_h, int pad_w, int dilation_h, int dilation_w, int deformable_group); std::tuple<at::Tensor, at::Tensor> dcn_v2_psroi_pooling_cuda_forward(const at::Tensor &input, const at::Tensor &bbox, const at::Tensor &trans, const int no_trans, const float spatial_scale, const int output_dim, const int group_size, const int pooled_size, const int part_size, const int sample_per_part, const float trans_std); std::tuple<at::Tensor, at::Tensor> dcn_v2_psroi_pooling_cuda_backward(const at::Tensor &out_grad, const at::Tensor &input, const at::Tensor &bbox, const at::Tensor &trans, const at::Tensor &top_count, const int no_trans, const float spatial_scale, const int output_dim, const int group_size, const int pooled_size, const int part_size, const int sample_per_part, const float trans_std);
2,669
43.5
63
h
null
CHPDet-main/src/lib/models/networks/orn/csrc/ActiveRotatingFilter.h
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. #pragma once #include "cpu/vision.h" #ifdef WITH_CUDA #include "cuda/vision.h" #endif // Interface for Python at::Tensor ARF_forward(const at::Tensor& weight, const at::Tensor& indices) { if (weight.type().is_cuda()) { #ifdef WITH_CUDA return ARF_forward_cuda(weight, indices); #else AT_ERROR("Not compiled with GPU support"); #endif } return ARF_forward_cpu(weight, indices); } at::Tensor ARF_backward(const at::Tensor& indices, const at::Tensor& gradOutput) { if (gradOutput.type().is_cuda()) { #ifdef WITH_CUDA return ARF_backward_cuda(indices, gradOutput); #else AT_ERROR("Not compiled with GPU support"); #endif } return ARF_backward_cpu(indices, gradOutput); AT_ERROR("Not implemented on the CPU"); }
852
24.088235
72
h
null
CHPDet-main/src/lib/models/networks/orn/csrc/RotationInvariantEncoding.h
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. #pragma once #include "cpu/vision.h" #ifdef WITH_CUDA #include "cuda/vision.h" #endif // Interface for Python std::tuple<at::Tensor, at::Tensor> RIE_forward(const at::Tensor& feature, const uint8 nOrientation) { if (feature.type().is_cuda()) { #ifdef WITH_CUDA return RIE_forward_cuda(feature, nOrientation); #else AT_ERROR("Not compiled with GPU support"); #endif } return RIE_forward_cpu(feature, nOrientation); } at::Tensor RIE_backward(const at::Tensor& mainDirection, const at::Tensor& gradOutput, const uint8 nOrientation) { if (gradOutput.type().is_cuda()) { #ifdef WITH_CUDA return RIE_backward_cuda(mainDirection, gradOutput, nOrientation); #else AT_ERROR("Not compiled with GPU support"); #endif } return RIE_backward_cpu(mainDirection, gradOutput, nOrientation); AT_ERROR("Not implemented on the CPU"); }
1,009
27.857143
74
h
null
CHPDet-main/src/lib/models/networks/orn/csrc/cpu/vision.h
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. #pragma once // #include <torch/extension.h> #include <torch/serialize/tensor.h> typedef unsigned long uint64; typedef unsigned int uint32; typedef unsigned short uint16; typedef unsigned char uint8; std::tuple<at::Tensor, at::Tensor> RIE_forward_cpu(const at::Tensor& feature, const uint8 nOrientation); at::Tensor RIE_backward_cpu(const at::Tensor& mainDirection, const at::Tensor& gradOutput, const uint8 nOrientation); at::Tensor ARF_forward_cpu(const at::Tensor& weight, const at::Tensor& indices); at::Tensor ARF_backward_cpu(const at::Tensor& indices, const at::Tensor& gradOutput);
830
35.130435
77
h
null
CHPDet-main/src/lib/models/networks/orn/csrc/cuda/vision.h
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. #pragma once // #include <torch/extension.h> #include <torch/serialize/tensor.h> typedef unsigned long uint64; typedef unsigned int uint32; typedef unsigned short uint16; typedef unsigned char uint8; std::tuple<at::Tensor, at::Tensor> RIE_forward_cuda(const at::Tensor& feature, const uint8 nOrientation); at::Tensor RIE_backward_cuda(const at::Tensor& mainDirection, const at::Tensor& gradOutput, const uint8 nOrientation); at::Tensor ARF_forward_cuda(const at::Tensor& weight, const at::Tensor& indices); at::Tensor ARF_backward_cuda(const at::Tensor& indices, const at::Tensor& gradOutput);
839
35.521739
78
h
gvisor
gvisor-master/images/basic/integrationtest/host_connect.c
// Copyright 2022 The gVisor 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 <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> int main(int argc, char** argv) { int fd; struct sockaddr_un addr; char buff[10]; if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) { perror("socket"); exit(1); } memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; strcpy(addr.sun_path, argv[1]); if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) { perror("connect"); exit(1); } strcpy(buff, "Hello"); if (send(fd, buff, strlen(buff) + 1, 0) == -1) { perror("send"); exit(1); } close(fd); exit(0); }
1,226
24.5625
75
c
gvisor
gvisor-master/images/basic/integrationtest/host_fd.c
// Copyright 2021 The gVisor 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 <err.h> #include <errno.h> #include <getopt.h> #include <stddef.h> #include <stdio.h> #include <sys/epoll.h> #include <sys/ioctl.h> #include <sys/select.h> #include <unistd.h> // Flag to indicate that TTY is being used in the container. static int tty = 0; // Tests that FIONREAD is supported with host FD. void testFionread() { int size = 0; if (ioctl(STDOUT_FILENO, FIONREAD, &size) < 0) { err(1, "ioctl(stdin, FIONREAD)"); } if (size != 0) { err(1, "FIONREAD wrong size, want: 0, got: %d", size); } } // Docker maps stdin to /dev/null which doesn't support epoll. Check that error // is correctly propagated. void testEpoll() { if (tty) { // stdin is not /dev/null when TTY is used for the container. return; } int fd = epoll_create(1); if (fd < 0) { err(1, "epoll_create"); } struct epoll_event event; event.events = EPOLLIN; event.data.u64 = 123; int res = epoll_ctl(fd, EPOLL_CTL_ADD, 0, &event); if (res != -1) { err(1, "epoll_ctl(EPOLL_CTL_ADD, stdin) should have failed"); } if (errno != EPERM) { err(1, "epoll_ctl(EPOLL_CTL_ADD, stdin) should have returned EPERM"); } } // Docker maps stdin to /dev/null. Check that select(2) works with stdin. void testSelect() { fd_set rfds; struct timeval tv; int res; FD_ZERO(&rfds); FD_SET(0, &rfds); tv.tv_sec = 0; tv.tv_usec = 1; res = select(1, &rfds, NULL, NULL, &tv); if (res == -1) { err(1, "select(1, [STDIN], NULL, NULL) returned error"); } } int main(int argc, char** argv) { int opt; while ((opt = getopt(argc, argv, "t")) != -1) { switch (opt) { case 't': tty = 1; break; default: fprintf(stderr, "Usage: %s [-t]\n", argv[0]); return 1; } } testFionread(); testEpoll(); testSelect(); return 0; }
2,422
24.239583
79
c
gvisor
gvisor-master/images/basic/integrationtest/link_test.c
// Copyright 2020 The gVisor 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 <err.h> #include <fcntl.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> // Basic test for linkat(2). Syscall tests requires CAP_DAC_READ_SEARCH and it // cannot use tricks like userns as root. For this reason, run a basic link test // to ensure some coverage. int main(int argc, char** argv) { const char kOldPath[] = "old.txt"; int fd = open(kOldPath, O_RDWR | O_CREAT | O_TRUNC, 0600); if (fd < 0) { errx(1, "open(%s) failed", kOldPath); } const char kData[] = "some random content"; if (write(fd, kData, sizeof(kData)) < 0) { err(1, "write failed"); } close(fd); struct stat old_stat; if (stat(kOldPath, &old_stat)) { errx(1, "stat(%s) failed", kOldPath); } const char kNewPath[] = "new.txt"; if (link(kOldPath, kNewPath)) { errx(1, "link(%s, %s) failed", kOldPath, kNewPath); } struct stat new_stat; if (stat(kNewPath, &new_stat)) { errx(1, "stat(%s) failed", kNewPath); } // Check that files are the same. if (old_stat.st_dev != new_stat.st_dev) { errx(1, "files st_dev is different, want: %lu, got: %lu", old_stat.st_dev, new_stat.st_dev); } if (old_stat.st_ino != new_stat.st_ino) { errx(1, "files st_ino is different, want: %lu, got: %lu", old_stat.st_ino, new_stat.st_ino); } // Check that link count is correct. if (new_stat.st_nlink != old_stat.st_nlink + 1) { errx(1, "wrong nlink, want: %lu, got: %lu", old_stat.st_nlink + 1, new_stat.st_nlink); } // Check taht contents are the same. fd = open(kNewPath, O_RDONLY); if (fd < 0) { errx(1, "open(%s) failed", kNewPath); } char buf[sizeof(kData)] = {}; if (read(fd, buf, sizeof(buf)) < 0) { err(1, "read failed"); } close(fd); if (strcmp(buf, kData) != 0) { errx(1, "file content mismatch: %s", buf); } // Cleanup. if (unlink(kNewPath)) { errx(1, "unlink(%s) failed", kNewPath); } if (unlink(kOldPath)) { errx(1, "unlink(%s) failed", kOldPath); } // Success! return 0; }
2,650
27.202128
80
c
gvisor
gvisor-master/images/basic/integrationtest/test_copy_up.c
#include <err.h> #include <fcntl.h> #include <stdio.h> #include <string.h> #include <sys/mman.h> #include <unistd.h> int main(int argc, char** argv) { const char kTestFilePath[] = "copy_up_testfile.txt"; const char kOldFileData[] = "old data\n"; const char kNewFileData[] = "new data\n"; const size_t kPageSize = sysconf(_SC_PAGE_SIZE); // Open a file that already exists in a host overlayfs lower layer. const int fd_rdonly = open(kTestFilePath, O_RDONLY); if (fd_rdonly < 0) { err(1, "open(%s, O_RDONLY)", kTestFilePath); } // Check that the file's initial contents are what we expect when read via // syscall. char oldbuf[sizeof(kOldFileData)] = {}; ssize_t n = pread(fd_rdonly, oldbuf, sizeof(oldbuf), 0); if (n < 0) { err(1, "initial pread"); } if (n != strlen(kOldFileData)) { errx(1, "short initial pread (%ld/%lu bytes)", n, strlen(kOldFileData)); } if (strcmp(oldbuf, kOldFileData) != 0) { errx(1, "initial pread returned wrong data: %s", oldbuf); } // Check that the file's initial contents are what we expect when read via // memory mapping. void* page = mmap(NULL, kPageSize, PROT_READ, MAP_SHARED, fd_rdonly, 0); if (page == MAP_FAILED) { err(1, "mmap"); } if (strcmp(page, kOldFileData) != 0) { errx(1, "mapping contains wrong initial data: %s", (const char*)page); } // Open the same file writably, causing host overlayfs to copy it up, and // replace its contents. const int fd_rdwr = open(kTestFilePath, O_RDWR); if (fd_rdwr < 0) { err(1, "open(%s, O_RDWR)", kTestFilePath); } n = write(fd_rdwr, kNewFileData, strlen(kNewFileData)); if (n < 0) { err(1, "write"); } if (n != strlen(kNewFileData)) { errx(1, "short write (%ld/%lu bytes)", n, strlen(kNewFileData)); } if (ftruncate(fd_rdwr, strlen(kNewFileData)) < 0) { err(1, "truncate"); } int failed = 0; // Check that syscalls on the old FD return updated contents. (Before Linux // 4.18, this requires that runsc use a post-copy-up FD to service the read.) char newbuf[sizeof(kNewFileData)] = {}; n = pread(fd_rdonly, newbuf, sizeof(newbuf), 0); if (n < 0) { err(1, "final pread"); } if (n != strlen(kNewFileData)) { warnx("short final pread (%ld/%lu bytes)", n, strlen(kNewFileData)); failed = 1; } else if (strcmp(newbuf, kNewFileData) != 0) { warnx("final pread returned wrong data: %s", newbuf); failed = 1; } // Check that the memory mapping of the old FD has been updated. (Linux // overlayfs does not do this, so regardless of kernel version this requires // that runsc replace existing memory mappings with mappings of a // post-copy-up FD.) if (strcmp(page, kNewFileData) != 0) { warnx("mapping contains wrong final data: %s", (const char*)page); failed = 1; } return failed; }
2,841
30.932584
79
c
gvisor
gvisor-master/images/basic/integrationtest/test_rewinddir.c
#include <dirent.h> #include <err.h> #include <errno.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> int main(int argc, char** argv) { const char kDirPath[] = "rewinddir_test_dir"; const char kFileBasename[] = "rewinddir_test_file"; // Create the test directory. if (mkdir(kDirPath, 0755) < 0) { err(1, "mkdir(%s)", kDirPath); } // The test directory should initially be empty. DIR* dir = opendir(kDirPath); if (!dir) { err(1, "opendir(%s)", kDirPath); } int failed = 0; while (1) { errno = 0; struct dirent* d = readdir(dir); if (!d) { if (errno != 0) { err(1, "readdir"); } break; } if (strcmp(d->d_name, ".") != 0 && strcmp(d->d_name, "..") != 0) { warnx("unexpected file %s in new directory", d->d_name); failed = 1; } } // Create a file in the test directory. char* file_path = malloc(strlen(kDirPath) + 1 + strlen(kFileBasename)); if (!file_path) { errx(1, "malloc"); } strcpy(file_path, kDirPath); file_path[strlen(kDirPath)] = '/'; strcpy(file_path + strlen(kDirPath) + 1, kFileBasename); if (mknod(file_path, 0644, 0) < 0) { err(1, "mknod(%s)", file_path); } // After rewinddir(), re-reading the directory stream should yield the new // file. rewinddir(dir); size_t found_file = 0; while (1) { errno = 0; struct dirent* d = readdir(dir); if (!d) { if (errno != 0) { err(1, "readdir"); } break; } if (strcmp(d->d_name, kFileBasename) == 0) { found_file++; } else if (strcmp(d->d_name, ".") != 0 && strcmp(d->d_name, "..") != 0) { warnx("unexpected file %s in new directory", d->d_name); failed = 1; } } if (found_file != 1) { warnx("readdir returned file %s %zu times, wanted 1", kFileBasename, found_file); failed = 1; } return failed; }
1,921
23.329114
77
c
gvisor
gvisor-master/images/basic/integrationtest/test_sticky.c
#include <err.h> #include <errno.h> #include <fcntl.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> void createFile(const char* path) { int fd = open(path, O_WRONLY | O_CREAT, 0777); if (fd < 0) { err(1, "open(%s)", path); exit(1); } else { close(fd); } } void waitAndCheckStatus(pid_t child) { int status; if (waitpid(child, &status, 0) == -1) { err(1, "waitpid() failed"); exit(1); } if (WIFEXITED(status)) { int es = WEXITSTATUS(status); if (es) { err(1, "child exit status %d", es); exit(1); } } else { err(1, "child did not exit normally"); exit(1); } } void deleteFile(uid_t user, const char* path) { pid_t child = fork(); if (child == 0) { if (setuid(user)) { err(1, "setuid(%d)", user); exit(1); } if (unlink(path)) { err(1, "unlink(%s)", path); exit(1); } exit(0); } waitAndCheckStatus(child); } int main(int argc, char** argv) { const char kUser1Dir[] = "/user1dir"; const char kUser2File[] = "/user1dir/user2file"; const char kUser2File2[] = "/user1dir/user2file2"; const uid_t user1 = 6666; const uid_t user2 = 6667; if (mkdir(kUser1Dir, 0755) != 0) { err(1, "mkdir(%s)", kUser1Dir); exit(1); } // Enable sticky bit for user1dir. if (chmod(kUser1Dir, 01777) != 0) { err(1, "chmod(%s)", kUser1Dir); exit(1); } createFile(kUser2File); createFile(kUser2File2); if (chown(kUser1Dir, user1, getegid())) { err(1, "chown(%s)", kUser1Dir); exit(1); } if (chown(kUser2File, user2, getegid())) { err(1, "chown(%s)", kUser2File); exit(1); } if (chown(kUser2File2, user2, getegid())) { err(1, "chown(%s)", kUser2File2); exit(1); } // User1 should be able to delete any file inside user1dir, even files of // other users due to the sticky bit. deleteFile(user1, kUser2File); // User2 should naturally be able to delete its own file even if the file is // inside a sticky dir owned by someone else. deleteFile(user2, kUser2File2); }
2,116
20.824742
78
c
gvisor
gvisor-master/images/benchmarks/syscallbench/syscallbench.c
// Copyright 2022 The gVisor 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 <getopt.h> #include <stdio.h> #include <stdlib.h> #include <sys/syscall.h> #include <unistd.h> static int loops = 10000000; enum syscall_type { get_pid, get_pid_opt }; #ifdef __x86_64__ #define SYSNO_STR1(x) #x #define SYSNO_STR(x) SYSNO_STR1(x) void do_getpidopt() { __asm__("movl $" SYSNO_STR(SYS_getpid) ", %%eax\n" "syscall\n" : : : "rax", "rcx", "r11"); } #endif static void show_usage(const char *cmd) { fprintf(stderr, "Usage: %s [options]\n" "-l, --loops <num>\t\t Number of syscall loops, default 10000000\n" "-s, --syscall <num>\t\tSyscall to run (default getpid)\n" "\tOptions:\n" "\t%d) getpid\n" "\t%d) getpidopt\n", cmd, get_pid, get_pid_opt); } int main(int argc, char *argv[]) { int i, c, sys_val = get_pid; struct option long_options[] = {{"loops", required_argument, 0, 'l'}, {"syscall", required_argument, 0, 's'}, {0, 0, 0, 0}}; int option_index = 0; while ((c = getopt_long(argc, argv, "l:s:", long_options, &option_index)) != -1) { switch (c) { case 'l': loops = atoi(optarg); if (loops <= 0) { show_usage(argv[0]); exit(1); } break; case 's': sys_val = atoi(optarg); if (sys_val < 0) { show_usage(argv[0]); exit(1); } break; default: fprintf(stderr, "unknown option: '%c'\n", c); show_usage(argv[0]); exit(1); } } switch (sys_val) { case (int)get_pid: for (i = 0; i < loops; i++) syscall(SYS_getpid); break; case (int)get_pid_opt: for (i = 0; i < loops; i++) do_getpidopt(); break; default: fprintf(stderr, "unknown syscall option: %d\n", sys_val); show_usage(argv[0]); exit(1); } printf("# Executed %'d calls\n", loops); return 0; }
2,554
25.894737
78
c
gvisor
gvisor-master/pkg/sentry/platform/systrap/sysmsg/atomic.h
// Copyright 2023 The gVisor 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. #ifndef THIRD_PARTY_GVISOR_PKG_SENTRY_PLATFORM_SYSTRAP_SYSMSG_ATOMIC_H_ #define THIRD_PARTY_GVISOR_PKG_SENTRY_PLATFORM_SYSTRAP_SYSMSG_ATOMIC_H_ #define atomic_load(p) __atomic_load_n(p, __ATOMIC_ACQUIRE) #define atomic_store(p, val) __atomic_store_n(p, val, __ATOMIC_RELEASE) #define atomic_compare_exchange(p, old, val) \ __atomic_compare_exchange_n(p, old, val, false, __ATOMIC_ACQ_REL, \ __ATOMIC_ACQUIRE) #define atomic_add(p, val) __atomic_add_fetch(p, val, __ATOMIC_ACQ_REL) #define atomic_sub(p, val) __atomic_sub_fetch(p, val, __ATOMIC_ACQ_REL) #endif // THIRD_PARTY_GVISOR_PKG_SENTRY_PLATFORM_SYSTRAP_SYSMSG_ATOMIC_H_
1,282
46.518519
75
h
gvisor
gvisor-master/pkg/sentry/platform/systrap/sysmsg/sighandler_amd64.c
// Copyright 2020 The gVisor 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. #define _GNU_SOURCE #include <asm/prctl.h> #include <asm/unistd_64.h> #include <errno.h> #include <linux/audit.h> #include <linux/futex.h> #include <linux/unistd.h> #include <signal.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdlib.h> #include <sys/prctl.h> #include <sys/ucontext.h> #include "atomic.h" #include "sysmsg.h" #include "sysmsg_offsets.h" #include "sysmsg_offsets_amd64.h" // TODO(b/271631387): These globals are shared between AMD64 and ARM64; move to // sysmsg_lib.c. struct arch_state __export_arch_state; uint64_t __export_stub_start; long __syscall(long n, long a1, long a2, long a3, long a4, long a5, long a6) { unsigned long ret; register long r10 __asm__("r10") = a4; register long r8 __asm__("r8") = a5; register long r9 __asm__("r9") = a6; __asm__ __volatile__("syscall" : "=a"(ret) : "a"(n), "D"(a1), "S"(a2), "d"(a3), "r"(r10), "r"(r8), "r"(r9) : "rcx", "r11", "memory"); return ret; } long sys_futex(uint32_t *addr, int op, int val, struct __kernel_timespec *tv, uint32_t *addr2, int val3) { return __syscall(__NR_futex, (long)addr, (long)op, (long)val, (long)tv, (long)addr2, (long)val3); } union csgsfs { uint64_t csgsfs; // REG_CSGSFS struct { uint16_t cs; uint16_t gs; uint16_t fs; uint16_t ss; }; }; static void gregs_to_ptregs(ucontext_t *ucontext, struct user_regs_struct *ptregs) { union csgsfs csgsfs = {.csgsfs = ucontext->uc_mcontext.gregs[REG_CSGSFS]}; // Set all registers except: // * fs_base and gs_base, because they can be only changed by arch_prctl. // * DS and ES are not used on x86_64. ptregs->r15 = ucontext->uc_mcontext.gregs[REG_R15]; ptregs->r14 = ucontext->uc_mcontext.gregs[REG_R14]; ptregs->r13 = ucontext->uc_mcontext.gregs[REG_R13]; ptregs->r12 = ucontext->uc_mcontext.gregs[REG_R12]; ptregs->rbp = ucontext->uc_mcontext.gregs[REG_RBP]; ptregs->rbx = ucontext->uc_mcontext.gregs[REG_RBX]; ptregs->r11 = ucontext->uc_mcontext.gregs[REG_R11]; ptregs->r10 = ucontext->uc_mcontext.gregs[REG_R10]; ptregs->r9 = ucontext->uc_mcontext.gregs[REG_R9]; ptregs->r8 = ucontext->uc_mcontext.gregs[REG_R8]; ptregs->rax = ucontext->uc_mcontext.gregs[REG_RAX]; ptregs->rcx = ucontext->uc_mcontext.gregs[REG_RCX]; ptregs->rdx = ucontext->uc_mcontext.gregs[REG_RDX]; ptregs->rsi = ucontext->uc_mcontext.gregs[REG_RSI]; ptregs->rdi = ucontext->uc_mcontext.gregs[REG_RDI]; ptregs->rip = ucontext->uc_mcontext.gregs[REG_RIP]; ptregs->eflags = ucontext->uc_mcontext.gregs[REG_EFL]; ptregs->rsp = ucontext->uc_mcontext.gregs[REG_RSP]; ptregs->cs = csgsfs.cs; ptregs->ss = csgsfs.ss; ptregs->fs = csgsfs.fs; ptregs->gs = csgsfs.gs; } static void ptregs_to_gregs(ucontext_t *ucontext, struct user_regs_struct *ptregs) { union csgsfs csgsfs = {.csgsfs = ucontext->uc_mcontext.gregs[REG_CSGSFS]}; ucontext->uc_mcontext.gregs[REG_R15] = ptregs->r15; ucontext->uc_mcontext.gregs[REG_R14] = ptregs->r14; ucontext->uc_mcontext.gregs[REG_R13] = ptregs->r13; ucontext->uc_mcontext.gregs[REG_R12] = ptregs->r12; ucontext->uc_mcontext.gregs[REG_RBP] = ptregs->rbp; ucontext->uc_mcontext.gregs[REG_RBX] = ptregs->rbx; ucontext->uc_mcontext.gregs[REG_R11] = ptregs->r11; ucontext->uc_mcontext.gregs[REG_R10] = ptregs->r10; ucontext->uc_mcontext.gregs[REG_R9] = ptregs->r9; ucontext->uc_mcontext.gregs[REG_R8] = ptregs->r8; ucontext->uc_mcontext.gregs[REG_RAX] = ptregs->rax; ucontext->uc_mcontext.gregs[REG_RCX] = ptregs->rcx; ucontext->uc_mcontext.gregs[REG_RDX] = ptregs->rdx; ucontext->uc_mcontext.gregs[REG_RSI] = ptregs->rsi; ucontext->uc_mcontext.gregs[REG_RDI] = ptregs->rdi; ucontext->uc_mcontext.gregs[REG_RIP] = ptregs->rip; ucontext->uc_mcontext.gregs[REG_EFL] = ptregs->eflags; ucontext->uc_mcontext.gregs[REG_RSP] = ptregs->rsp; csgsfs.cs = ptregs->cs; csgsfs.ss = ptregs->ss; csgsfs.fs = ptregs->fs; csgsfs.gs = ptregs->gs; ucontext->uc_mcontext.gregs[REG_CSGSFS] = csgsfs.csgsfs; } // get_fsbase writes the current thread's fsbase value to ptregs. static uint64_t get_fsbase(void) { uint64_t fsbase; if (__export_arch_state.fsgsbase) { asm volatile("rdfsbase %0" : "=r"(fsbase)); } else { int ret = __syscall(__NR_arch_prctl, ARCH_GET_FS, (long)&fsbase, 0, 0, 0, 0); if (ret) { panic(ret); } } return fsbase; } // set_fsbase sets the current thread's fsbase to the fsbase value in ptregs. static void set_fsbase(uint64_t fsbase) { if (__export_arch_state.fsgsbase) { asm volatile("wrfsbase %0" : : "r"(fsbase) : "memory"); } else { int ret = __syscall(__NR_arch_prctl, ARCH_SET_FS, fsbase, 0, 0, 0, 0); if (ret) { panic(ret); } } } // switch_context_amd64 is a wrapper of switch_context() which does checks // specific to amd64. struct thread_context *switch_context_amd64( struct sysmsg *sysmsg, struct thread_context *ctx, enum context_state new_context_state) { struct thread_context *old_ctx = sysmsg->context; for (;;) { ctx = switch_context(sysmsg, ctx, new_context_state); // After setting THREAD_STATE_NONE, syshandled can be interrupted by // SIGCHLD. In this case, we consider that the current context contains // the actual state and sighandler can take control on it. atomic_store(&sysmsg->state, THREAD_STATE_NONE); if (atomic_load(&ctx->interrupt) != 0) { atomic_store(&sysmsg->state, THREAD_STATE_PREP); // This context got interrupted while it was waiting in the queue. // Setup all the necessary bits to let the sentry know this context has // switched back because of it. atomic_store(&ctx->interrupt, 0); new_context_state = CONTEXT_STATE_FAULT; ctx->signo = SIGCHLD; ctx->siginfo.si_signo = SIGCHLD; ctx->ptregs.orig_rax = -1; } else { break; } } if (old_ctx != ctx || ctx->last_thread_id != sysmsg->thread_id) { ctx->fpstate_changed = 1; } return ctx; } static void prep_fpstate_for_sigframe(void *buf, uint32_t user_size, bool use_xsave); void __export_sighandler(int signo, siginfo_t *siginfo, void *_ucontext) { ucontext_t *ucontext = _ucontext; void *sp = sysmsg_sp(); struct sysmsg *sysmsg = sysmsg_addr(sp); if (sysmsg != sysmsg->self) panic(0xdeaddead); int32_t thread_state = atomic_load(&sysmsg->state); if (thread_state == THREAD_STATE_INITIALIZING) { // This thread was interrupted before it even had a context. return; } struct thread_context *ctx = sysmsg->context; // If the current thread is in syshandler, an interrupt has to be postponed, // because sysmsg can't be changed. if (signo == SIGCHLD && thread_state != THREAD_STATE_NONE) { return; } // Handle faults in syshandler. if ((signo == SIGSEGV || signo == SIGBUS) && sysmsg->fault_jump) { ucontext->uc_mcontext.gregs[REG_RIP] += sysmsg->fault_jump; sysmsg->fault_jump = 0; return; } long fs_base = get_fsbase(); ctx->signo = signo; ctx->siginfo = *siginfo; // syshandler sets THREAD_STATE_NONE right before it starts resuming a // context. It means the context contains the actual state, and the state of // the stub thread is incomplete. if (signo != SIGCHLD || ucontext->uc_mcontext.gregs[REG_RIP] < __export_stub_start) { ctx->ptregs.fs_base = fs_base; gregs_to_ptregs(ucontext, &ctx->ptregs); memcpy(ctx->fpstate, (uint8_t *)ucontext->uc_mcontext.fpregs, __export_arch_state.fp_len); atomic_store(&ctx->fpstate_changed, 0); } enum context_state ctx_state = CONTEXT_STATE_INVALID; switch (signo) { case SIGSYS: { ctx_state = CONTEXT_STATE_SYSCALL; // Check whether this syscall can be replaced on a function call or not. // If a syscall instruction set is "mov sysno, %eax, syscall", it can be // replaced on a function call which works much faster. // Look at pkg/sentry/usertrap for more details. if (siginfo->si_arch == AUDIT_ARCH_X86_64) { uint8_t *rip = (uint8_t *)ctx->ptregs.rip; // FIXME(b/144063246): Even if all five bytes before the syscall // instruction match the "mov sysno, %eax" instruction, they can be a // part of a longer instruction. Here is not easy way to decode x86 // instructions in reverse. uint64_t syscall_code_int[2]; uint8_t *syscall_code = (uint8_t *)&syscall_code_int[0]; // We need to receive 5 bytes before the syscall instruction, but they // are not aligned, so we can't read them atomically. Let's read them // twice. If the second copy will not contain the FAULT_OPCODE, this // will mean that the first copy is in the consistent state. for (int i = 0; i < 2; i++) { // fault_jump is set to the size of "mov (%rbx)" which is 3 bytes. atomic_store(&sysmsg->fault_jump, 3); asm volatile("movq (%1), %0\n" : "=a"(syscall_code_int[i]) : "b"(rip - 8) : "cc", "memory"); atomic_store(&sysmsg->fault_jump, 0); } // The mov instruction is 5 bytes: b8 <sysno, 4 bytes>. // The syscall instruction is 2 bytes: 0f 05. uint32_t sysno = *(uint32_t *)(syscall_code + 2); int need_trap = *(syscall_code + 6) == 0x0f && // syscall *(syscall_code + 7) == 0x05 && *(syscall_code + 1) == 0xb8 && // mov sysno, %eax sysno == siginfo->si_syscall && sysno == ctx->ptregs.rax; // Restart syscall if it has been patched by another thread. When a // syscall instruction set is replaced on a function call, all threads // have to call it via the function call. Otherwise the syscall will not // be restarted properly if it will be interrupted by signal. syscall_code = (uint8_t *)&syscall_code_int[1]; uint8_t syscall_opcode = *(syscall_code + 6); // A binary patch is built so that the first byte of the syscall // instruction is changed on the invalid instuction. If we meet this // case, this means that another thread has been patched this syscall // and we need to restart it. if (syscall_opcode == FAULT_OPCODE) { ucontext->uc_mcontext.gregs[REG_RIP] -= 7; return; } if (need_trap) { // This syscall can be replaced on the function call. ctx_state = CONTEXT_STATE_SYSCALL_NEED_TRAP; } } ctx->ptregs.orig_rax = ctx->ptregs.rax; ctx->ptregs.rax = (unsigned long)-ENOSYS; if (siginfo->si_arch != AUDIT_ARCH_X86_64) // gVisor doesn't support x32 system calls, so let's change the syscall // number so that it returns ENOSYS. ctx->ptregs.orig_rax += 0x86000000; break; } case SIGCHLD: case SIGSEGV: case SIGBUS: case SIGFPE: case SIGTRAP: case SIGILL: ctx->ptregs.orig_rax = -1; ctx_state = CONTEXT_STATE_FAULT; break; default: return; } ctx = switch_context_amd64(sysmsg, ctx, ctx_state); if (fs_base != ctx->ptregs.fs_base) { set_fsbase(ctx->ptregs.fs_base); } if (atomic_load(&ctx->fpstate_changed)) { prep_fpstate_for_sigframe( ctx->fpstate, __export_arch_state.fp_len, __export_arch_state.xsave_mode != XSAVE_MODE_FXSAVE); ucontext->uc_mcontext.fpregs = (void *)ctx->fpstate; } ptregs_to_gregs(ucontext, &ctx->ptregs); } void __syshandler() { struct sysmsg *sysmsg; asm volatile("movq %%gs:0, %0\n" : "=r"(sysmsg) : :); // SYSMSG_STATE_PREP is set to postpone interrupts. Look at // __export_sighandler for more details. int state = atomic_load(&sysmsg->state); if (state != THREAD_STATE_PREP) panic(state); struct thread_context *ctx = sysmsg->context; enum context_state ctx_state = CONTEXT_STATE_SYSCALL_TRAP; ctx->signo = SIGSYS; ctx->siginfo.si_addr = 0; ctx->siginfo.si_syscall = ctx->ptregs.rax; ctx->ptregs.rax = (unsigned long)-ENOSYS; long fs_base = get_fsbase(); ctx->ptregs.fs_base = fs_base; ctx = switch_context_amd64(sysmsg, ctx, ctx_state); // switch_context_amd64 changed sysmsg->state to THREAD_STATE_NONE, so we can // only resume the current process, all other actions are // prohibited after this point. if (fs_base != ctx->ptregs.fs_base) { set_fsbase(ctx->ptregs.fs_base); } } void __export_start(struct sysmsg *sysmsg, void *_ucontext) { init_new_thread(); asm volatile("movq %%gs:0, %0\n" : "=r"(sysmsg) : :); if (sysmsg->self != sysmsg) { panic(0xdeaddead); } struct thread_context *ctx = switch_context_amd64(sysmsg, NULL, CONTEXT_STATE_INVALID); restore_state(sysmsg, ctx, _ucontext); } // asm_restore_state is implemented in syshandler_amd64.S void asm_restore_state(); // On x86 restore_state jumps straight to user code and does not return. void restore_state(struct sysmsg *sysmsg, struct thread_context *ctx, void *unused) { set_fsbase(ctx->ptregs.fs_base); asm_restore_state(); } void verify_offsets_amd64() { #define PTREGS_OFFSET offsetof(struct thread_context, ptregs) BUILD_BUG_ON(offsetof_thread_context_ptregs != PTREGS_OFFSET); BUILD_BUG_ON(offsetof_thread_context_ptregs_r15 != (offsetof(struct user_regs_struct, r15) + PTREGS_OFFSET)); BUILD_BUG_ON(offsetof_thread_context_ptregs_r14 != (offsetof(struct user_regs_struct, r14) + PTREGS_OFFSET)); BUILD_BUG_ON(offsetof_thread_context_ptregs_r13 != (offsetof(struct user_regs_struct, r13) + PTREGS_OFFSET)); BUILD_BUG_ON(offsetof_thread_context_ptregs_r12 != (offsetof(struct user_regs_struct, r12) + PTREGS_OFFSET)); BUILD_BUG_ON(offsetof_thread_context_ptregs_rbp != (offsetof(struct user_regs_struct, rbp) + PTREGS_OFFSET)); BUILD_BUG_ON(offsetof_thread_context_ptregs_rbx != (offsetof(struct user_regs_struct, rbx) + PTREGS_OFFSET)); BUILD_BUG_ON(offsetof_thread_context_ptregs_r11 != (offsetof(struct user_regs_struct, r11) + PTREGS_OFFSET)); BUILD_BUG_ON(offsetof_thread_context_ptregs_r10 != (offsetof(struct user_regs_struct, r10) + PTREGS_OFFSET)); BUILD_BUG_ON(offsetof_thread_context_ptregs_r9 != (offsetof(struct user_regs_struct, r9) + PTREGS_OFFSET)); BUILD_BUG_ON(offsetof_thread_context_ptregs_r8 != (offsetof(struct user_regs_struct, r8) + PTREGS_OFFSET)); BUILD_BUG_ON(offsetof_thread_context_ptregs_rax != (offsetof(struct user_regs_struct, rax) + PTREGS_OFFSET)); BUILD_BUG_ON(offsetof_thread_context_ptregs_rcx != (offsetof(struct user_regs_struct, rcx) + PTREGS_OFFSET)); BUILD_BUG_ON(offsetof_thread_context_ptregs_rdx != (offsetof(struct user_regs_struct, rdx) + PTREGS_OFFSET)); BUILD_BUG_ON(offsetof_thread_context_ptregs_rsi != (offsetof(struct user_regs_struct, rsi) + PTREGS_OFFSET)); BUILD_BUG_ON(offsetof_thread_context_ptregs_rdi != (offsetof(struct user_regs_struct, rdi) + PTREGS_OFFSET)); BUILD_BUG_ON(offsetof_thread_context_ptregs_orig_rax != (offsetof(struct user_regs_struct, orig_rax) + PTREGS_OFFSET)); BUILD_BUG_ON(offsetof_thread_context_ptregs_rip != (offsetof(struct user_regs_struct, rip) + PTREGS_OFFSET)); BUILD_BUG_ON(offsetof_thread_context_ptregs_cs != (offsetof(struct user_regs_struct, cs) + PTREGS_OFFSET)); BUILD_BUG_ON(offsetof_thread_context_ptregs_eflags != (offsetof(struct user_regs_struct, eflags) + PTREGS_OFFSET)); BUILD_BUG_ON(offsetof_thread_context_ptregs_rsp != (offsetof(struct user_regs_struct, rsp) + PTREGS_OFFSET)); BUILD_BUG_ON(offsetof_thread_context_ptregs_ss != (offsetof(struct user_regs_struct, ss) + PTREGS_OFFSET)); BUILD_BUG_ON(offsetof_thread_context_ptregs_fs_base != (offsetof(struct user_regs_struct, fs_base) + PTREGS_OFFSET)); BUILD_BUG_ON(offsetof_thread_context_ptregs_gs_base != (offsetof(struct user_regs_struct, gs_base) + PTREGS_OFFSET)); BUILD_BUG_ON(offsetof_thread_context_ptregs_ds != (offsetof(struct user_regs_struct, ds) + PTREGS_OFFSET)); BUILD_BUG_ON(offsetof_thread_context_ptregs_es != (offsetof(struct user_regs_struct, es) + PTREGS_OFFSET)); BUILD_BUG_ON(offsetof_thread_context_ptregs_fs != (offsetof(struct user_regs_struct, fs) + PTREGS_OFFSET)); BUILD_BUG_ON(offsetof_thread_context_ptregs_gs != (offsetof(struct user_regs_struct, gs) + PTREGS_OFFSET)); #undef PTREGS_OFFSET } // asm/sigcontext.h conflicts with signal.h. struct __fpx_sw_bytes { uint32_t magic1; uint32_t extended_size; uint64_t xfeatures; uint32_t xstate_size; uint32_t padding[7]; }; struct __fpstate { uint16_t cwd; uint16_t swd; uint16_t twd; uint16_t fop; uint64_t rip; uint64_t rdp; uint32_t mxcsr; uint32_t mxcsr_mask; uint32_t st_space[32]; uint32_t xmm_space[64]; uint32_t reserved2[12]; struct __fpx_sw_bytes sw_reserved; }; // The kernel expects to see some additional info in an FPU state. More details // can be found in arch/x86/kernel/fpu/signal.c:check_xstate_in_sigframe. static void prep_fpstate_for_sigframe(void *buf, uint32_t user_size, bool use_xsave) { struct __fpstate *fpstate = buf; struct __fpx_sw_bytes *sw_bytes = &fpstate->sw_reserved; sw_bytes->magic1 = FP_XSTATE_MAGIC1; sw_bytes->extended_size = user_size + FP_XSTATE_MAGIC2_SIZE; sw_bytes->xfeatures = ~(0ULL); sw_bytes->xstate_size = user_size; *(uint32_t *)(buf + user_size) = use_xsave ? FP_XSTATE_MAGIC2 : 0; }
18,672
37.342916
80
c
gvisor
gvisor-master/pkg/sentry/platform/systrap/sysmsg/sighandler_arm64.c
// Copyright 2020 The gVisor 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. #define _GNU_SOURCE #include <asm/sigcontext.h> #include <asm/unistd.h> #include <errno.h> #include <linux/audit.h> #include <linux/futex.h> #include <linux/unistd.h> #include <signal.h> #include <stddef.h> #include <stdint.h> #include <stdlib.h> #include <sys/prctl.h> #include <sys/ucontext.h> #include "atomic.h" #include "sysmsg.h" #include "sysmsg_offsets.h" // TODO(b/271631387): These globals are shared between AMD64 and ARM64; move to // sysmsg_lib.c. struct arch_state __export_arch_state; uint64_t __export_stub_start; long __syscall(long n, long a1, long a2, long a3, long a4, long a5, long a6) { // ARM64 syscall interface passes the syscall number in x8 and the 6 arguments // in x0-x5. The return value is in x0. // // See: https://man7.org/linux/man-pages/man2/syscall.2.html register long x8 __asm__("x8") = n; register long x0 __asm__("x0") = a1; register long x1 __asm__("x1") = a2; register long x2 __asm__("x2") = a3; register long x3 __asm__("x3") = a4; register long x4 __asm__("x4") = a5; register long x5 __asm__("x5") = a6; __asm__ __volatile__("svc #0" : "=r"(x0) : "r"(x8), "0"(x0), "r"(x1), "r"(x2), "r"(x3), "r"(x4), "r"(x5) : "memory", "cc"); return x0; } static __inline void set_tls(uint64_t tls) { __asm__("msr tpidr_el0,%0" : : "r"(tls)); } static __inline uint64_t get_tls() { uint64_t tls; __asm__("mrs %0,tpidr_el0" : "=r"(tls)); return tls; } long sys_futex(uint32_t *addr, int op, int val, struct __kernel_timespec *tv, uint32_t *addr2, int val3) { return __syscall(__NR_futex, (long)addr, (long)op, (long)val, (long)tv, (long)addr2, (long)val3); } static void gregs_to_ptregs(ucontext_t *ucontext, struct user_regs_struct *ptregs) { // Set all registers. for (int i = 0; i < 31; i++ ) { ptregs->regs[i] = ucontext->uc_mcontext.regs[i]; } ptregs->sp = ucontext->uc_mcontext.sp; ptregs->pc = ucontext->uc_mcontext.pc; ptregs->pstate = ucontext->uc_mcontext.pstate; } static void ptregs_to_gregs(ucontext_t *ucontext, struct user_regs_struct *ptregs) { for (int i = 0; i < 31; i++ ) { ucontext->uc_mcontext.regs[i] = ptregs->regs[i]; } ucontext->uc_mcontext.sp = ptregs->sp; ucontext->uc_mcontext.pc = ptregs->pc; ucontext->uc_mcontext.pstate = ptregs->pstate; } void __export_start(struct sysmsg *sysmsg, void *_ucontext) { panic(0x11111111); } void __export_sighandler(int signo, siginfo_t *siginfo, void *_ucontext) { ucontext_t *ucontext = _ucontext; void *sp = sysmsg_sp(); struct sysmsg *sysmsg = sysmsg_addr(sp); if (sysmsg != sysmsg->self) panic(0xdeaddead); int32_t thread_state = atomic_load(&sysmsg->state); uint32_t ctx_state = CONTEXT_STATE_INVALID; struct thread_context *ctx = NULL, *old_ctx = NULL; if (thread_state == THREAD_STATE_INITIALIZING) { // Find a new context and exit to restore it. init_new_thread(); goto init; } ctx = sysmsg->context; old_ctx = sysmsg->context; ctx->signo = signo; gregs_to_ptregs(ucontext, &ctx->ptregs); // Signal frames for ARM64 include 8 byte magic header before the floating // point context. // // See: arch/arm64/include/uapi/asm/sigcontext.h const uint64_t kSigframeMagicHeaderLen = sizeof(struct _aarch64_ctx); // Verify the header. if (((uint32_t *)&ucontext->uc_mcontext.__reserved)[0] != FPSIMD_MAGIC) { panic(0xbadf); } uint8_t *fpStatePointer = (uint8_t *)&ucontext->uc_mcontext.__reserved + kSigframeMagicHeaderLen; memcpy(ctx->fpstate, fpStatePointer, __export_arch_state.fp_len); ctx->tls = get_tls(); ctx->siginfo = *siginfo; switch (signo) { case SIGSYS: { ctx_state = CONTEXT_STATE_SYSCALL; if (siginfo->si_arch != AUDIT_ARCH_AARCH64) { // gVisor doesn't support x32 system calls, so let's change the syscall // number so that it returns ENOSYS. The value added here is just a // random large number which is large enough to not match any existing // syscall number in linux. ctx->ptregs.regs[8] += 0x86000000; } break; } case SIGCHLD: case SIGSEGV: case SIGBUS: case SIGFPE: case SIGTRAP: case SIGILL: ctx_state = CONTEXT_STATE_FAULT; break; default: return; } init: for (;;) { ctx = switch_context(sysmsg, ctx, ctx_state); if (atomic_load(&ctx->interrupt) != 0) { // This context got interrupted while it was waiting in the queue. // Setup all the necessary bits to let the sentry know this context has // switched back because of it. atomic_store(&ctx->interrupt, 0); ctx_state = CONTEXT_STATE_FAULT; ctx->signo = SIGCHLD; ctx->siginfo.si_signo = SIGCHLD; } else { break; } } if (old_ctx != ctx || ctx->last_thread_id != sysmsg->thread_id) { ctx->fpstate_changed = 1; } restore_state(sysmsg, ctx, _ucontext); } // On ARM restore_state sets up a correct restore from the sighandler by // populating _ucontext. void restore_state(struct sysmsg *sysmsg, struct thread_context *ctx, void *_ucontext) { ucontext_t *ucontext = _ucontext; struct fpsimd_context *fpctx = (struct fpsimd_context *)&ucontext->uc_mcontext.__reserved; uint8_t *fpStatePointer = (uint8_t *)&fpctx->fpsr; if (atomic_load(&ctx->fpstate_changed)) { memcpy(fpStatePointer, ctx->fpstate, __export_arch_state.fp_len); } ptregs_to_gregs(ucontext, &ctx->ptregs); set_tls(ctx->tls); atomic_store(&sysmsg->state, THREAD_STATE_NONE); }
6,267
30.497487
86
c
gvisor
gvisor-master/pkg/sentry/platform/systrap/sysmsg/sysmsg.h
// Copyright 2020 The gVisor 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. #ifndef THIRD_PARTY_GVISOR_PKG_SENTRY_PLATFORM_SYSTRAP_SYSMSG_SYSMSG_H_ #define THIRD_PARTY_GVISOR_PKG_SENTRY_PLATFORM_SYSTRAP_SYSMSG_SYSMSG_H_ #include <stdint.h> #include <sys/types.h> #include <sys/user.h> #include "sysmsg_offsets.h" // NOLINT #if defined(__x86_64__) // LINT.IfChange struct arch_state { uint32_t xsave_mode; uint32_t fp_len; uint32_t fsgsbase; }; // LINT.ThenChange(sysmsg_amd64.go) #else // LINT.IfChange struct arch_state { uint32_t fp_len; }; // LINT.ThenChange(sysmsg_arm64.go) #endif // LINT.IfChange enum thread_state { THREAD_STATE_NONE, THREAD_STATE_DONE, THREAD_STATE_PREP, THREAD_STATE_ASLEEP, THREAD_STATE_INITIALIZING, }; struct thread_context; // sysmsg contains the current state of the sysmsg thread. See: sysmsg.go:Msg struct sysmsg { struct sysmsg *self; uint64_t ret_addr; uint64_t syshandler; uint64_t syshandler_stack; uint64_t app_stack; uint32_t interrupt; uint32_t state; struct thread_context *context; // The fields above have offsets defined in sysmsg_offsets*.h int32_t fault_jump; int32_t err; int32_t err_line; uint64_t debug; uint32_t thread_id; }; enum context_state { CONTEXT_STATE_NONE, CONTEXT_STATE_SYSCALL, CONTEXT_STATE_FAULT, CONTEXT_STATE_SYSCALL_TRAP, CONTEXT_STATE_SYSCALL_NEED_TRAP, CONTEXT_STATE_INVALID, }; // thread_context contains the current context of the sysmsg thread. // See sysmsg.go:SysThreadContext struct thread_context { uint8_t fpstate[MAX_FPSTATE_LEN]; uint64_t fpstate_changed; struct user_regs_struct ptregs; // The fields above have offsets defined in sysmsg_offsets*.h siginfo_t siginfo; int64_t signo; uint32_t state; uint32_t interrupt; uint32_t thread_id; uint32_t last_thread_id; uint32_t sentry_fast_path; uint32_t acked; uint64_t tls; uint64_t debug; }; #ifndef PAGE_SIZE #define PAGE_SIZE 4096 #endif #define PER_THREAD_MEM_SIZE (8 * PAGE_SIZE) #define GUARD_SIZE (PAGE_SIZE) #define MSG_OFFSET_FROM_START (PER_THREAD_MEM_SIZE - PAGE_SIZE) #define SPINNING_QUEUE_MEM_SIZE PAGE_SIZE // LINT.ThenChange(sysmsg.go) #define FAULT_OPCODE 0x06 // "push %es" on x32 and invalid opcode on x64. #define __stringify_1(x...) #x #define __stringify(x...) __stringify_1(x) #define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2 * !!(condition)])) extern uint64_t __export_pr_sched_core; extern uint64_t __export_deep_sleep_timeout; extern struct arch_state __export_arch_state; struct context_queue; extern struct context_queue *__export_context_queue_addr; // NOLINTBEGIN(runtime/int) static void *sysmsg_sp() { volatile int p; void *sp = (struct sysmsg *)(((long)&p) / PER_THREAD_MEM_SIZE * PER_THREAD_MEM_SIZE); _Static_assert( sizeof(struct sysmsg) < (PER_THREAD_MEM_SIZE - MSG_OFFSET_FROM_START), "The sysmsg structure is too big."); return sp; } static struct sysmsg *sysmsg_addr(void *sp) { return (struct sysmsg *)(sp + MSG_OFFSET_FROM_START); } long __syscall(long n, long a1, long a2, long a3, long a4, long a5, long a6); struct __kernel_timespec; long sys_futex(uint32_t *addr, int op, int val, struct __kernel_timespec *tv, uint32_t *addr2, int val3); static void __panic(int err, long line) { void *sp = sysmsg_sp(); struct sysmsg *sysmsg = sysmsg_addr(sp); struct thread_context *ctx = sysmsg->context; sysmsg->err = err; sysmsg->err_line = line; // Wake up the goroutine waiting on the current context. __atomic_store_n(&ctx->state, CONTEXT_STATE_FAULT, __ATOMIC_RELEASE); sys_futex(&ctx->state, FUTEX_WAKE, 1, NULL, NULL, 666); // crash the stub process. // // Normal user processes cannot map addresses lower than vm.mmap_min_addr // which is usually > 4K. So writing to an address <4K should crash the // process with a segfault. #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Warray-bounds" *(int *)(line % 4096) = err; #pragma GCC diagnostic pop } void memcpy(uint8_t *dest, uint8_t *src, size_t n); void __export_start(struct sysmsg *sysmsg, void *_ucontext); void restore_state(struct sysmsg *sysmsg, struct thread_context *ctx, void *_ucontext); struct thread_context *switch_context(struct sysmsg *sysmsg, struct thread_context *ctx, enum context_state new_context_state); int wait_state(struct sysmsg *sysmsg, enum thread_state new_thread_state); void init_new_thread(void); #define panic(err) __panic(err, __LINE__) // NOLINTEND(runtime/int) #endif // THIRD_PARTY_GVISOR_PKG_SENTRY_PLATFORM_SYSTRAP_SYSMSG_SYSMSG_H_
5,218
27.519126
80
h
gvisor
gvisor-master/pkg/sentry/platform/systrap/sysmsg/sysmsg_lib.c
// Copyright 2022 The gVisor 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. #define _GNU_SOURCE #include <errno.h> #include <linux/futex.h> #include <linux/unistd.h> #include <signal.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdlib.h> #include "atomic.h" #include "sysmsg.h" // __export_deep_sleep_timeout is the timeout after which the stub thread stops // polling and fall asleep. uint64_t __export_deep_sleep_timeout; // LINT.IfChange #define MAX_GUEST_CONTEXTS (4095) #define MAX_CONTEXT_QUEUE_ENTRIES (MAX_GUEST_CONTEXTS + 1) #define INVALID_CONTEXT_ID 0xfefefefe #define INVALID_THREAD_ID 0xfefefefe // Each element of a context_queue ring buffer is a sum of its index shifted by // CQ_INDEX_SHIFT and context_id. #define CQ_INDEX_SHIFT 32 #define CQ_CONTEXT_MASK ((1UL << CQ_INDEX_SHIFT) - 1) // See systrap/context_queue.go struct context_queue { uint32_t start; uint32_t end; uint32_t num_active_threads; uint32_t num_threads_to_wakeup; uint32_t num_active_contexts; uint32_t num_awake_contexts; uint64_t fast_path_disalbed_ts; uint32_t fast_path_failed_in_row; uint32_t fast_path_disabled; uint64_t ringbuffer[MAX_CONTEXT_QUEUE_ENTRIES]; }; struct context_queue *__export_context_queue_addr; // LINT.ThenChange(../context_queue.go) uint32_t is_empty(struct context_queue *queue) { return atomic_load(&queue->start) == atomic_load(&queue->end); } int32_t queued_contexts(struct context_queue *queue) { return (atomic_load(&queue->end) + MAX_CONTEXT_QUEUE_ENTRIES - atomic_load(&queue->start)) % MAX_CONTEXT_QUEUE_ENTRIES; } #if defined(__x86_64__) static __inline__ unsigned long rdtsc(void) { unsigned h, l; __asm__ __volatile__("rdtsc" : "=a"(l), "=d"(h)); return ((unsigned long)l) | (((unsigned long)h) << 32); } static __inline__ void spinloop(void) { asm("pause"); } #elif defined(__aarch64__) static __inline__ unsigned long rdtsc(void) { long val; asm volatile("mrs %0, cntvct_el0" : "=r"(val)); return val; } static __inline__ void spinloop(void) { asm volatile("yield" : : : "memory"); } #endif void *__export_context_region; static struct thread_context *thread_context_addr(uint32_t tcid) { return (struct thread_context *)(__export_context_region + tcid * ALLOCATED_SIZEOF_THREAD_CONTEXT_STRUCT); } void memcpy(uint8_t *dest, uint8_t *src, size_t n) { for (size_t i = 0; i < n; i += 1) { dest[i] = src[i]; } } // The spinning queue is a queue of spinning threads. It solves the // fragmentation problem. The idea is to minimize the number of threads // processing requests. We can't control how system threads are scheduled, so // can't distribute requests efficiently. The spinning queue emulates virtual // threads sorted by their spinning time. // // This queue is lock-less to be sure that any thread scheduled out // from CPU doesn't block others. #define SPINNING_QUEUE_SIZE 128 // MAX_SPINNING_THREADS is half of SPINNING_QUEUE_SIZE to be sure that the tail // doesn't catch the head. More details are in spinning_queue_remove_first. #define MAX_SPINNING_THREADS (SPINNING_QUEUE_SIZE / 2) struct spinning_queue { uint32_t start; uint32_t end; uint64_t start_times[SPINNING_QUEUE_SIZE]; }; struct spinning_queue *__export_spinning_queue_addr; // spinning_queue_push adds a new thread to the queue. It returns false if the // queue if full. static bool spinning_queue_push() __attribute__((warn_unused_result)); static bool spinning_queue_push(void) { struct spinning_queue *queue = __export_spinning_queue_addr; uint32_t idx, start, end; BUILD_BUG_ON(sizeof(struct spinning_queue) > SPINNING_QUEUE_MEM_SIZE); end = atomic_add(&queue->end, 1); start = atomic_load(&queue->start); if (end - start > MAX_SPINNING_THREADS) { atomic_sub(&queue->end, 1); return false; } idx = end - 1; atomic_store(&queue->start_times[idx % SPINNING_QUEUE_SIZE], rdtsc()); return true; } // spinning_queue_pop() removes one thread from a queue that has been spinning // the shortest time. static void spinning_queue_pop() { struct spinning_queue *queue = __export_spinning_queue_addr; atomic_sub(&queue->end, 1); } // spinning_queue_remove_first removes one thread from a queue that has been // spinning longer than others and longer than a specified timeout. // // If `timeout` is zero, it always removes one element and never returns false. // // Returns true if one thread has been removed from the queue. static bool spinning_queue_remove_first(uint64_t timeout) __attribute__((warn_unused_result)); static bool spinning_queue_remove_first(uint64_t timeout) { struct spinning_queue *queue = __export_spinning_queue_addr; uint64_t ts; uint32_t idx; while (1) { idx = atomic_load(&queue->start); ts = atomic_load(&queue->start_times[idx % SPINNING_QUEUE_SIZE]); if (ts == 0 && timeout == 0) continue; if (ts == 0 || rdtsc() - ts < timeout) return false; // The current thread is still in a queue and the length of the queue is // twice of the maximum number of threads, so we can zero the element and be // sure that nobody is trying to set it in a non-zero value. atomic_store(&queue->start_times[idx % SPINNING_QUEUE_SIZE], 0); if (atomic_compare_exchange(&queue->start, &idx, idx + 1)) { break; } } return true; } struct thread_context *queue_get_context(struct sysmsg *sysmsg) { struct context_queue *queue = __export_context_queue_addr; // Indexes should not jump when start or end are overflowed. BUILD_BUG_ON(UINT32_MAX % MAX_CONTEXT_QUEUE_ENTRIES != MAX_CONTEXT_QUEUE_ENTRIES - 1); while (!is_empty(queue)) { uint64_t idx = atomic_load(&queue->start); uint32_t next = idx % MAX_CONTEXT_QUEUE_ENTRIES; uint64_t v = atomic_load(&queue->ringbuffer[next]); // We need to check the index to be sure that a ring buffer hasn't been // recycled. if ((v >> CQ_INDEX_SHIFT) != idx) continue; if (!atomic_compare_exchange(&queue->ringbuffer[next], &v, INVALID_CONTEXT_ID)) { continue; } uint32_t context_id = v & CQ_CONTEXT_MASK; if (context_id == INVALID_CONTEXT_ID) continue; atomic_add(&queue->start, 1); if (context_id > MAX_GUEST_CONTEXTS) { panic(context_id); } struct thread_context *ctx = thread_context_addr(context_id); sysmsg->context = ctx; atomic_store(&ctx->acked, 1); atomic_store(&ctx->thread_id, sysmsg->thread_id); return ctx; } return NULL; } #define FAILED_FAST_PATH_LIMIT 5 #define FAILED_FAST_PATH_TIMEOUT 20000000 // 10ms // get_context_fast sets nr_active_threads_p only if it deactivates the thread. static struct thread_context *get_context_fast(struct sysmsg *sysmsg, struct context_queue *queue, uint32_t *nr_active_threads_p) { uint32_t nr_active_threads, nr_awake_contexts; if (!spinning_queue_push()) return NULL; while (1) { struct thread_context *ctx; ctx = queue_get_context(sysmsg); if (ctx) { atomic_store(&queue->fast_path_failed_in_row, 0); spinning_queue_pop(); return ctx; } if (atomic_load(&queue->fast_path_disabled) != 0) { if (!spinning_queue_remove_first(0)) panic(0); break; } nr_active_threads = atomic_load(&queue->num_active_threads); nr_awake_contexts = atomic_load(&queue->num_awake_contexts); if (nr_awake_contexts < nr_active_threads) { if (atomic_compare_exchange(&queue->num_active_threads, &nr_active_threads, nr_active_threads - 1)) { nr_active_threads -= 1; if (!spinning_queue_remove_first(0)) panic(0); *nr_active_threads_p = nr_active_threads; break; } } if (spinning_queue_remove_first(__export_deep_sleep_timeout)) { uint32_t nr = atomic_add(&queue->fast_path_failed_in_row, 1); if (nr >= FAILED_FAST_PATH_LIMIT) { atomic_store(&queue->fast_path_disalbed_ts, rdtsc()); } break; } spinloop(); } return NULL; } #define NR_IF_THREAD_IS_ACTIVE (~0) static bool try_to_dec_threads_to_wakeup(struct context_queue *queue) { while (1) { uint32_t nr = atomic_load(&queue->num_threads_to_wakeup); if (nr == 0) { return false; } if (atomic_compare_exchange(&queue->num_threads_to_wakeup, &nr, nr - 1)) { return true; }; } } void init_new_thread() { struct context_queue *queue = __export_context_queue_addr; atomic_add(&queue->num_active_threads, 1); try_to_dec_threads_to_wakeup(queue); } // get_context retrieves a context that is ready to be restored to the user. // This populates sysmsg->thread_context_id. struct thread_context *get_context(struct sysmsg *sysmsg) { struct context_queue *queue = __export_context_queue_addr; uint32_t nr_active_threads; for (;;) { struct thread_context *ctx; // Change sysmsg thread state just to indicate thread is not asleep. atomic_store(&sysmsg->state, THREAD_STATE_PREP); ctx = queue_get_context(sysmsg); if (ctx) { atomic_store(&queue->fast_path_failed_in_row, 0); return ctx; } uint64_t slow_path_ts = atomic_load(&queue->fast_path_disalbed_ts); bool fast_path_enabled = true; if (!slow_path_ts) { if (rdtsc() - slow_path_ts > FAILED_FAST_PATH_TIMEOUT) { atomic_store(&queue->fast_path_failed_in_row, 0); atomic_store(&queue->fast_path_disalbed_ts, 0); } else { fast_path_enabled = false; } } if (atomic_load(&queue->fast_path_disabled) != 0) { fast_path_enabled = false; } nr_active_threads = NR_IF_THREAD_IS_ACTIVE; if (fast_path_enabled) { ctx = get_context_fast(sysmsg, queue, &nr_active_threads); if (ctx) return ctx; } if (nr_active_threads == NR_IF_THREAD_IS_ACTIVE) { nr_active_threads = atomic_sub(&queue->num_active_threads, 1); } atomic_store(&sysmsg->state, THREAD_STATE_ASLEEP); uint32_t nr_active_contexts = atomic_load(&queue->num_active_contexts); // We have to make another attempt to get a context here to prevent TOCTTOU // races with waitOnState and kickSysmsgThread. There are two assumptions: // * If the queue isn't empty, one or more threads have to be active. // * A new thread isn't kicked, if the number of active threads are not less // than a number of active contexts. if (nr_active_threads < nr_active_contexts) { ctx = queue_get_context(sysmsg); if (ctx) { atomic_store(&sysmsg->state, THREAD_STATE_PREP); atomic_add(&queue->num_active_threads, 1); return ctx; } } while (1) { if (!try_to_dec_threads_to_wakeup(queue)) { sys_futex(&queue->num_threads_to_wakeup, FUTEX_WAIT, 0, NULL, NULL, 0); continue; } // Mark this thread as being active only if it can get a context. ctx = queue_get_context(sysmsg); if (ctx) { atomic_store(&sysmsg->state, THREAD_STATE_PREP); atomic_add(&queue->num_active_threads, 1); return ctx; } } } } // switch_context signals the sentry that the old context is ready to be worked // on and retrieves a new context to switch to. struct thread_context *switch_context(struct sysmsg *sysmsg, struct thread_context *ctx, enum context_state new_context_state) { struct context_queue *queue = __export_context_queue_addr; if (ctx) { atomic_sub(&queue->num_active_contexts, 1); atomic_store(&ctx->thread_id, INVALID_THREAD_ID); atomic_store(&ctx->last_thread_id, sysmsg->thread_id); atomic_store(&ctx->state, new_context_state); if (atomic_load(&ctx->sentry_fast_path) == 0) { int ret = sys_futex(&ctx->state, FUTEX_WAKE, 1, NULL, NULL, 0); if (ret < 0) { panic(ret); } } } return get_context(sysmsg); } void verify_offsets() { BUILD_BUG_ON(offsetof_sysmsg_self != offsetof(struct sysmsg, self)); BUILD_BUG_ON(offsetof_sysmsg_ret_addr != offsetof(struct sysmsg, ret_addr)); BUILD_BUG_ON(offsetof_sysmsg_syshandler != offsetof(struct sysmsg, syshandler)); BUILD_BUG_ON(offsetof_sysmsg_syshandler_stack != offsetof(struct sysmsg, syshandler_stack)); BUILD_BUG_ON(offsetof_sysmsg_app_stack != offsetof(struct sysmsg, app_stack)); BUILD_BUG_ON(offsetof_sysmsg_interrupt != offsetof(struct sysmsg, interrupt)); BUILD_BUG_ON(offsetof_sysmsg_state != offsetof(struct sysmsg, state)); BUILD_BUG_ON(offsetof_sysmsg_context != offsetof(struct sysmsg, context)); BUILD_BUG_ON(offsetof_thread_context_fpstate != offsetof(struct thread_context, fpstate)); BUILD_BUG_ON(offsetof_thread_context_fpstate_changed != offsetof(struct thread_context, fpstate_changed)); BUILD_BUG_ON(offsetof_thread_context_ptregs != offsetof(struct thread_context, ptregs)); BUILD_BUG_ON(kTHREAD_STATE_NONE != THREAD_STATE_NONE); BUILD_BUG_ON(sizeof(struct thread_context) > ALLOCATED_SIZEOF_THREAD_CONTEXT_STRUCT); }
13,843
32.601942
80
c
gvisor
gvisor-master/pkg/sentry/platform/systrap/sysmsg/sysmsg_offsets.h
// Copyright 2020 The gVisor 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. #ifndef THIRD_PARTY_GVISOR_PKG_SENTRY_PLATFORM_SYSTRAP_SYSMSG_SYSMSG_OFFSETS_H_ #define THIRD_PARTY_GVISOR_PKG_SENTRY_PLATFORM_SYSTRAP_SYSMSG_SYSMSG_OFFSETS_H_ // FAULT_OPCODE is the opcode of the invalid instruction that is used to replace // the first byte of the syscall instruction. More details in the description // for the pkg/sentry/platform/systrap/usertrap package. #define FAULT_OPCODE 0x06 // LINT.IfChange #define MAX_FPSTATE_LEN 3584 // Note: To be explicit, 2^12 = 4096; if ALLOCATED_SIZEOF_THREAD_CONTEXT_STRUCT // is changed, make sure to change the code that relies on the bitshift. #define ALLOCATED_SIZEOF_THREAD_CONTEXT_STRUCT 4096 #define THREAD_CONTEXT_STRUCT_BITSHIFT 12 // LINT.ThenChange(sysmsg.go) // LINT.IfChange // Define offsets in the struct sysmsg to use them in assembly files. // Each offset has to have BUILD_BUG_ON in sighandler.c. #define offsetof_sysmsg_self 0x0 #define offsetof_sysmsg_ret_addr 0x8 #define offsetof_sysmsg_syshandler 0x10 #define offsetof_sysmsg_syshandler_stack 0x18 #define offsetof_sysmsg_app_stack 0x20 #define offsetof_sysmsg_interrupt 0x28 #define offsetof_sysmsg_state 0x2c #define offsetof_sysmsg_context 0x30 #define offsetof_thread_context_fpstate 0x0 #define offsetof_thread_context_fpstate_changed MAX_FPSTATE_LEN #define offsetof_thread_context_ptregs 0x8 + MAX_FPSTATE_LEN #define kTHREAD_STATE_NONE 0 #define kTHREAD_STATE_INTERRUPT 3 // LINT.ThenChange(sysmsg.h, sysmsg_lib.c) #endif // THIRD_PARTY_GVISOR_PKG_SENTRY_PLATFORM_SYSTRAP_SYSMSG_SYSMSG_OFFSETS_H_
2,144
38.722222
82
h
gvisor
gvisor-master/pkg/sentry/platform/systrap/sysmsg/sysmsg_offsets_amd64.h
// Copyright 2022 The gVisor 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. #ifndef THIRD_PARTY_GVISOR_PKG_SENTRY_PLATFORM_SYSTRAP_SYSMSG_SYSMSG_OFFSETS_AMD64_H_ #define THIRD_PARTY_GVISOR_PKG_SENTRY_PLATFORM_SYSTRAP_SYSMSG_SYSMSG_OFFSETS_AMD64_H_ // LINT.IfChange #define offsetof_arch_state_xsave_mode (0x0) #define offsetof_arch_state_fpLen (0x4) #define offsetof_arch_state_fsgsbase (0x8) #define XSAVE_MODE_FXSAVE (0x0) #define XSAVE_MODE_XSAVE (0x1) #define XSAVE_MODE_XSAVEOPT (0x2) #define XSAVE_MODE_XSAVEC (0x3) // LINT.ThenChange(sysmsg.h, sysmsg_amd64.go) // LINT.IfChange #define offsetof_thread_context_ptregs_r15 \ (0x0 + offsetof_thread_context_ptregs) #define offsetof_thread_context_ptregs_r14 \ (0x8 + offsetof_thread_context_ptregs) #define offsetof_thread_context_ptregs_r13 \ (0x10 + offsetof_thread_context_ptregs) #define offsetof_thread_context_ptregs_r12 \ (0x18 + offsetof_thread_context_ptregs) #define offsetof_thread_context_ptregs_rbp \ (0x20 + offsetof_thread_context_ptregs) #define offsetof_thread_context_ptregs_rbx \ (0x28 + offsetof_thread_context_ptregs) #define offsetof_thread_context_ptregs_r11 \ (0x30 + offsetof_thread_context_ptregs) #define offsetof_thread_context_ptregs_r10 \ (0x38 + offsetof_thread_context_ptregs) #define offsetof_thread_context_ptregs_r9 \ (0x40 + offsetof_thread_context_ptregs) #define offsetof_thread_context_ptregs_r8 \ (0x48 + offsetof_thread_context_ptregs) #define offsetof_thread_context_ptregs_rax \ (0x50 + offsetof_thread_context_ptregs) #define offsetof_thread_context_ptregs_rcx \ (0x58 + offsetof_thread_context_ptregs) #define offsetof_thread_context_ptregs_rdx \ (0x60 + offsetof_thread_context_ptregs) #define offsetof_thread_context_ptregs_rsi \ (0x68 + offsetof_thread_context_ptregs) #define offsetof_thread_context_ptregs_rdi \ (0x70 + offsetof_thread_context_ptregs) #define offsetof_thread_context_ptregs_orig_rax \ (0x78 + offsetof_thread_context_ptregs) #define offsetof_thread_context_ptregs_rip \ (0x80 + offsetof_thread_context_ptregs) #define offsetof_thread_context_ptregs_cs \ (0x88 + offsetof_thread_context_ptregs) #define offsetof_thread_context_ptregs_eflags \ (0x90 + offsetof_thread_context_ptregs) #define offsetof_thread_context_ptregs_rsp \ (0x98 + offsetof_thread_context_ptregs) #define offsetof_thread_context_ptregs_ss \ (0xa0 + offsetof_thread_context_ptregs) #define offsetof_thread_context_ptregs_fs_base \ (0xa8 + offsetof_thread_context_ptregs) #define offsetof_thread_context_ptregs_gs_base \ (0xb0 + offsetof_thread_context_ptregs) #define offsetof_thread_context_ptregs_ds \ (0xb8 + offsetof_thread_context_ptregs) #define offsetof_thread_context_ptregs_es \ (0xc0 + offsetof_thread_context_ptregs) #define offsetof_thread_context_ptregs_fs \ (0xc8 + offsetof_thread_context_ptregs) #define offsetof_thread_context_ptregs_gs \ (0xd0 + offsetof_thread_context_ptregs) // LINT.ThenChange(sysmsg.h, sighandler_amd64.c) #endif // THIRD_PARTY_GVISOR_PKG_SENTRY_PLATFORM_SYSTRAP_SYSMSG_SYSMSG_OFFSETS_AMD64_H_
3,606
39.077778
88
h